moi-computer 0.13.1-next.3 → 0.13.1-next.4

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.
Files changed (82) hide show
  1. package/client/app/app-provider.tsx +14 -20
  2. package/client/app/app-router.tsx +5 -8
  3. package/client/app/routes/workspace-route.tsx +28 -11
  4. package/client/app/shell/sidebar-layout.tsx +5 -10
  5. package/client/features/app-settings/api.ts +3 -3
  6. package/client/features/applets/applet-cache.ts +1 -2
  7. package/client/features/applets/use-applet.ts +18 -20
  8. package/client/features/chat/chat-store.ts +1 -1
  9. package/client/features/chat/connection/chat-connection.ts +25 -68
  10. package/client/features/chat/connection/chat-frames.ts +20 -32
  11. package/client/features/chat/sessions/api.ts +2 -2
  12. package/client/features/collab/presence/client.ts +63 -83
  13. package/client/features/collab/presence/provider.tsx +8 -2
  14. package/client/features/dev/chat-states-page.tsx +1 -1
  15. package/client/features/dev/harness-debug-page.tsx +2 -2
  16. package/client/features/scratchpad/scratchpad.tsx +29 -20
  17. package/client/features/views/api.ts +5 -6
  18. package/client/features/workspace/api.ts +6 -11
  19. package/client/features/workspace/harness-transition.ts +3 -5
  20. package/client/features/workspace/remote.ts +9 -0
  21. package/client/features/workspace/settings/use-env-vars.ts +4 -4
  22. package/client/features/workspace/use-workspace-navigation.ts +1 -1
  23. package/client/features/workspace/use-workspace-socket.ts +51 -0
  24. package/client/features/workspace/workspace-content.tsx +3 -7
  25. package/client/features/workspace/workspace-layout-context.tsx +6 -13
  26. package/client/features/workspace/workspace-state.ts +17 -6
  27. package/client/runtime/app-context.ts +2 -2
  28. package/client/runtime/app-events.ts +75 -0
  29. package/client/runtime/reconnecting-socket.ts +115 -0
  30. package/client/runtime/{use-workspace-events.ts → use-client-events.ts} +9 -10
  31. package/dist/{chunk-f44cs6mw.js → chunk-0t8m1ehd.js} +2 -2
  32. package/dist/chunk-851bx8ss.js +72 -0
  33. package/dist/{chunk-xj1pjhng.js → chunk-c8g5x288.js} +1 -1
  34. package/dist/chunk-cty37f3v.js +1 -0
  35. package/dist/chunk-dy6f6h3e.js +5 -0
  36. package/dist/chunk-j6928pwm.js +1 -0
  37. package/dist/{chunk-r95acex1.js → chunk-k32585ne.js} +70 -70
  38. package/dist/chunk-qtkv7hp8.js +2 -0
  39. package/dist/chunk-rh58dc0y.js +2 -0
  40. package/dist/{chunk-a865c7x4.js → chunk-wjbejzek.js} +1 -1
  41. package/dist/index.html +1 -1
  42. package/lib/events.ts +61 -0
  43. package/lib/ids.ts +2 -8
  44. package/lib/types.ts +12 -15
  45. package/package.json +1 -1
  46. package/server/AGENTS.md +3 -3
  47. package/server/README.md +29 -15
  48. package/server/api/index.ts +54 -35
  49. package/server/applets/views.ts +15 -14
  50. package/server/applets/widgets.ts +4 -3
  51. package/server/cli/commands/refresh.ts +2 -5
  52. package/server/control.ts +24 -33
  53. package/server/events.ts +14 -13
  54. package/server/harness/README.md +7 -7
  55. package/server/harness/acp/session.ts +9 -5
  56. package/server/harness/auth.ts +7 -30
  57. package/server/harness/claude-code/session.ts +8 -4
  58. package/server/harness/codex/NOTES.md +1 -1
  59. package/server/harness/codex/session.ts +18 -10
  60. package/server/harness/hermes/NOTES.md +3 -3
  61. package/server/harness/openclaw/session.ts +9 -5
  62. package/server/onboarding/jobs.ts +7 -7
  63. package/server/operations/commands.ts +1 -1
  64. package/server/scratchpad/executor.ts +2 -2
  65. package/server/scratchpad/relay.ts +3 -3
  66. package/server/sessions/archive.ts +1 -1
  67. package/server/sessions/lifecycle.ts +1 -1
  68. package/server/sessions/pending-views.ts +17 -11
  69. package/server/web.ts +40 -30
  70. package/server/workspace-state/index.ts +15 -4
  71. package/server/workspaces/config.ts +14 -13
  72. package/server/workspaces/env-apply.ts +1 -1
  73. package/server/workspaces/layout.ts +40 -7
  74. package/server/workspaces/shared.ts +1 -1
  75. package/client/features/scratchpad/scratch-executor.ts +0 -20
  76. package/client/runtime/workspace-events.ts +0 -168
  77. package/dist/chunk-0h4zypgf.js +0 -1
  78. package/dist/chunk-1tksq43z.js +0 -72
  79. package/dist/chunk-6gxf0xr8.js +0 -5
  80. package/dist/chunk-h3qag4a6.js +0 -2
  81. package/dist/chunk-q2tpy0h7.js +0 -2
  82. package/dist/chunk-w5h9grdr.js +0 -1
@@ -0,0 +1,2 @@
1
+ var pt=Object.create;var{getPrototypeOf:ht,defineProperty:rr,getOwnPropertyNames:gt}=Object;var br=Object.prototype.hasOwnProperty;function ut(r){return this[r]}var vt,mt,e=(r,t,o)=>{var i=r!=null&&typeof r==="object";if(i){var n=t?vt??=new WeakMap:mt??=new WeakMap,l=n.get(r);if(l)return l}o=r!=null?pt(ht(r)):{};let d=t||!r||!r.__esModule||!br.call(r,"default")?rr(o,"default",{value:r,enumerable:!0}):o;if(r&&typeof r==="object"||typeof r==="function"){for(let s of gt(r))if(!br.call(d,s))rr(d,s,{get:ut.bind(r,s),enumerable:!0})}if(i)n.set(r,d);return d};var C=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports);var ft=(r)=>r;function bt(r,t){this[r]=ft.bind(null,t)}var Ht=(r,t)=>{for(var o in t)rr(r,o,{get:t[o],enumerable:!0,configurable:!0,set:bt.bind(t,o)})};var an=((r)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var xr,tr,F,Fe=(r,t)=>{for(var[o,i,n]of xr||[])for(var l=[r],d=globalThis,s=d.document,c,p,g,h,u;p=l.pop();)if(!tr[p]&&(g=i[p])){tr[p]=1;for(h=1;h<g.length;h++)l.push(n[g[h]]);if(!t&&p!==r&&(c=s&&s.head)){if(F===void 0)F=(h=s.querySelector("meta[property=csp-nonce]"))&&(h.nonce||h.getAttribute("nonce"))||"";if(u=s.createElement("link"),u.rel="modulepreload",u.crossOrigin="",F)u.nonce=F;u.href=new d.URL(g[0],o),c.appendChild(u)}}},xt=(r,t,o,i)=>{for(var n={},l=0;l<t.length;l++)n[t[l]]=o[l];(xr||=[]).push([r,n,t]),tr||={},Fe(t[i],1)};xt(import.meta.url,["qtkv7hp8","851bx8ss","j6928pwm","wjbejzek","nf2wkvf9","k32585ne","dy6f6h3e","rh58dc0y","0t8m1ehd","cty37f3v","c8g5x288"],[["/chunk-qtkv7hp8.js"],["/chunk-851bx8ss.js",6,0,7,8],["/chunk-j6928pwm.js",7],["/chunk-wjbejzek.js",0,8],["/chunk-nf2wkvf9.js"],["/chunk-k32585ne.js",6,7,0,10,8],["/chunk-dy6f6h3e.js",0,7,8],["/chunk-rh58dc0y.js",0,8],["/chunk-0t8m1ehd.js"],["/chunk-cty37f3v.js",10],["/chunk-c8g5x288.js"]],0);
2
+ if(typeof globalThis.structuredClone==="function")globalThis.structuredClone=globalThis.structuredClone.bind(globalThis);var P=["pink","orange","amber","lime","emerald","cyan","blue","violet"];function Q(r){return typeof r==="string"&&P.includes(r)}function oo(r){let t=2166136261;for(let o=0;o<r.length;o++)t^=r.charCodeAt(o),t=Math.imul(t,16777619);return P[(t>>>0)%P.length]??P[0]}var ln=1;var yt=8192,kt=320;function Be(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)}function L(r,t=256){return typeof r==="string"&&r.length>0&&!r.includes("\x00")&&new TextEncoder().encode(r).length<=t}function yr(r){return Be(r)&&L(r.id,240)&&r.id.trim().length>0&&(r.name===void 0||L(r.name)&&r.name.trim().length>0)&&Q(r.color)&&(r.avatar===void 0||L(r.avatar,yt))&&(r.email===void 0||L(r.email,kt))}function N(r,t){return typeof r==="string"&&r.length<=t&&!r.includes("\x00")}function zt(r){if(!N(r,2048))return!1;try{return["http:","https:"].includes(new URL(r).protocol)}catch{return!1}}function nt(r){if(!Be(r)||!N(r.id,240)||!r.id.trim()||r.id!==r.id.trim()||!N(r.name,256)||r.avatar!==void 0&&!zt(r.avatar))throw Error("Invalid identity");let t={id:r.id,name:r.name,...r.avatar!==void 0?{avatar:r.avatar}:{}};if(r.type==="agent")return{...t,type:"agent"};if(r.type==="user"&&N(r.email,320)&&typeof r.isAnonymous==="boolean")return{...t,type:"user",email:r.email,isAnonymous:r.isAnonymous};throw Error("Invalid identity")}var ze=(r)=>`${r.type}:${r.id}`,wt=(r)=>r.type==="agent"?`agent:${r.id}`:r.id;var W,zr=0,_r=0,er=new Set,Te=()=>W,kr=()=>_r,le=()=>zr;function no(r){return er.add(r),()=>{er.delete(r)}}function St(r){let t=r===null?null:nt(r);if((W&&ze(W))!==(t&&ze(t)))zr++;_r++,W=t,er.forEach((i)=>i())}var _t=["Curious Kiwi","Cheerful Cherry","Sleepy Peach","Excited Banana","Cosmic Mango","Velvet Lemon","Electric Plum","Wandering Pear","Dramatic Papaya","Suspicious Pineapple","Confused Coconut","Sneaky Tangerine","Gentle Fig","Quiet Apricot","Mellow Melon","Dreamy Guava"];function Cr(r,t){let o=r.filter((i)=>i!==t);return o[Math.floor(Math.random()*o.length)]??r[0]}function Et(r){return{name:Cr(_t,r?.name),color:Cr(P,r?.color)}}function At(r,t){let o=t.name.trim();return{id:r,...o?{name:o}:{},color:t.color}}function Sr(){return At(`local-${crypto.randomUUID().slice(0,8)}`,Et())}var lr="moi:local-profile",_,E,R=new Set;function dr(r,t){return JSON.stringify(r)===JSON.stringify(t)}function j(r){if(!r||typeof r.id!=="string"||!r.id.trim())throw Error("A user profile needs an id.");if(r.name!==void 0&&typeof r.name!=="string")throw Error("A user profile name must be a string when provided.");if(r.color!==void 0&&!Q(r.color))throw Error("A user profile color must be one of the user palette names.");let t=r.id.trim(),o=r.name?.trim(),i={id:t,...o?{name:o}:{},color:r.color??oo(t),...r.avatar!==void 0?{avatar:r.avatar}:{},...r.email!==void 0?{email:r.email}:{}};if(!yr(i))throw Error("Invalid user profile.");return Object.freeze(i)}var cr,Ar;function pe(){let r=Te();if(r===void 0)return _;if(r!==Ar){Ar=r;let t=!r||r.type==="user"&&r.isAnonymous?void 0:j({id:wt(r),name:r.name||void 0,avatar:r.avatar,email:r.type==="user"?r.email||void 0:void 0});if(!dr(cr,t))cr=t}return cr}function It(r){let t=pe(),o=we(),i=()=>{let l=pe(),d=we();if(t===l&&o===d)return;t=l,o=d,r()};R.add(i);let n=no(i);return()=>{R.delete(i),n()}}function we(){return Te()!==void 0?"external":E}function cn({provider:r,profile:t}){if(we()==="external")return;if(r===void 0){if(E===void 0||E==="local")return;E=void 0,_=void 0}else{let o=t===void 0?void 0:j(t);if(E===r&&dr(_,o))return;E=r,_=o}R.forEach((o)=>o())}function Pt(){try{localStorage.setItem(lr,JSON.stringify(_))}catch{}}function io(r){if(we()!==void 0&&we()!=="local")return;let t=j(r);E="local",_=t,Pt(),R.forEach((o)=>o())}function jr(r,t){if(!r||!t||t.provider!==void 0||we()!==void 0)return;try{let o=localStorage.getItem(lr);if(o){io(JSON.parse(o));return}}catch{}io(Sr())}function Mr(r){if(r.key!==lr||!r.newValue||we()!=="local")return;try{let t=j(JSON.parse(r.newValue));if(dr(t,_))return;_=t,R.forEach((o)=>o())}catch{}}function Or(){return window.addEventListener("storage",Mr),()=>window.removeEventListener("storage",Mr)}var Mt={setTimeout:(r,t)=>setTimeout(r,t),clearTimeout:(r)=>clearTimeout(r),setInterval:(r,t)=>setInterval(r,t),clearInterval:(r)=>clearInterval(r)},jt=class{#r=Mt;#t=!1;setTimeoutProvider(r){this.#r=r}setTimeout(r,t){return this.#r.setTimeout(r,t)}clearTimeout(r){this.#r.clearTimeout(r)}setInterval(r,t){return this.#r.setInterval(r,t)}clearInterval(r){this.#r.clearInterval(r)}},He=new jt;function Ir(r){setTimeout(r,0)}var hr=typeof window>"u"||"Deno"in globalThis;function H(){}function qr(r,t){return typeof r==="function"?r(t):r}function so(r){return typeof r==="number"&&r>=0&&r!==1/0}function ao(r,t){return Math.max(r+(t||0)-Date.now(),0)}function U(r,t){return typeof r==="function"?r(t):r}function or(r,t){let{type:o="all",exact:i,fetchStatus:n,predicate:l,queryKey:d,stale:s}=r;if(d){if(i){if(t.queryHash!==q(d,t.options))return!1}else if(!S(t.queryKey,d))return!1}if(o!=="all"){let c=t.isActive();if(o==="active"&&!c)return!1;if(o==="inactive"&&c)return!1}if(typeof s==="boolean"&&t.isStale()!==s)return!1;if(n&&n!==t.state.fetchStatus)return!1;if(l&&!l(t))return!1;return!0}function B(r,t){let{exact:o,status:i,predicate:n,mutationKey:l}=r;if(l){if(!t.options.mutationKey)return!1;if(o){if(Ue(t.options.mutationKey)!==Ue(l))return!1}else if(!S(t.options.mutationKey,l))return!1}if(i&&t.state.status!==i)return!1;if(n&&!n(t))return!1;return!0}function q(r,t){return(t?.queryKeyHashFn||Ue)(r)}function Ue(r){return JSON.stringify(r,(t,o)=>pr(o)?Object.keys(o).sort().reduce((i,n)=>(i[n]=o[n],i),{}):o)}function S(r,t){if(r===t)return!0;if(typeof r!==typeof t)return!1;if(r&&t&&typeof r==="object"&&typeof t==="object"){if(Array.isArray(r)&&Array.isArray(t)){for(let i=0;i<t.length;i++)if(!S(r[i],t[i]))return!1;return!0}let o=Object.keys(t);for(let i of o)if(!S(r[i],t[i]))return!1;return!0}return!1}var Ot=Object.prototype.hasOwnProperty;function We(r,t,o=0){if(r===t)return r;if(o>500)return t;let i=Dr(r)&&Dr(t);if(!i&&!(pr(r)&&pr(t)))return t;let n=(i?r:Object.keys(r)).length,l=i?t:Object.keys(t),d=l.length,s=i?Array(d):{},c=0;for(let p=0;p<d;p++){let g=i?p:l[p],h=r[g],u=t[g];if(h===u){if(s[g]=h,i?p<n:Ot.call(r,g))c++;continue}if(h===null||u===null||typeof h!=="object"||typeof u!=="object"){s[g]=u;continue}let y=We(h,u,o+1);if(s[g]=y,y===h)c++}return n===d&&c===n?r:s}function Ct(r,t){if(!t||Object.keys(r).length!==Object.keys(t).length)return!1;for(let o in r)if(r[o]!==t[o])return!1;return!0}function Dr(r){return Array.isArray(r)&&r.length===Object.keys(r).length}function pr(r){if(!Rr(r))return!1;let t=r.constructor;if(t===void 0)return!0;let o=t.prototype;if(!Rr(o))return!1;if(!o.hasOwnProperty("isPrototypeOf"))return!1;if(Object.getPrototypeOf(r)!==Object.prototype)return!1;return!0}function Rr(r){return Object.prototype.toString.call(r)==="[object Object]"}function Ur(r){return new Promise((t)=>{He.setTimeout(t,r)})}function Tr(r,t,o){if(typeof o.structuralSharing==="function")return o.structuralSharing(r,t);else if(o.structuralSharing!==!1)return We(r,t);return t}function Fr(r,t,o=0){let i=[...r,t];return o&&i.length>o?i.slice(1):i}function Qr(r,t,o=0){let i=[t,...r];return o&&i.length>o?i.slice(0,-1):i}var O=Symbol();function K(r,t){if(!r.queryFn&&t?.initialPromise)return()=>t.initialPromise;if(!r.queryFn||r.queryFn===O)return()=>Promise.reject(Error(`Missing queryFn: '${r.queryHash}'`));return r.queryFn}function nr(r,t){if(typeof r==="function")return r(...t);return!!r}function Lr(r,t,o){let i=!1,n;return Object.defineProperty(r,"signal",{enumerable:!0,get:()=>{if(n??=t(),i)return n;if(i=!0,n.aborted)o();else n.addEventListener("abort",o,{once:!0});return n}}),r}var Dt=()=>hr,ir=()=>Dt();var ye=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(r){return this.listeners.add(r),this.onSubscribe(),()=>{this.listeners.delete(r),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var Rt=class extends ye{#r;#t;#a;constructor(){super();this.#a=(r)=>{if(typeof window<"u"&&window.addEventListener){let t=()=>r();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){if(!this.#t)this.setEventListener(this.#a)}onUnsubscribe(){if(!this.hasListeners())this.#t?.(),this.#t=void 0}setEventListener(r){this.#a=r,this.#t?.(),this.#t=r((t)=>{if(typeof t==="boolean")this.setFocused(t);else this.onFocus()})}setFocused(r){if(this.#r!==r)this.#r=r,this.onFocus()}onFocus(){let r=this.isFocused();this.listeners.forEach((t)=>{t(r)})}isFocused(){if(typeof this.#r==="boolean")return this.#r;return globalThis.document?.visibilityState!=="hidden"}},sr=new Rt;var Nr=Ir;function qt(){let r=[],t=0,o=(s)=>{s()},i=(s)=>{s()},n=Nr,l=(s)=>{if(t)r.push(s);else n(()=>{o(s)})},d=()=>{let s=r;if(r=[],s.length)n(()=>{i(()=>{s.forEach((c)=>{o(c)})})})};return{batch:(s)=>{let c;t++;try{c=s()}finally{if(t--,!t)d()}return c},batchCalls:(s)=>(...c)=>{l(()=>{s(...c)})},schedule:l,setNotifyFunction:(s)=>{o=s},setBatchNotifyFunction:(s)=>{i=s},setScheduler:(s)=>{n=s}}}var M=qt();var Tt=class extends ye{#r=!0;#t;#a;constructor(){super();this.#a=(r)=>{if(typeof window<"u"&&window.addEventListener){let t=()=>r(!0),o=()=>r(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",o,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",o)}}}}onSubscribe(){if(!this.#t)this.setEventListener(this.#a)}onUnsubscribe(){if(!this.hasListeners())this.#t?.(),this.#t=void 0}setEventListener(r){this.#a=r,this.#t?.(),this.#t=r(this.setOnline.bind(this))}setOnline(r){if(this.#r!==r)this.#r=r,this.listeners.forEach((t)=>{t(r)})}isOnline(){return this.#r}},I=new Tt;function Ft(r){return Math.min(1000*2**r,30000)}function gr(r){return(r??"online")==="online"?I.isOnline():!0}var V=class extends Error{constructor(r){super("CancelledError");this.revert=r?.revert,this.silent=r?.silent}};function Y(r){let t=!1,o=0,i,n="pending",l,d,s=new Promise((v,f)=>{l=v,d=f});s.catch(H);let c=()=>n!=="pending",p=(v)=>{if(!c()){let f=new V(v);m(f),r.onCancel?.(f)}},g=()=>{t=!0},h=()=>{t=!1},u=()=>sr.isFocused()&&(r.networkMode==="always"||I.isOnline())&&r.canRun(),y=()=>gr(r.networkMode)&&r.canRun(),w=(v)=>{if(!c())i?.(),n="resolved",l(v)},m=(v)=>{if(!c())i?.(),n="rejected",d(v)},k=()=>new Promise((v)=>{i=(f)=>{if(c()||u())v(f)},r.onPause?.()}).then(()=>{if(i=void 0,!c())r.onContinue?.()}),T=()=>{if(c())return;let v,f=o===0?r.initialPromise:void 0;try{v=f??r.fn()}catch(b){v=Promise.reject(b)}Promise.resolve(v).then(w).catch((b)=>{if(c())return;let z=r.retry??(ir()?0:3),A=r.retryDelay??Ft,lt=typeof A==="function"?A(o,b):A,dt=z===!0||typeof z==="number"&&o<z||typeof z==="function"&&z(o,b);if(t||!dt){m(b);return}o++,r.onFail?.(o,b),Ur(lt).then(()=>u()?void 0:k()).then(()=>{if(t)m(b);else T()})})};return{promise:s,status:()=>n,cancel:p,continue:()=>(i?.(),s),cancelRetry:g,continueRetry:h,canStart:y,start:()=>{if(y())T();else k().then(T);return s}}}var J=class{#r;destroy(){this.clearGcTimeout()}scheduleGc(){if(this.clearGcTimeout(),so(this.gcTime))this.#r=He.setTimeout(()=>{this.optionalRemove()},this.gcTime)}updateGcTime(r){this.gcTime=Math.max(this.gcTime||0,r??(ir()?1/0:300000))}clearGcTimeout(){if(this.#r!==void 0)He.clearTimeout(this.#r),this.#r=void 0}};function Br(r){return{onFetch:(t,o)=>{let i=t.options,n=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],d=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,p=async()=>{let g=!1,h=(w)=>{Lr(w,()=>t.signal,()=>g=!0)},u=K(t.options,t.fetchOptions),y=async(w,m,k)=>{if(g)return Promise.reject(t.signal.reason);if(m==null&&w.pages.length)return Promise.resolve(w);let v=(()=>{let A={client:t.client,queryKey:t.queryKey,pageParam:m,direction:k?"backward":"forward",meta:t.options.meta};return h(A),A})(),f=await u(v),{maxPages:b}=t.options,z=k?Qr:Fr;return{pages:z(w.pages,f,b),pageParams:z(w.pageParams,m,b)}};if(n&&l.length){let w=n==="backward",m=w?Qt:Wr,k={pages:l,pageParams:d};s=await y(k,m(i,k),w)}else{let w=r??l.length;do{let m=c===0?d[0]??i.initialPageParam:Wr(i,s);if(c>0&&m==null)break;s=await y(s,m),c++}while(c<w)}return s};if(t.options.persister)t.fetchFn=()=>t.options.persister?.(p,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},o);else t.fetchFn=p}}}function Wr(r,{pages:t,pageParams:o}){let i=t.length-1;return t.length>0?r.getNextPageParam(t[i],t,o[i],o):void 0}function Qt(r,{pages:t,pageParams:o}){return t.length>0?r.getPreviousPageParam?.(t[0],t,o[0],o):void 0}var Vr=class extends J{#r;#t;#a;#o;#i;#e;#c;#n;constructor(r){super();this.#n=!1,this.#c=r.defaultOptions,this.setOptions(r.options),this.observers=[],this.#i=r.client,this.#o=this.#i.getQueryCache(),this.queryKey=r.queryKey,this.queryHash=r.queryHash,this.#t=Kr(this.options),this.state=r.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#r}get promise(){return this.#e?.promise}setOptions(r){if(this.options={...this.#c,...r},r?._type)this.#r=r._type;if(this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let t=Kr(this.options);if(t.data!==void 0)this.setState(Hr(t.data,t.dataUpdatedAt)),this.#t=t}}optionalRemove(){if(!this.observers.length&&this.state.fetchStatus==="idle")this.#o.remove(this)}setData(r,t){let o=Tr(this.state.data,r,this.options);return this.#s({data:o,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),o}setState(r){this.#s({type:"setState",state:r})}cancel(r){let t=this.#e?.promise;return this.#e?.cancel(r),t?t.then(H).catch(H):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some((r)=>U(r.options.enabled,this)!==!1)}isDisabled(){if(this.getObserversCount()>0)return!this.isActive();return this.options.queryFn===O||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){if(this.getObserversCount()>0)return this.observers.some((r)=>U(r.options.staleTime,this)==="static");return!1}isStale(){if(this.getObserversCount()>0)return this.observers.some((r)=>r.getCurrentResult().isStale);return this.state.data===void 0||this.state.isInvalidated}isStaleByTime(r=0){if(this.state.data===void 0)return!0;if(r==="static")return!1;if(this.state.isInvalidated)return!0;return!ao(this.state.dataUpdatedAt,r)}onFocus(){this.observers.find((r)=>r.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#e?.continue()}onOnline(){this.observers.find((r)=>r.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#e?.continue()}addObserver(r){if(!this.observers.includes(r))this.observers.push(r),this.clearGcTimeout(),this.#o.notify({type:"observerAdded",query:this,observer:r})}removeObserver(r){let t=this.observers.indexOf(r);if(t!==-1){if(this.observers.splice(t,1),!this.observers.length){if(this.#e)if(this.#n||this.state.fetchStatus==="paused"&&this.state.status==="pending")this.#e.cancel({revert:!0});else this.#e.cancelRetry();this.scheduleGc()}this.#o.notify({type:"observerRemoved",query:this,observer:r})}}getObserversCount(){return this.observers.length}invalidate(){if(!this.state.isInvalidated)this.#s({type:"invalidate"})}async fetch(r,t){if(this.state.fetchStatus!=="idle"&&this.#e?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#e)return this.#e.continueRetry(),this.#e.promise}if(r)this.setOptions(r);if(!this.options.queryFn){let c=this.observers.find((p)=>p.options.queryFn);if(c)this.setOptions(c.options)}let o=new AbortController,i=(c)=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#n=!0,o.signal)})},n=()=>{let c=K(this.options,t),g=(()=>{let h={client:this.#i,queryKey:this.queryKey,meta:this.meta};return i(h),h})();if(this.#n=!1,this.options.persister)return this.options.persister(c,g,this);return c(g)},d=(()=>{let c={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:n};return i(c),c})();if((this.#r==="infinite"?Br(this.options.pages):this.options.behavior)?.onFetch(d,this),this.#a=this.state,this.state.fetchStatus==="idle"||this.state.fetchMeta!==d.fetchOptions?.meta)this.#s({type:"fetch",meta:d.fetchOptions?.meta});let s=this.#e=Y({initialPromise:t?.initialPromise,fn:d.fetchFn,onCancel:(c)=>{if(c instanceof V&&c.revert)this.setState({...this.#a,fetchStatus:"idle"});o.abort()},onFail:(c,p)=>{this.#s({type:"failed",failureCount:c,error:p})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:d.options.retry,retryDelay:d.options.retryDelay,networkMode:d.options.networkMode,canRun:()=>!0});try{let c=await s.start();if(c===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(c),this.#o.config.onSuccess?.(c,this),this.#o.config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof V){if(c.silent)return this.#e.promise;else if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw this.#s({type:"error",error:c}),this.#o.config.onError?.(c,this),this.#o.config.onSettled?.(this.state.data,c,this),c}finally{if(this.#e===s)this.#e=void 0;this.scheduleGc()}}#s(r){let t=(o)=>{switch(r.type){case"failed":return{...o,fetchFailureCount:r.failureCount,fetchFailureReason:r.error};case"pause":return{...o,fetchStatus:"paused"};case"continue":return{...o,fetchStatus:"fetching"};case"fetch":return{...o,...Fo(o.data,this.options),fetchMeta:r.meta??null};case"success":let i={...o,...Hr(r.data,r.dataUpdatedAt),dataUpdateCount:o.dataUpdateCount+1,...!r.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#a=r.manual?i:void 0,i;case"error":let n=r.error;return{...o,error:n,errorUpdateCount:o.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:o.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...o,isInvalidated:!0};case"setState":return{...o,...r.state}}};this.state=t(this.state),M.batch(()=>{this.observers.slice().forEach((o)=>{o.onQueryUpdate()}),this.#o.notify({query:this,type:"updated",action:r})})}};function Fo(r,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:gr(t.networkMode)?"fetching":"paused",...r===void 0&&{error:null,status:"pending"}}}function Hr(r,t){return{data:r,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Kr(r){let t=typeof r.initialData==="function"?r.initialData():r.initialData,o=t!==void 0,i=o?typeof r.initialDataUpdatedAt==="function"?r.initialDataUpdatedAt():r.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:o?i??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:o?"success":"pending",fetchStatus:"idle"}}var $r=class extends J{#r;#t;#a;#o;constructor(r){super();this.#r=r.client,this.mutationId=r.mutationId,this.#a=r.mutationCache,this.#t=[],this.state=r.state||Bo(),this.setOptions(r.options),this.scheduleGc()}setOptions(r){this.options=r,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(r){if(!this.#t.includes(r))this.#t.push(r),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",mutation:this,observer:r})}removeObserver(r){this.#t=this.#t.filter((t)=>t!==r),this.scheduleGc(),this.#a.notify({type:"observerRemoved",mutation:this,observer:r})}optionalRemove(){if(!this.#t.length)if(this.state.status==="pending")this.scheduleGc();else this.#a.remove(this)}continue(){return this.#o?.continue()??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(r){let t=()=>{this.#i({type:"continue"})},o={client:this.#r,meta:this.options.meta,mutationKey:this.options.mutationKey},i=this.#o=Y({fn:()=>{if(!this.options.mutationFn)return Promise.reject(Error("No mutationFn found"));return this.options.mutationFn(r,o)},onFail:(d,s)=>{this.#i({type:"failed",failureCount:d,error:s})},onPause:()=>{this.#i({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#a.canRun(this)}),n=this.state.status==="pending",l=!i.canStart();try{if(n)t();else{if(this.#i({type:"pending",variables:r,isPaused:l}),this.#a.config.onMutate)await this.#a.config.onMutate(r,this,o);let s=await this.options.onMutate?.(r,o);if(s!==this.state.context)this.#i({type:"pending",context:s,variables:r,isPaused:l})}let d=await i.start();return await this.#a.config.onSuccess?.(d,r,this.state.context,this,o),await this.options.onSuccess?.(d,r,this.state.context,o),await this.#a.config.onSettled?.(d,null,this.state.variables,this.state.context,this,o),await this.options.onSettled?.(d,null,r,this.state.context,o),this.#i({type:"success",data:d}),d}catch(d){try{await this.#a.config.onError?.(d,r,this.state.context,this,o)}catch(s){Promise.reject(s)}try{await this.options.onError?.(d,r,this.state.context,o)}catch(s){Promise.reject(s)}try{await this.#a.config.onSettled?.(void 0,d,this.state.variables,this.state.context,this,o)}catch(s){Promise.reject(s)}try{await this.options.onSettled?.(void 0,d,r,this.state.context,o)}catch(s){Promise.reject(s)}throw this.#i({type:"error",error:d}),d}finally{if(this.#o===i)this.#o=void 0;this.#a.runNext(this)}}#i(r){let t=(o)=>{switch(r.type){case"failed":return{...o,failureCount:r.failureCount,failureReason:r.error};case"pause":return{...o,isPaused:!0};case"continue":return{...o,isPaused:!1};case"pending":return{...o,context:r.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:r.isPaused,status:"pending",variables:r.variables,submittedAt:Date.now()};case"success":return{...o,data:r.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...o,data:void 0,error:r.error,failureCount:o.failureCount+1,failureReason:r.error,isPaused:!1,status:"error"}}};this.state=t(this.state),M.batch(()=>{this.#t.forEach((o)=>{o.onMutationUpdate(r)}),this.#a.notify({mutation:this,type:"updated",action:r})})}};function Bo(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Yr=class extends ye{#r;#t;#a;constructor(r={}){super();this.config=r,this.#r=new Set,this.#t=new Map,this.#a=0}build(r,t,o){let i=new $r({client:r,mutationCache:this,mutationId:++this.#a,options:r.defaultMutationOptions(t),state:o});return this.add(i),i}add(r){this.#r.add(r);let t=X(r);if(typeof t==="string"){let o=this.#t.get(t);if(o)o.push(r);else this.#t.set(t,[r])}this.notify({type:"added",mutation:r})}remove(r){if(this.#r.delete(r)){let t=X(r);if(typeof t==="string"){let o=this.#t.get(t);if(o){if(o.length>1){let i=o.indexOf(r);if(i!==-1)o.splice(i,1)}else if(o[0]===r)this.#t.delete(t)}}}this.notify({type:"removed",mutation:r})}canRun(r){let t=X(r);if(typeof t==="string"){let o=this.#t.get(t)?.find((i)=>i.state.status==="pending");return!o||o===r}else return!0}runNext(r){let t=X(r);if(typeof t==="string")return this.#t.get(t)?.find((o)=>o!==r&&o.state.isPaused)?.continue()??Promise.resolve();else return Promise.resolve()}clear(){M.batch(()=>{this.#r.forEach((r)=>{this.notify({type:"removed",mutation:r})}),this.#r.clear(),this.#t.clear()})}getAll(){return Array.from(this.#r)}find(r){let t={exact:!0,...r};return this.getAll().find((o)=>B(t,o))}findAll(r={}){return this.getAll().filter((t)=>B(r,t))}notify(r){M.batch(()=>{this.listeners.forEach((t)=>{t(r)})})}resumePausedMutations(){let r=this.getAll().filter((t)=>t.state.isPaused);return M.batch(()=>Promise.all(r.map((t)=>t.continue().catch(H))))}};function X(r){return r.options.scope?.id}var Jr=class extends ye{#r;constructor(r={}){super();this.config=r,this.#r=new Map}build(r,t,o){let i=t.queryKey,n=t.queryHash??q(i,t),l=this.get(n);if(!l)l=new Vr({client:r,queryKey:i,queryHash:n,options:r.defaultQueryOptions(t),state:o,defaultOptions:r.getQueryDefaults(i)}),this.add(l);return l}add(r){if(!this.#r.has(r.queryHash))this.#r.set(r.queryHash,r),this.notify({type:"added",query:r})}remove(r){let t=this.#r.get(r.queryHash);if(t){if(r.destroy(),t===r)this.#r.delete(r.queryHash);this.notify({type:"removed",query:r})}}clear(){M.batch(()=>{this.getAll().forEach((r)=>{this.remove(r)})})}get(r){return this.#r.get(r)}getAll(){return[...this.#r.values()]}find(r){let t={exact:!0,...r};return this.getAll().find((o)=>or(t,o))}findAll(r={}){let t=this.getAll();return Object.keys(r).length>0?t.filter((o)=>or(r,o)):t}notify(r){M.batch(()=>{this.listeners.forEach((t)=>{t(r)})})}onFocus(){M.batch(()=>{this.getAll().forEach((r)=>{r.onFocus()})})}onOnline(){M.batch(()=>{this.getAll().forEach((r)=>{r.onOnline()})})}};var ur=class{#r;#t;#a;#o;#i;#e;#c;#n;constructor(r={}){this.#r=r.queryCache||new Jr,this.#t=r.mutationCache||new Yr,this.#a=r.defaultOptions||{},this.#o=new Map,this.#i=new Map,this.#e=0}mount(){if(this.#e++,this.#e!==1)return;this.#c=sr.subscribe(async(r)=>{if(r)await this.resumePausedMutations(),this.#r.onFocus()}),this.#n=I.subscribe(async(r)=>{if(r)await this.resumePausedMutations(),this.#r.onOnline()})}unmount(){if(this.#e--,this.#e!==0)return;this.#c?.(),this.#c=void 0,this.#n?.(),this.#n=void 0}isFetching(r){return this.#r.findAll({...r,fetchStatus:"fetching"}).length}isMutating(r){return this.#t.findAll({...r,status:"pending"}).length}getQueryData(r){let t=this.defaultQueryOptions({queryKey:r});return this.#r.get(t.queryHash)?.state.data}ensureQueryData(r){let t=this.defaultQueryOptions(r),o=this.#r.build(this,t),i=o.state.data;if(i===void 0)return this.fetchQuery(r);if(r.revalidateIfStale&&o.isStaleByTime(U(t.staleTime,o)))this.prefetchQuery(t);return Promise.resolve(i)}getQueriesData(r){return this.#r.findAll(r).map(({queryKey:t,state:o})=>[t,o.data])}setQueryData(r,t,o){let i=this.defaultQueryOptions({queryKey:r}),n=this.#r.get(i.queryHash)?.state.data,l=qr(t,n);if(l===void 0)return;return this.#r.build(this,i).setData(l,{...o,manual:!0})}setQueriesData(r,t,o){return M.batch(()=>this.#r.findAll(r).map(({queryKey:i})=>[i,this.setQueryData(i,t,o)]))}getQueryState(r){let t=this.defaultQueryOptions({queryKey:r});return this.#r.get(t.queryHash)?.state}removeQueries(r){let t=this.#r;M.batch(()=>{t.findAll(r).forEach((o)=>{t.remove(o)})})}resetQueries(r,t){let o=this.#r;return M.batch(()=>{let i=o.findAll(r),n=new Set(i);return i.forEach((l)=>{l.reset()}),this.refetchQueries({type:"active",predicate:(l)=>n.has(l)},t)})}cancelQueries(r,t={}){let o={revert:!0,...t},i=M.batch(()=>this.#r.findAll(r).map((n)=>n.cancel(o)));return Promise.all(i).then(H).catch(H)}invalidateQueries(r,t={}){return M.batch(()=>{if(this.#r.findAll(r).forEach((o)=>{o.invalidate()}),r?.refetchType==="none")return Promise.resolve();return this.refetchQueries({...r,type:r?.refetchType??r?.type??"active"},t)})}refetchQueries(r,t={}){let o={...t,cancelRefetch:t.cancelRefetch??!0},i=M.batch(()=>this.#r.findAll(r).filter((n)=>!n.isDisabled()&&!n.isStatic()).map((n)=>{let l=n.fetch(void 0,o);if(!o.throwOnError)l=l.catch(H);return n.state.fetchStatus==="paused"?Promise.resolve():l}));return Promise.all(i).then(H)}async query(r){let t=this.defaultQueryOptions(r);if(t.retry===void 0)t.retry=!1;let o=this.#r.build(this,t),i=o.isStaleByTime(U(t.staleTime,o))?await o.fetch(t):o.state.data,n=t.select;if(n)return n(i);return i}fetchQuery(r){let t=this.defaultQueryOptions(r);if(t.retry===void 0)t.retry=!1;let o=this.#r.build(this,t);return o.isStaleByTime(U(t.staleTime,o))?o.fetch(t):Promise.resolve(o.state.data)}prefetchQuery(r){return this.fetchQuery(r).then(H).catch(H)}infiniteQuery(r){return r._type="infinite",this.query(r)}fetchInfiniteQuery(r){return r._type="infinite",this.fetchQuery(r)}prefetchInfiniteQuery(r){return this.fetchInfiniteQuery(r).then(H).catch(H)}ensureInfiniteQueryData(r){return r._type="infinite",this.ensureQueryData(r)}resumePausedMutations(){if(I.isOnline())return this.#t.resumePausedMutations();return Promise.resolve()}getQueryCache(){return this.#r}getMutationCache(){return this.#t}getDefaultOptions(){return this.#a}setDefaultOptions(r){this.#a=r}setQueryDefaults(r,t){this.#o.set(Ue(r),{queryKey:r,defaultOptions:t})}getQueryDefaults(r){let t=[...this.#o.values()],o={};return t.forEach((i)=>{if(S(r,i.queryKey))Object.assign(o,i.defaultOptions)}),o}setMutationDefaults(r,t){this.#i.set(Ue(r),{mutationKey:r,defaultOptions:t})}getMutationDefaults(r){let t=[...this.#i.values()],o={};return t.forEach((i)=>{if(S(r,i.mutationKey))Object.assign(o,i.defaultOptions)}),o}defaultQueryOptions(r){if(r._defaulted)return r;let t={...this.#a.queries,...this.getQueryDefaults(r.queryKey),...r,_defaulted:!0};if(!t.queryHash)t.queryHash=q(t.queryKey,t);if(t.refetchOnReconnect===void 0)t.refetchOnReconnect=t.networkMode!=="always";if(t.throwOnError===void 0)t.throwOnError=!!t.suspense;if(!t.networkMode&&t.persister)t.networkMode="offlineFirst";if(t.queryFn===O)t.enabled=!1;return t}defaultMutationOptions(r){if(r?._defaulted)return r;return{...this.#a.mutations,...r?.mutationKey&&this.getMutationDefaults(r.mutationKey),...r,_defaulted:!0}}clear(){this.#r.clear(),this.#t.clear()}};var it=new ur;var a={all:["workspaces"],discover:["workspaces","discover"],previews:["workspaces","previews"],layout:(r)=>["workspaces","layout",r],widgets:(r)=>["workspaces","widgets",r],appletThumbnails:(r)=>["workspaces","applet-thumbnails",r],views:(r)=>["workspaces","views",r],sessions:(r)=>["workspaces","sessions",r],events:(r,t)=>["workspaces","events",r,t],state:(r)=>["workspaces","state",r],mcp:(r)=>["workspaces","mcp",r],harness:(r)=>["workspaces","harness",r],skills:(r)=>["workspaces","skills",r],env:(r)=>["workspaces","env",r]};function ar(r){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${r}`}class Ut{url;options;listeners=new Set;socket;holders=0;attempts=0;lastMessageAt=0;retry;heartbeat;constructor(r,t={}){this.url=r;this.options=t}get isOpen(){return this.socket?.readyState===WebSocket.OPEN}subscribe(r){return this.listeners.add(r),()=>{this.listeners.delete(r)}}start(){let r=!0;if(this.holders++===0)this.open();return()=>{if(!r)return;if(r=!1,--this.holders===0)this.drop()}}reconnect(){if(this.drop(),this.holders)this.retry=setTimeout(()=>this.open(),0)}send(r){if(!this.isOpen)return;try{this.socket?.send(JSON.stringify(r))}catch{this.socket?.close()}}open(){if(this.socket||!this.holders)return;let r=new WebSocket(this.url());this.socket=r,r.onopen=()=>{if(r!==this.socket)return;if(this.attempts=0,this.lastMessageAt=Date.now(),this.options.ping)this.heartbeat=setInterval(()=>{if(Date.now()-this.lastMessageAt>45000)r.close();else this.send({type:"ping"})},15000);for(let t of this.listeners)t.open?.()},r.onmessage=(t)=>{if(r!==this.socket)return;this.lastMessageAt=Date.now();let o;try{o=JSON.parse(String(t.data))}catch{return}for(let i of this.listeners)i.message?.(o)},r.onerror=()=>r.close(),r.onclose=()=>{if(r!==this.socket)return;clearInterval(this.heartbeat),this.socket=void 0;for(let i of this.listeners)i.close?.();let o=Math.min((this.options.baseDelayMs??500)*2**this.attempts++,1e4)*(0.5+Math.random()*0.5);this.retry=setTimeout(()=>this.open(),o)}}drop(){clearTimeout(this.retry),clearInterval(this.heartbeat);let r=this.socket;if(!r)return;this.socket=void 0,r.close();for(let t of this.listeners)t.close?.()}}var vr=(r,t)=>t.getQueryData(a.layout(r));function Wt(r,t=it){return vr(r,t)?.isRemote??!1}function ce(r,t=it){let o=vr(r,t)?.apiBase;if(!o)throw Error("Workspace identity is not loaded");return o}function Pr(r,t=it){let o=vr(r,t)?.apiBase;return o?decodeURIComponent(o.slice(16)):r}function lo(r){return new Ut(()=>ar(`${ce(r)}/events`),{ping:!0})}function wr(r){if(!Be(r)||!Array.isArray(r.members)||!Array.isArray(r.invitations))throw Error("Invalid workspace members");let t=r.members.map((i)=>{let n=nt(i);if(Be(i)&&i.membershipId!==void 0){if(typeof i.membershipId!=="string"||!i.membershipId||i.membershipId.length>240)throw Error("Invalid membership id");return{...n,membershipId:i.membershipId}}return n}),o=r.invitations.map((i)=>{if(!Be(i)||typeof i.id!=="string"||!i.id||typeof i.email!=="string"||!i.email||typeof i.expiresAt!=="string"||!Number.isFinite(Date.parse(i.expiresAt)))throw Error("Invalid invitation");return{id:i.id,email:i.email,expiresAt:i.expiresAt}});if(new Set(t.map(ze)).size!==t.length||new Set(o.map((i)=>i.id)).size!==o.length)throw Error("Duplicate workspace member or invitation");return{members:t,invitations:o}}function G(r){if(!/^(?:[A-Za-z0-9_-]{1,64}:)?[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(r))throw Error("Invalid workspace id");return r}var mr;function x(){let r=le();if(mr?.accountGeneration!==r)mr={accountGeneration:r,lists:new Map,complete:!1};return mr}var Zr=0,fr=new Set;function D(){Zr++,fr.forEach((r)=>r())}var rt=()=>Zr,Xr=new WeakMap,Lt={members:[],invitations:[]},Gr=new WeakMap;function tt(r){if(!x().complete)return;if(r.includes(":"))return Lt;let t=Te();if(t?.type!=="user"||t.isAnonymous)return;let o=Xr.get(t);if(!o)o={members:[t],invitations:[]},Xr.set(t,o);return o}function Z(r,t){let{lists:o}=x();o.set(r,We(o.get(r),t))}function at(r,t){Z(G(r),wr(t)),D()}function et(r){if(!Array.isArray(r))throw Error("Invalid workspace members");let t=r.map((n)=>[G(n.id),wr(n)]),o=new Set(t.map(([n])=>n));if(o.size!==t.length)throw Error("Duplicate workspace id");let{lists:i}=x();for(let n of i.keys())if(!o.has(n))i.delete(n);for(let[n,l]of t)Z(n,l);x().complete=!0,D()}function ot(r){x().lists.delete(G(r)),D()}function st(){x().lists.clear(),D()}function un(r,t){let o=Pr(r),i=x().lists.get(o)??tt(o),n=i&&t(i);if(!n)return;Z(o,n),D()}function dn(r){let t=ze(r);for(let[o,i]of x().lists)Z(o,{...i,members:i.members.map((n)=>ze(n)===t?{...r,...n.membershipId&&{membershipId:n.membershipId}}:n)});D()}function zo(r){let t=Pr(r);return x().lists.get(t)??tt(t)}function pn(r){let t=zo(r);if(!t)return;let o=Gr.get(t);if(!o)o=t.members.map((i)=>j({id:wt(i),name:i.name||void 0,avatar:i.avatar,email:i.type==="user"?i.email||void 0:void 0})),Gr.set(t,o);return o}function Er(r){fr.add(r);let t=it.getQueryCache().subscribe((o)=>{let[i,n]=o.query.queryKey;if(i===a.all[0]&&n==="layout")r()});return()=>{fr.delete(r),t()}}function ct(){if(typeof window>"u")return;let r=window;r.moi??={},r.moi.identity={set:St,getRevision:kr},r.moi.workspaceMembers={set:at,setAll:et,remove:ot,clear:st,getRevision:rt}}ct();Or();async function Nt(r){let[{mount:t},o,i]=await Promise.all([(Fe("851bx8ss"),import("/chunk-851bx8ss.js")),(Fe("j6928pwm"),import("/chunk-j6928pwm.js")).then((n)=>n.loadAppConfig()),(Fe("wjbejzek"),import("/chunk-wjbejzek.js")).then((n)=>n.loadProxyUser())]);jr(o?.environment==="local"&&!o.demo,i),t(r)}globalThis.__init=Nt;export{e,C,Ht,an,Fe,oo,ln,Be,nt,ze,wt,Te,kr,le,no,St,pe,It,we,cn,io,He,H,so,ao,U,or,Ue,We,Ct,Tr,nr,ir,ye,sr,M,Fo,Bo,it,a,ar,Ut,Wt,ce,Pr,lo,un,dn,zo,pn,Er};
@@ -0,0 +1,2 @@
1
+ import{e,C}from"/chunk-qtkv7hp8.js";import{h}from"/chunk-0t8m1ehd.js";var r=C(function(l,i){i.exports=globalThis.__esm.react});var p=e(r(),1);var f={environment:"local",demo:!1,demoInstallUrl:"https://moi.computer"},t=f,o=new Set;function s(n){return o.add(n),()=>{o.delete(n)}}async function c(){try{t=await h("/api/config");for(let n of o)n();return t}catch{}}async function ni(){return c()}function oe(){return t.demo?"/demo":"/"}function B(){return p.useSyncExternalStore(s,()=>t,()=>t)}
2
+ export{r,ni,oe,B};
@@ -1 +1 @@
1
- import{on}from"/chunk-h3qag4a6.js";import{h}from"/chunk-f44cs6mw.js";async function r(){try{let e=await h("/api/proxy-user");if(!e||typeof e!=="object"||Array.isArray(e)||e.provider!==void 0&&e.provider!=="cloudflare-access"||e.provider===void 0&&e.profile!==void 0)return;return on(e),e}catch{}}async function n(){return r()}export{n as loadProxyUser};
1
+ import{cn}from"/chunk-qtkv7hp8.js";import{h}from"/chunk-0t8m1ehd.js";async function r(){try{let e=await h("/api/proxy-user");if(!e||typeof e!=="object"||Array.isArray(e)||e.provider!==void 0&&e.provider!=="cloudflare-access"||e.provider===void 0&&e.profile!==void 0)return;return cn(e),e}catch{}}async function n(){return r()}export{n as loadProxyUser};
package/dist/index.html CHANGED
@@ -55,7 +55,7 @@
55
55
  <link rel="modulepreload" href="/vendor/react/19.2.4/production/react-dom-client.js" />
56
56
  <link rel="modulepreload" href="/vendor/react/19.2.4/production/_impl/react-dom-client.js" />
57
57
 
58
- <link rel="stylesheet" crossorigin href="/chunk-kffcah9w.css"><script type="module" crossorigin src="/chunk-h3qag4a6.js"></script></head>
58
+ <link rel="stylesheet" crossorigin href="/chunk-kffcah9w.css"><script type="module" crossorigin src="/chunk-qtkv7hp8.js"></script></head>
59
59
  <body>
60
60
  <div id="root"></div>
61
61
 
package/lib/events.ts ADDED
@@ -0,0 +1,61 @@
1
+ import type { NavigationRequest } from './navigation'
2
+ import type {
3
+ AppSettings,
4
+ CompiledView,
5
+ HarnessType,
6
+ WidgetInfo,
7
+ ScratchpadOpMessage,
8
+ WorkspaceOpenRequestMessage,
9
+ WorkspaceState
10
+ } from './types'
11
+
12
+ // The workspace URL supplies scope on the wire; the browser adds its local ID.
13
+ export type SharedWorkspaceEvent =
14
+ | { type: 'widget:changed'; name: string }
15
+ | { type: 'widgets-list:changed'; widgets: WidgetInfo[] }
16
+ | { type: 'view:changed'; name: string }
17
+ | { type: 'views-list:changed'; views: CompiledView[] }
18
+ | { type: 'view:deleted'; name: string }
19
+ | { type: 'workspace-config:changed'; origin?: string }
20
+ | { type: 'scratchpad:changed'; origin?: string }
21
+
22
+ export type HarnessEvent =
23
+ | { type: 'harness:changed' }
24
+ | { type: 'workspace-harness:switched'; workspaceId: string; harness: HarnessType }
25
+
26
+ export type AppEvent =
27
+ | WorkspaceOpenRequestMessage
28
+ | ScratchpadOpMessage
29
+ | { type: 'applets:refresh'; workspaceId: string; only?: 'widgets' | 'views'; name?: string }
30
+ | {
31
+ type: 'personal-state:changed'
32
+ workspaceId: string
33
+ state: WorkspaceState
34
+ completedViews?: CompiledView[]
35
+ }
36
+ | { type: 'env:changed'; workspaceId: string }
37
+ | { type: 'workspaces-list:changed'; origin?: string }
38
+ | { type: 'app-settings:changed'; settings: AppSettings }
39
+
40
+ export type ServerEvent = (SharedWorkspaceEvent & { workspaceId: string }) | HarnessEvent | AppEvent
41
+
42
+ export type ClientEvent =
43
+ | ServerEvent
44
+ | { type: 'app:connected' }
45
+ | { type: 'workspace:connected'; workspaceId: string }
46
+ | NavigationRequest
47
+
48
+ export function isSharedWorkspaceEvent(event: { type?: unknown }): event is SharedWorkspaceEvent {
49
+ switch (event.type) {
50
+ case 'widget:changed':
51
+ case 'widgets-list:changed':
52
+ case 'view:changed':
53
+ case 'views-list:changed':
54
+ case 'view:deleted':
55
+ case 'workspace-config:changed':
56
+ case 'scratchpad:changed':
57
+ return true
58
+ default:
59
+ return false
60
+ }
61
+ }
package/lib/ids.ts CHANGED
@@ -8,14 +8,8 @@ const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'
8
8
  // whole life. 10 chars (~52 bits) stays collision-free at any realistic count.
9
9
  export const newWorkspaceId = customAlphabet(ALPHABET, 10)
10
10
 
11
- // Ids no workspace can hold, because a URL carrying one never reaches it:
12
- // `/api/workspaces/:id` is registered after the literal collection routes, so
13
- // `create`, `discover`, `order` and `previews` match those instead, and `ws` is claimed by
14
- // the live-event WebSocket upgrade in `server/web.ts` before Hono sees the
15
- // request. A workspace registered under one of these would persist fine and
16
- // then be unreachable in the app. `server/api/reserved-ids.test.ts` re-derives
17
- // this list from the router so a new collection route cannot outgrow it.
18
- export const RESERVED_WORKSPACE_IDS = ['create', 'discover', 'order', 'previews', 'ws']
11
+ // Literal collection routes take precedence over workspace IDs.
12
+ export const RESERVED_WORKSPACE_IDS = ['create', 'discover', 'order', 'previews']
19
13
 
20
14
  // Ids may also be chosen by hand (`moi init --id <id>`), so they are validated
21
15
  // rather than assumed. Slightly wider than the generated alphabet — dashes and
package/lib/types.ts CHANGED
@@ -267,9 +267,6 @@ export type ClientMessage =
267
267
  context?: MoiContext
268
268
  }
269
269
  | { type: 'stop'; workspaceId: string; sessionId: string }
270
- // Reply to a relayed Scratchpad op (see ScratchpadOpMessage). Carries the
271
- // op's correlation id so the server settles the right pending CLI request.
272
- | { type: 'scratchpad:op-result'; opId: string; result?: ScratchOpResult; error?: string }
273
270
 
274
271
  // Session details supplied by the agent backend.
275
272
  export type SessionSummary = {
@@ -313,7 +310,7 @@ export type WorkspaceSessionState = {
313
310
  }
314
311
 
315
312
  // Personal state on this Moi installation, shared across its browser windows.
316
- // GET /api/workspaces/:id/state; writes publish `state:changed`.
313
+ // GET /api/workspaces/:id/state; writes publish `personal-state:changed`.
317
314
  export type WorkspaceState = {
318
315
  // Personal tab list/order, excluding the always-open Overview.
319
316
  // Missing opens all available tabs; an empty list opens only Overview.
@@ -399,11 +396,9 @@ export type ServerMessage =
399
396
  | SessionRenamedMessage
400
397
  | SessionsChangedMessage
401
398
  | SessionArchivedMessage
402
- | WorkspaceSwitchMessage
403
399
  | ErrorFrame
404
400
  | StoppedFrame
405
401
  | StatusSnapshotMessage
406
- | ScratchpadOpMessage
407
402
 
408
403
  // A live token-by-token snapshot of an assistant message still being generated.
409
404
  // Ephemeral: it is NOT a StreamEvent, never persisted, and never folded into the
@@ -412,7 +407,7 @@ export type ServerMessage =
412
407
  // lands. `blocks[].text` is CUMULATIVE, so a lost/reordered/duplicated frame is
413
408
  // simply overwritten by the next one — it can never corrupt the transcript.
414
409
  export type PreviewFrame = {
415
- type: 'preview'
410
+ type: 'session:preview'
416
411
  workspaceId: string
417
412
  sessionId: string
418
413
  // API message id (`msg_...`), globally unique — the accumulator key, so
@@ -453,12 +448,12 @@ export type BroadcastFrame =
453
448
  // clears a spinner whose terminal `status` frame was lost (disconnect window,
454
449
  // dropped frame, harness gap).
455
450
  export type StatusSnapshotMessage = {
456
- type: 'status_snapshot'
451
+ type: 'sessions:status-snapshot'
457
452
  sessions: { workspaceId: string; sessionId: string; activity: SessionActivity }[]
458
453
  }
459
454
 
460
- export type WorkspaceSwitchMessage = {
461
- type: 'workspace:switch'
455
+ export type WorkspaceOpenRequestMessage = {
456
+ type: 'workspace:open-requested'
462
457
  workspaceId: string
463
458
  }
464
459
 
@@ -557,20 +552,20 @@ export type DiscoveredWorkspace = {
557
552
  }
558
553
 
559
554
  export type SessionRenamedMessage = {
560
- type: 'session_renamed'
555
+ type: 'session:renamed'
561
556
  workspaceId: string
562
557
  from: string
563
558
  to: string
564
559
  }
565
560
 
566
561
  export type SessionsChangedMessage = {
567
- type: 'sessions_changed'
562
+ type: 'sessions:changed'
568
563
  workspaceId: string
569
564
  sessionId: string
570
565
  }
571
566
 
572
567
  export type SessionArchivedMessage = {
573
- type: 'session_archived'
568
+ type: 'session:archived'
574
569
  workspaceId: string
575
570
  sessionId: string
576
571
  }
@@ -601,7 +596,7 @@ export type StoppedFrame = {
601
596
  export type SessionActivity = 'idle' | 'running' | 'requires-action'
602
597
 
603
598
  export type StatusMessage = {
604
- type: 'status'
599
+ type: 'session:status'
605
600
  workspaceId: string
606
601
  sessionId: string
607
602
  activity: SessionActivity
@@ -636,6 +631,8 @@ export type WorkspaceLayout = {
636
631
  theme?: WorkspaceTheme
637
632
  }
638
633
 
634
+ export type WorkspaceLayoutPatch = Partial<Pick<WorkspaceLayout, 'widgetGrid' | 'theme'>>
635
+
639
636
  // GET /api/workspaces/:id returns either a complete local layout or a remote reference.
640
637
  type WorkspaceRouting = { apiBase: string; cwd: string }
641
638
  type WorkspaceMetadata = { name: string; harness?: HarnessType; agentId?: string }
@@ -760,7 +757,7 @@ export type Model = {
760
757
  }
761
758
 
762
759
  // GET /api/workspaces/:id/harness. Model changes arrive on refetch;
763
- // `harness:updated` events refresh availability.
760
+ // `harness:changed` events refresh availability.
764
761
  export type WorkspaceHarness = {
765
762
  /** Credential overrides require workspace readiness instead of shared account status. */
766
763
  hasAuthOverrides?: boolean
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.13.1-next.3",
3
+ "version": "0.13.1-next.4",
4
4
  "description": "Local AI workspace powered by the Claude Agent SDK, Bun, React, and Tailwind. Requires Bun.",
5
5
  "license": "Elastic-2.0",
6
6
  "type": "module",
package/server/AGENTS.md CHANGED
@@ -1,11 +1,11 @@
1
- Bun server on port 13337 by default. Serves the client at `/`, upgrades `/ws` to WebSocket. Read [README.md](README.md) for the directory map, storage ownership, and test commands.
1
+ Bun server on port 13337 by default. Serves the client at `/`; the WebSocket routes are listed under “Live connections” in the README. Read [README.md](README.md) for the directory map, storage ownership, and test commands.
2
2
 
3
- - `web.ts` owns the Bun fullstack surface only: the SPA HTML shell (dev bundler + HMR / prebuilt `dist/`), the two WebSocket channels (`/ws` chat, `/api/workspaces/ws` live events), and graceful shutdown. Every HTTP API request is delegated to the Hono app via `fetch`.
3
+ - `web.ts` owns the Bun fullstack surface only: the SPA HTML shell (dev bundler + HMR / prebuilt `dist/`), WebSocket routing, and graceful shutdown. Every HTTP API request is delegated to the Hono app via `fetch`.
4
4
  - `api/index.ts` assembles the Hono REST API (all `/api/*` routes). Harness authentication routes live in `api/harnesses.ts`. `personalWorkspace` and `ownerWorkspace` middleware resolve `:id` → workspace (404 if missing) and stash it on the context, so handlers read `c.get('ws')`. Declare the policy on each workspace route; owner routes reject local references to remote workspaces. Its catch-all serves the prebuilt client from `dist/` in prod via Hono's `serveStatic` (cached, traversal-safe).
5
5
  - API tests live in `api/` without an `api-` filename prefix. Unit tests stay beside their modules; existing integration and fixture-based tests live in `test/`.
6
6
  - `cli.ts` is the executable entry point and loads color setup before the command tree. `cli/index.ts` owns command registration, root help, and demo/managed-user gates; `cli/commands/` holds one module per top-level command, with its subcommands and private helpers. Shared CLI support lives directly in `cli/`. Server launches use `PACKAGE_ROOT` to find the entry point and package files, independent of the command module's location.
7
7
  - `scratchpad/` owns document persistence and reads (`document.ts`), asset files and cleanup (`assets.ts`), headless writes (`executor.ts` and `shape-defaults.ts`), and browser operation forwarding (`relay.ts`). Its unit tests live beside those modules.
8
- - `static.ts` exposes the `dist/` location (`DIST_DIR`), the `prebuilt` flag, and the prod SPA `distShell`. `events.ts` holds `publishEvent` (server→client live-event broadcast over `/api/workspaces/ws`) decoupled from `web.ts` to avoid an import cycle; `web.ts` wires it via `setEventServer`.
8
+ - `static.ts` exposes the `dist/` location (`DIST_DIR`), the `prebuilt` flag, and the prod SPA `distShell`. `events.ts` holds `publishEvent` decoupled from `web.ts` to avoid an import cycle; `web.ts` wires it via `setEventServer`.
9
9
  - `state.ts` holds the connected chat clients and `broadcast()` (which also feeds the harness debug tap).
10
10
  - `workspaces/` owns discovery, registration, provisioning, layout, environment settings, and workspace presentation. `workspaces/layout.ts` is the sole reader/writer of `.moi/.workspace.json`; `workspaces/registry.ts` stores the local workspace list in `DATA_DIR`.
11
11
  - `sessions/` owns Moi's session metadata, selections and pins, renames, archiving, attachment preparation, and pending-view handoffs. Provider history and live provider sessions stay in `harness/`.
package/server/README.md CHANGED
@@ -5,21 +5,21 @@ WebSocket handlers, and CLI commands call the same feature modules.
5
5
 
6
6
  ## Where code belongs
7
7
 
8
- | Location | Owns |
9
- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
10
- | `api/` | Hono HTTP routes, request validation, workspace lookup middleware, and API tests. `index.ts` assembles and defines the main routes; `harnesses.ts` defines login routes. |
11
- | `cli/commands/` | One module per top-level CLI command, with its subcommands and private helpers. |
12
- | `cli/` | Command registration, help, CLI access gates, terminal formatting, control requests, and server launching. |
13
- | `workspaces/` | Workspace discovery and registration, creation/import, `.moi/` scaffolding, shared layout, theme, icons, file previews, and environment settings. |
14
- | `sessions/` | Moi's session metadata, selection and pin state, archiving, ID renames, message attachments, and pending-view chat handoffs. Provider-owned history stays in the harnesses. |
15
- | `workspace-state/` | Per-workspace `state.json` storage: one writer per workspace, transactions, atomic writes, lock timeout, a revision and a `state:changed` event per change, re-adoption of a removed workspace's id. |
16
- | `applets/` | View/widget manifests, source analysis, builds, CSS scoping, typechecking, bundle serving, server-function workers, thumbnails, UI component installation, and the error journal. |
17
- | `scratchpad/` | Canvas documents, assets, headless drawing, and browser screenshot requests. |
18
- | `skills/` | Bundled workspace skill installation, version checks, and updates. These modules manage the copies shipped under `workspace/`. |
19
- | `harness/` | Provider adapters, transports, sessions, discovery, authentication, and readiness. See [the harness guide](harness/README.md). |
20
- | `collab/` | Cloud collaboration workers, presence, proxy identity, and the optional collaboration skill. |
21
- | `onboarding/` | Idea discovery, its prompt and output validation, and workspace creation jobs. HTTP handlers live in [api/onboarding.ts](api/onboarding.ts). |
22
- | `test/` | Integration tests and existing tests that share fixtures. Other unit tests live beside their modules. |
8
+ | Location | Owns |
9
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
10
+ | `api/` | Hono HTTP routes, request validation, workspace lookup middleware, and API tests. `index.ts` assembles and defines the main routes; `harnesses.ts` defines login routes. |
11
+ | `cli/commands/` | One module per top-level CLI command, with its subcommands and private helpers. |
12
+ | `cli/` | Command registration, help, CLI access gates, terminal formatting, control requests, and server launching. |
13
+ | `workspaces/` | Workspace discovery and registration, creation/import, `.moi/` scaffolding, shared layout, theme, icons, file previews, and environment settings. |
14
+ | `sessions/` | Moi's session metadata, selection and pin state, archiving, ID renames, message attachments, and pending-view chat handoffs. Provider-owned history stays in the harnesses. |
15
+ | `workspace-state/` | Per-workspace `state.json` storage: one writer per workspace, transactions, atomic writes, lock timeout, a revision and a `personal-state:changed` event per change, re-adoption of a removed workspace's id. |
16
+ | `applets/` | View/widget manifests, source analysis, builds, CSS scoping, typechecking, bundle serving, server-function workers, thumbnails, UI component installation, and the error journal. |
17
+ | `scratchpad/` | Canvas documents, assets, headless drawing, and browser screenshot requests. |
18
+ | `skills/` | Bundled workspace skill installation, version checks, and updates. These modules manage the copies shipped under `workspace/`. |
19
+ | `harness/` | Provider adapters, transports, sessions, discovery, authentication, and readiness. See [the harness guide](harness/README.md). |
20
+ | `collab/` | Cloud collaboration workers, presence, proxy identity, and the optional collaboration skill. |
21
+ | `onboarding/` | Idea discovery, its prompt and output validation, and workspace creation jobs. HTTP handlers live in [api/onboarding.ts](api/onboarding.ts). |
22
+ | `test/` | Integration tests and existing tests that share fixtures. Other unit tests live beside their modules. |
23
23
 
24
24
  Use direct module imports such as `workspaces/registry` or `sessions/store`.
25
25
  Keep shared helpers in the feature that owns them. A folder does not imply a
@@ -58,6 +58,20 @@ workspace list; `harness/registry.ts` owns the available agent backends.
58
58
  New server wiring can stay at the root. Feature implementations belong in the
59
59
  corresponding directory above.
60
60
 
61
+ ## Live connections
62
+
63
+ | Socket | Source and scope |
64
+ | ---------------------------- | -------------------------------------------------------------------------------------------------------- |
65
+ | `/cloud/api/events` | Cloud account and membership changes (owned by Batiok) |
66
+ | `/api/events` | This machine's workspace list, app settings, personal state, environment, navigation and canvas commands |
67
+ | `/api/harness/events` | This machine's chats, run activity and harness readiness across workspaces |
68
+ | `/api/workspaces/:id/events` | Shared workspace updates and presence, served by the owner |
69
+
70
+ Remote shared connections use `ownerId:workspaceId`, just like owner HTTP requests.
71
+ The URL supplies workspace scope; shared event payloads omit `workspaceId`. The
72
+ browser attaches its local reference ID when notifying cache consumers. Personal
73
+ state and navigation always use the visitor's machine.
74
+
61
75
  ## Storage ownership
62
76
 
63
77
  | State | Location and owner |
@@ -11,13 +11,14 @@ import type { SpeedMode } from '@/lib/types'
11
11
  import { isSpeedMode } from '@/lib/speed-mode'
12
12
  import { isMessageAttachments } from '@/lib/message-attachments'
13
13
  import { Hono } from 'hono'
14
+ import { z } from 'zod'
15
+ import { AGENT_THEMES, COLOR_THEMES, FONT_THEMES, RADIUS_THEMES } from '@/lib/themes'
14
16
  import { serveStatic } from 'hono/bun'
15
17
  import { createMiddleware } from 'hono/factory'
16
18
  import { existsSync } from 'node:fs'
17
19
  import { basename, resolve } from 'node:path'
18
20
 
19
21
  import { UPDATE_ACTIVE_AGENT_MESSAGE } from '@/lib/update'
20
- import { resolveWorkspaceTheme } from '@/lib/themes'
21
22
  import { isWorkspaceIcon } from '@/lib/workspace-icon'
22
23
  import type {
23
24
  AppletKind,
@@ -43,12 +44,7 @@ import { applyEnvChanged } from '../workspaces/env-apply'
43
44
  import { publishEvent } from '../events'
44
45
  import { callFunction, parseFunctionPath } from '../applets/functions'
45
46
  import { processIcon } from '../workspaces/icon'
46
- import {
47
- getWorkspacePreview,
48
- loadLayout,
49
- mergeLayoutForSave,
50
- saveLayout
51
- } from '../workspaces/layout'
47
+ import { getWorkspacePreview, mergeLayoutForSave, updateLayout } from '../workspaces/layout'
52
48
  import {
53
49
  getAppletThumbnailRecords,
54
50
  isValidAppletId,
@@ -512,7 +508,7 @@ one.get('/uploads/:uploadId', personalWorkspace, c => {
512
508
  })
513
509
  })
514
510
 
515
- // Personal state writes return the latest snapshot and publish `state:changed`.
511
+ // Personal state writes return the latest snapshot and publish `personal-state:changed`.
516
512
  one.get('/state', personalWorkspace, async c => c.json(await getWorkspaceState(c.get('ws'))))
517
513
 
518
514
  one.put('/state/tabs', personalWorkspace, async c => {
@@ -767,9 +763,7 @@ one.get('/harness', personalWorkspace, async c => {
767
763
  // Gateway-backed harnesses still have workspace-specific readiness.
768
764
  harness.authStatus && !hasAuthOverrides
769
765
  ? Promise.resolve({ status: 'available' as const })
770
- : refresh
771
- ? harnessStore.refresh(ws)
772
- : harnessStore.getAvailability(ws),
766
+ : harnessStore.getAvailability(ws, refresh),
773
767
  harness.listModels(ws).catch(err => {
774
768
  console.error(`[api] listModels failed for ${harness.id}`, err)
775
769
  return []
@@ -807,7 +801,11 @@ one.put('/config', ownerWorkspace, async c => {
807
801
  return c.text('Expected a workspace config field', 400)
808
802
  }
809
803
  await setWorkspaceConfig(ws.path, { name, icon })
810
- publishEvent({ type: 'workspace:updated', workspaceId: ws.id, origin: eventOrigin(body.origin) })
804
+ publishEvent({
805
+ type: 'workspace-config:changed',
806
+ workspaceId: ws.id,
807
+ origin: eventOrigin(body.origin)
808
+ })
811
809
  return c.json(await getWorkspaceConfig(ws.path))
812
810
  })
813
811
 
@@ -847,7 +845,7 @@ one.put('/scratchpad', ownerWorkspace, async c => {
847
845
  }
848
846
  await saveScratchpadDoc(body.document, ws.path)
849
847
  publishEvent({
850
- type: 'scratchpad:updated',
848
+ type: 'scratchpad:changed',
851
849
  workspaceId: ws.id,
852
850
  origin: eventOrigin(body.origin)
853
851
  })
@@ -906,13 +904,13 @@ one.put('/icon', ownerWorkspace, async c => {
906
904
  }
907
905
  const workspaceIcon = { type: 'upload', value: icon } as const
908
906
  await setWorkspaceConfig(ws.path, { icon: workspaceIcon })
909
- publishEvent({ type: 'workspace:updated', workspaceId: c.get('ws').id })
907
+ publishEvent({ type: 'workspace-config:changed', workspaceId: c.get('ws').id })
910
908
  return c.json({ icon: workspaceIcon })
911
909
  })
912
910
 
913
911
  one.delete('/icon', ownerWorkspace, async c => {
914
912
  await setWorkspaceConfig(c.get('ws').path, { icon: null })
915
- publishEvent({ type: 'workspace:updated', workspaceId: c.get('ws').id })
913
+ publishEvent({ type: 'workspace-config:changed', workspaceId: c.get('ws').id })
916
914
  return c.body(null, 204)
917
915
  })
918
916
 
@@ -995,6 +993,33 @@ one.put('/applet-thumbnails', ownerWorkspace, async c => {
995
993
  return c.body(null, 204)
996
994
  })
997
995
 
996
+ function themePreset<T extends string>(presets: Record<T, unknown>) {
997
+ return z.custom<T>(value => typeof value === 'string' && Object.hasOwn(presets, value))
998
+ }
999
+
1000
+ const layoutPatchSchema = z
1001
+ .strictObject({
1002
+ theme: z
1003
+ .strictObject({
1004
+ font: themePreset(FONT_THEMES),
1005
+ color: themePreset(COLOR_THEMES),
1006
+ radius: themePreset(RADIUS_THEMES),
1007
+ agent: themePreset(AGENT_THEMES)
1008
+ })
1009
+ .optional(),
1010
+ widgetGrid: z
1011
+ .array(
1012
+ z.object({
1013
+ i: z.string().min(1),
1014
+ x: z.int().nonnegative(),
1015
+ y: z.int().nonnegative()
1016
+ })
1017
+ )
1018
+ .optional(),
1019
+ origin: z.string().optional()
1020
+ })
1021
+ .refine(patch => patch.theme !== undefined || patch.widgetGrid !== undefined)
1022
+
998
1023
  one.put('/', personalWorkspace, async c => {
999
1024
  const ws = c.get('ws')
1000
1025
  if (ws.remote) {
@@ -1003,20 +1028,16 @@ one.put('/', personalWorkspace, async c => {
1003
1028
  403
1004
1029
  )
1005
1030
  }
1006
- const body = await c.req.json()
1007
- if (!body || body.version !== 2) return c.text('Bad request', 400)
1008
- // `origin` is the writing tab's id, echoed so that tab skips its own event.
1009
- const { origin } = body
1010
- // Only widgets and theme are taken from the body, so a grid/theme save can't
1011
- // erase a `moi config`-set name or icon. See mergeLayoutForSave.
1012
- const existing = await loadLayout(ws.path)
1013
- const next = mergeLayoutForSave(existing, body)
1014
- await saveLayout(next, ws.path)
1015
- if (
1016
- JSON.stringify(resolveWorkspaceTheme(existing.theme)) !==
1017
- JSON.stringify(resolveWorkspaceTheme(next.theme))
1018
- ) {
1019
- publishEvent({ type: 'theme:updated', workspaceId: ws.id, origin: eventOrigin(origin) })
1031
+ const patch = layoutPatchSchema.safeParse(await c.req.json().catch(() => null))
1032
+ if (!patch.success) return c.text('Invalid layout patch', 400)
1033
+ const { origin, ...layout } = patch.data
1034
+ const { changed } = await updateLayout(ws.path, current => mergeLayoutForSave(current, layout))
1035
+ if (changed) {
1036
+ publishEvent({
1037
+ type: 'workspace-config:changed',
1038
+ workspaceId: ws.id,
1039
+ origin
1040
+ })
1020
1041
  }
1021
1042
  return c.body(null, 204)
1022
1043
  })
@@ -1077,9 +1098,9 @@ workspaces.put('/order', async c => {
1077
1098
  const hiddenIds = all.filter(entry => !visible.has(entry.id)).map(entry => entry.id)
1078
1099
  const entries = await reorderWorkspaces([...body.ids, ...hiddenIds])
1079
1100
  // List-only change: a narrow event so clients refetch just the sidebar
1080
- // list, not every per-workspace query (`workspace:updated` also triggers
1101
+ // list, not every per-workspace query (`workspace-config:changed` also triggers
1081
1102
  // layout refetches in open workspaces).
1082
- publishEvent({ type: 'workspaces-list:updated', origin: eventOrigin(body.origin) })
1103
+ publishEvent({ type: 'workspaces-list:changed', origin: eventOrigin(body.origin) })
1083
1104
  return c.json(await mergeWorkspaceList(visibleWorkspaces(entries)))
1084
1105
  } catch (err) {
1085
1106
  const message = err instanceof Error ? err.message : String(err)
@@ -1218,13 +1239,11 @@ workspaces.post('/create', async c => {
1218
1239
  await setWorkspaceConfig(path, { name })
1219
1240
  const entry = await registerWorkspace(path, { id: basename(path), harness, name })
1220
1241
  // Nudge every connected client (the sidebar list) to refetch.
1221
- publishEvent({ type: 'workspaces-list:updated' })
1242
+ publishEvent({ type: 'workspaces-list:changed' })
1222
1243
  return c.json(entry, 201)
1223
1244
  })
1224
1245
 
1225
1246
  // `/:id` is registered after the static `/discover` so the literal path wins.
1226
- // `/api/workspaces/ws` (the live-event WebSocket) is intercepted by Bun's routes
1227
- // table before it ever reaches Hono, so it never collides with `:id`.
1228
1247
  workspaces.route('/:id', one)
1229
1248
 
1230
1249
  // ---- top-level API ----------------------------------------------------------
@@ -1306,7 +1325,7 @@ api.patch('/api/settings', async c => {
1306
1325
  }
1307
1326
  // Other open clients hold these in a query cache with no polling; broadcast
1308
1327
  // the new value so an app-wide preference applies everywhere immediately.
1309
- publishEvent({ type: 'settings:updated', settings })
1328
+ publishEvent({ type: 'app-settings:changed', settings })
1310
1329
  return c.json(settings)
1311
1330
  })
1312
1331