moi-computer 0.13.1-next.2 → 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 (109) 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/chat/sessions/use-selected-session.ts +0 -13
  13. package/client/features/collab/presence/client.ts +63 -83
  14. package/client/features/collab/presence/provider.tsx +8 -2
  15. package/client/features/dev/chat-states-page.tsx +1 -1
  16. package/client/features/dev/harness-debug-page.tsx +2 -2
  17. package/client/features/scratchpad/scratchpad.tsx +29 -20
  18. package/client/features/views/api.ts +38 -14
  19. package/client/features/views/use-view-actions.ts +2 -23
  20. package/client/features/workspace/api.ts +6 -11
  21. package/client/features/workspace/harness-transition.ts +3 -5
  22. package/client/features/workspace/remote.ts +9 -0
  23. package/client/features/workspace/settings/use-env-vars.ts +4 -4
  24. package/client/features/workspace/tab-resolution.ts +1 -8
  25. package/client/features/workspace/use-workspace-navigation.ts +5 -4
  26. package/client/features/workspace/use-workspace-socket.ts +51 -0
  27. package/client/features/workspace/workspace-content.tsx +5 -18
  28. package/client/features/workspace/workspace-layout-context.tsx +6 -13
  29. package/client/features/workspace/workspace-preferences.ts +67 -10
  30. package/client/features/workspace/workspace-state.ts +57 -21
  31. package/client/runtime/app-context.ts +2 -2
  32. package/client/runtime/app-events.ts +75 -0
  33. package/client/runtime/reconnecting-socket.ts +115 -0
  34. package/client/runtime/{use-workspace-events.ts → use-client-events.ts} +9 -10
  35. package/client/store/ui.ts +1 -6
  36. package/client/store/workspace-session.ts +30 -0
  37. package/dist/chunk-0t8m1ehd.js +2 -0
  38. package/dist/chunk-851bx8ss.js +72 -0
  39. package/dist/{chunk-n0fawy9x.js → chunk-c8g5x288.js} +1 -1
  40. package/dist/chunk-cty37f3v.js +1 -0
  41. package/dist/chunk-dy6f6h3e.js +5 -0
  42. package/dist/chunk-j6928pwm.js +1 -0
  43. package/dist/{chunk-rmd0ctfx.js → chunk-k32585ne.js} +73 -73
  44. package/dist/chunk-qtkv7hp8.js +2 -0
  45. package/dist/chunk-rh58dc0y.js +2 -0
  46. package/dist/{chunk-ec5ennpv.js → chunk-wjbejzek.js} +1 -1
  47. package/dist/index.html +1 -1
  48. package/lib/events.ts +61 -0
  49. package/lib/ids.ts +2 -8
  50. package/lib/moi-context.ts +19 -5
  51. package/lib/types.ts +16 -20
  52. package/lib/workspace-layout.ts +3 -20
  53. package/package.json +2 -1
  54. package/server/AGENTS.md +4 -4
  55. package/server/README.md +50 -33
  56. package/server/api/index.ts +175 -152
  57. package/server/applets/views.ts +15 -14
  58. package/server/applets/widgets.ts +4 -3
  59. package/server/cli/commands/init.ts +7 -2
  60. package/server/cli/commands/refresh.ts +2 -5
  61. package/server/cli/commands/remote.ts +128 -26
  62. package/server/cli/remote-control.ts +12 -9
  63. package/server/cli/remote-operations.ts +47 -44
  64. package/server/control.ts +33 -34
  65. package/server/events.ts +14 -13
  66. package/server/harness/README.md +7 -7
  67. package/server/harness/acp/session.ts +9 -5
  68. package/server/harness/auth.ts +7 -30
  69. package/server/harness/claude-code/session.ts +8 -4
  70. package/server/harness/codex/NOTES.md +1 -1
  71. package/server/harness/codex/session.ts +18 -10
  72. package/server/harness/hermes/NOTES.md +3 -3
  73. package/server/harness/openclaw/session.ts +9 -5
  74. package/server/onboarding/jobs.ts +8 -8
  75. package/server/operations/commands.ts +1 -1
  76. package/server/remote/broker-client.ts +76 -0
  77. package/server/remote/broker.ts +81 -0
  78. package/server/remote/client.ts +212 -152
  79. package/server/remote/errors.ts +2 -0
  80. package/server/remote/routes.ts +121 -0
  81. package/server/scratchpad/document.ts +3 -2
  82. package/server/scratchpad/executor.ts +2 -2
  83. package/server/scratchpad/relay.ts +3 -3
  84. package/server/sessions/archive.ts +1 -1
  85. package/server/sessions/lifecycle.ts +1 -1
  86. package/server/sessions/pending-views.ts +19 -12
  87. package/server/sessions/send-message.ts +102 -0
  88. package/server/sessions/view-sessions.ts +4 -94
  89. package/server/web.ts +42 -31
  90. package/server/workspace-state/file.ts +2 -0
  91. package/server/workspace-state/index.ts +15 -4
  92. package/server/workspaces/api.ts +4 -8
  93. package/server/workspaces/config.ts +14 -13
  94. package/server/workspaces/env-apply.ts +1 -1
  95. package/server/workspaces/layout.ts +40 -7
  96. package/server/workspaces/shared.ts +1 -1
  97. package/server/workspaces/tabs.ts +1 -2
  98. package/skill/SKILL.md +75 -34
  99. package/skill/references/SCRATCHPAD.md +4 -0
  100. package/skill/references/UI-COMPONENTS.md +1 -1
  101. package/client/features/scratchpad/scratch-executor.ts +0 -20
  102. package/client/runtime/workspace-events.ts +0 -168
  103. package/dist/chunk-44khk4sp.js +0 -2
  104. package/dist/chunk-ba6mz56s.js +0 -72
  105. package/dist/chunk-ectsnw81.js +0 -2
  106. package/dist/chunk-en7w5ypg.js +0 -1
  107. package/dist/chunk-f695wcx5.js +0 -5
  108. package/dist/chunk-pdt9hxfw.js +0 -2
  109. package/dist/chunk-zv22wv0g.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-44khk4sp.js";import{h}from"/chunk-pdt9hxfw.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-44khk4sp.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
@@ -27,8 +27,9 @@ const MOI_CONTEXT_OPEN = '<moi-context>'
27
27
  const MOI_CONTEXT_CLOSE = '</moi-context>'
28
28
  // Start of the first line inside the tag. Doubles as the strip guard: a user
29
29
  // literally typing `<moi-context>` in their message won't have their text
30
- // eaten. Keep this phrase byte-stable when rewording the envelope.
31
- const MOI_CONTEXT_MARKER = 'You are running in a `moi` workspace'
30
+ // eaten. Retain older markers so persisted chat history still strips correctly.
31
+ const MOI_CONTEXT_MARKER = 'You are in a Moi workspace'
32
+ const LEGACY_MOI_CONTEXT_MARKER = 'You are running in a `moi` workspace'
32
33
 
33
34
  const SYSTEM_REMINDER_OPEN = '<system-reminder>'
34
35
  const SYSTEM_REMINDER_CLOSE = '</system-reminder>'
@@ -57,6 +58,8 @@ export type TabContext = {
57
58
  // the server for programmatic pending-view sends. Extend this (and
58
59
  // `renderMoiContext`) when new ambient fields land.
59
60
  export type MoiContext = {
61
+ // Server-resolved; the browser cannot choose the execution location.
62
+ workspaceMode?: 'local' | 'remote'
60
63
  // Server-resolved path to the installed COLLAB.md reference for this workspace.
61
64
  collabReference?: string
62
65
  // The workspace tab the user is on when they hit send.
@@ -133,10 +136,16 @@ function describeTab(tab: Pick<TabContext, 'id' | 'title'>): string {
133
136
  // wrapped text would double-wrap it.
134
137
  export function renderMoiContextBody(ctx: MoiContext): string {
135
138
  const preamble = [
136
- `${MOI_CONTEXT_MARKER} — a shared UI the user chats with you from, which you can extend and customize.`,
137
- 'Read the **`moi-workspace` skill** before responding — even to a simple question — unless you already read it in this chat.'
139
+ `${MOI_CONTEXT_MARKER}: a shared UI where the user chats with you, which you can extend and customize.`,
140
+ 'Read the `moi-workspace` skill before responding unless already read in this chat.'
138
141
  ].join('\n')
139
142
  const sections: string[] = []
143
+ if (ctx.workspaceMode) {
144
+ const lines = [`Workspace: ${ctx.workspaceMode}`]
145
+ if (ctx.workspaceMode === 'remote')
146
+ lines.push('You run in a local directory linked to a remote workspace.')
147
+ sections.push(lines.join('\n'))
148
+ }
140
149
  const appletIsActiveView =
141
150
  ctx.applet?.kind === 'view' && ctx.activeTab?.id === `views/${ctx.applet.id}`
142
151
  if (ctx.activeTab) {
@@ -186,6 +195,7 @@ export function renderMoiContext(ctx: MoiContext): string {
186
195
  export function isMoiContext(value: unknown): value is MoiContext {
187
196
  if (!isParamsRecord(value)) return false
188
197
  const v = value as {
198
+ workspaceMode?: unknown
189
199
  collabReference?: unknown
190
200
  activeTab?: unknown
191
201
  applet?: unknown
@@ -193,6 +203,9 @@ export function isMoiContext(value: unknown): value is MoiContext {
193
203
  directives?: unknown
194
204
  }
195
205
  return (
206
+ (v.workspaceMode === undefined ||
207
+ v.workspaceMode === 'local' ||
208
+ v.workspaceMode === 'remote') &&
196
209
  (v.activeTab === undefined || isTabContext(v.activeTab)) &&
197
210
  (v.collabReference === undefined || typeof v.collabReference === 'string') &&
198
211
  (v.applet === undefined || isAppletContext(v.applet)) &&
@@ -263,7 +276,8 @@ function stripOneMoiContext(text: string): string {
263
276
  if (start === -1) return text
264
277
  const end = text.indexOf(MOI_CONTEXT_CLOSE, start)
265
278
  if (end === -1) return text
266
- if (!text.slice(start, end).includes(MOI_CONTEXT_MARKER)) return text
279
+ const body = text.slice(start, end)
280
+ if (!body.includes(MOI_CONTEXT_MARKER) && !body.includes(LEGACY_MOI_CONTEXT_MARKER)) return text
267
281
  let before = text.slice(0, start)
268
282
  let after = text.slice(end + MOI_CONTEXT_CLOSE.length)
269
283
  if (
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,8 +310,11 @@ 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 = {
315
+ // Personal tab list/order, excluding the always-open Overview.
316
+ // Missing opens all available tabs; an empty list opens only Overview.
317
+ openTabs?: WorkspaceTabId[]
318
318
  // Personal defaults for new chats on this Moi installation.
319
319
  chatDefaults?: SessionConfig
320
320
  // Goes up by one with every saved change. Lets clients drop an older copy
@@ -396,11 +396,9 @@ export type ServerMessage =
396
396
  | SessionRenamedMessage
397
397
  | SessionsChangedMessage
398
398
  | SessionArchivedMessage
399
- | WorkspaceSwitchMessage
400
399
  | ErrorFrame
401
400
  | StoppedFrame
402
401
  | StatusSnapshotMessage
403
- | ScratchpadOpMessage
404
402
 
405
403
  // A live token-by-token snapshot of an assistant message still being generated.
406
404
  // Ephemeral: it is NOT a StreamEvent, never persisted, and never folded into the
@@ -409,7 +407,7 @@ export type ServerMessage =
409
407
  // lands. `blocks[].text` is CUMULATIVE, so a lost/reordered/duplicated frame is
410
408
  // simply overwritten by the next one — it can never corrupt the transcript.
411
409
  export type PreviewFrame = {
412
- type: 'preview'
410
+ type: 'session:preview'
413
411
  workspaceId: string
414
412
  sessionId: string
415
413
  // API message id (`msg_...`), globally unique — the accumulator key, so
@@ -450,12 +448,12 @@ export type BroadcastFrame =
450
448
  // clears a spinner whose terminal `status` frame was lost (disconnect window,
451
449
  // dropped frame, harness gap).
452
450
  export type StatusSnapshotMessage = {
453
- type: 'status_snapshot'
451
+ type: 'sessions:status-snapshot'
454
452
  sessions: { workspaceId: string; sessionId: string; activity: SessionActivity }[]
455
453
  }
456
454
 
457
- export type WorkspaceSwitchMessage = {
458
- type: 'workspace:switch'
455
+ export type WorkspaceOpenRequestMessage = {
456
+ type: 'workspace:open-requested'
459
457
  workspaceId: string
460
458
  }
461
459
 
@@ -554,20 +552,20 @@ export type DiscoveredWorkspace = {
554
552
  }
555
553
 
556
554
  export type SessionRenamedMessage = {
557
- type: 'session_renamed'
555
+ type: 'session:renamed'
558
556
  workspaceId: string
559
557
  from: string
560
558
  to: string
561
559
  }
562
560
 
563
561
  export type SessionsChangedMessage = {
564
- type: 'sessions_changed'
562
+ type: 'sessions:changed'
565
563
  workspaceId: string
566
564
  sessionId: string
567
565
  }
568
566
 
569
567
  export type SessionArchivedMessage = {
570
- type: 'session_archived'
568
+ type: 'session:archived'
571
569
  workspaceId: string
572
570
  sessionId: string
573
571
  }
@@ -598,7 +596,7 @@ export type StoppedFrame = {
598
596
  export type SessionActivity = 'idle' | 'running' | 'requires-action'
599
597
 
600
598
  export type StatusMessage = {
601
- type: 'status'
599
+ type: 'session:status'
602
600
  workspaceId: string
603
601
  sessionId: string
604
602
  activity: SessionActivity
@@ -614,11 +612,7 @@ export type LayoutMode = 'fullscreen' | 'split'
614
612
 
615
613
  export type WorkspaceTabId = 'overview' | 'scratchpad' | `views/${string}`
616
614
 
617
- // Open tabs plus the workspace's saved DEFAULT tab. `active` is not live focus
618
- // state — the live active tab is each browser tab's URL (`/workspace/:id/<tab>`).
619
- // The saved default answers one question: where a bare `/workspace/:id` lands
620
- // (and which row `moi tabs` marks). Navigating writes it, so it tracks the last
621
- // tab switch, last writer wins across clients.
615
+ // Client tab list and remembered active tab; the URL determines live focus.
622
616
  export type WorkspaceTabsState = {
623
617
  open: WorkspaceTabId[]
624
618
  active: WorkspaceTabId
@@ -637,6 +631,8 @@ export type WorkspaceLayout = {
637
631
  theme?: WorkspaceTheme
638
632
  }
639
633
 
634
+ export type WorkspaceLayoutPatch = Partial<Pick<WorkspaceLayout, 'widgetGrid' | 'theme'>>
635
+
640
636
  // GET /api/workspaces/:id returns either a complete local layout or a remote reference.
641
637
  type WorkspaceRouting = { apiBase: string; cwd: string }
642
638
  type WorkspaceMetadata = { name: string; harness?: HarnessType; agentId?: string }
@@ -761,7 +757,7 @@ export type Model = {
761
757
  }
762
758
 
763
759
  // GET /api/workspaces/:id/harness. Model changes arrive on refetch;
764
- // `harness:updated` events refresh availability.
760
+ // `harness:changed` events refresh availability.
765
761
  export type WorkspaceHarness = {
766
762
  /** Credential overrides require workspace readiness instead of shared account status. */
767
763
  hasAuthOverrides?: boolean
@@ -2,26 +2,9 @@ import { createDefaultWidgetGrid } from './default-widgets'
2
2
  import type { WorkspaceLayout, WorkspaceTabsState } from './types'
3
3
  import { isWorkspaceTabId } from './workspace-tabs'
4
4
 
5
- export function createDefaultWorkspaceTabs(): WorkspaceTabsState {
6
- return { open: ['overview'], active: 'overview' }
7
- }
8
-
9
- export function normalizeWorkspaceTabs(value: unknown): WorkspaceTabsState {
10
- const defaults = createDefaultWorkspaceTabs()
11
- if (!value || typeof value !== 'object') return defaults
12
-
13
- const raw = value as Record<string, unknown>
14
- const savedOpen = Array.isArray(raw.open)
15
- ? raw.open.filter(isWorkspaceTabId).filter((tab, index, all) => all.indexOf(tab) === index)
16
- : []
17
- if (savedOpen.length === 0) return defaults
18
-
19
- const open = [
20
- 'overview',
21
- ...savedOpen.filter(tab => tab !== 'overview')
22
- ] satisfies WorkspaceTabsState['open']
23
- const active = isWorkspaceTabId(raw.active) && open.includes(raw.active) ? raw.active : 'overview'
24
- return { open, active }
5
+ export function normalizeOpenTabs(value: unknown): WorkspaceTabsState['open'] {
6
+ if (!Array.isArray(value)) return []
7
+ return [...new Set(value.filter(tab => isWorkspaceTabId(tab) && tab !== 'overview'))]
25
8
  }
26
9
 
27
10
  export function createDefaultWorkspaceLayout(): WorkspaceLayout {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.13.1-next.2",
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",
@@ -104,6 +104,7 @@
104
104
  "react-markdown": "^10.1.0",
105
105
  "react-resizable": "^3.2.0",
106
106
  "react-resizable-panels": "^4.12.4",
107
+ "regexparam": "^3.0.0",
107
108
  "rehype-highlight": "^7.0.2",
108
109
  "remark-gfm": "^4.0.1",
109
110
  "shadcn": "4.21.0",
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`.
4
- - `api/index.ts` assembles the Hono REST API (all `/api/*` routes). Harness authentication routes live in `api/harnesses.ts`. `withWorkspace` middleware resolves `:id` → workspace (404 if missing) and stashes it on the context, so handlers read `c.get('ws')`. Its catch-all serves the prebuilt client from `dist/` in prod via Hono's `serveStatic` (cached, traversal-safe).
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
+ - `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,27 +5,31 @@ 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
26
26
  strict dependency layer: workspace setup installs skills, applets use workspace
27
27
  environment settings, and view builds coordinate with session metadata.
28
28
 
29
+ [sessions/send-message.ts](sessions/send-message.ts) prepares and sends workspace messages
30
+ for chat, onboarding, and view builds, including the agent context envelope.
31
+ [sessions/view-sessions.ts](sessions/view-sessions.ts) owns view creation and build handoffs.
32
+
29
33
  The two registries have different jobs: `workspaces/registry.ts` owns the local
30
34
  workspace list; `harness/registry.ts` owns the available agent backends.
31
35
 
@@ -54,26 +58,39 @@ workspace list; `harness/registry.ts` owns the available agent backends.
54
58
  New server wiring can stay at the root. Feature implementations belong in the
55
59
  corresponding directory above.
56
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
+
57
75
  ## Storage ownership
58
76
 
59
- | State | Location and owner |
60
- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
61
- | Workspace widget layout and theme | `.moi/.workspace.json`, read and written by `workspaces/layout.ts` |
62
- | Applet source | `.moi/views/`, `.moi/widgets/`, and shared workspace source |
63
- | Generated bundles and thumbnails | `.moi/.build/` and `.moi/.cache/`; re-creatable |
64
- | Scratchpad document and image bytes | `.moi/.scratchpad.json` and `.moi/.scratchpad/`; preserve both |
65
- | Installation-wide app settings, including `showOnboarding` | `DATA_DIR/settings.json`, owned by `app-settings.ts` |
66
- | Onboarding discovery results and workspace creation operation records | `DATA_DIR/onboarding/`, owned by [onboarding/jobs.ts](onboarding/jobs.ts) |
67
- | Registered workspaces | `DATA_DIR/workspaces.json`, owned by `workspaces/registry.ts` |
68
- | Chat defaults; session attribution, settings, and fork metadata; selected and pinned sessions; pending view creation | `DATA_DIR/workspaces/<workspace id>/state.json`, stored by `workspace-state/`; meaning owned by `sessions/store.ts`, `sessions/selected.ts`, and `sessions/pending-views.ts` |
69
- | Workspace environment preferences and secrets | `workspaces/env.ts`; metadata in `DATA_DIR`, secrets in the OS keychain or file fallback |
70
- | Provider credentials and conversation history | Owned by each provider; see `harness/README.md` |
71
-
72
- Open tabs, the active tab, split/fullscreen mode and panel widths live per workspace in the browser UI store (`moi:ui` in localStorage).
73
-
74
- Client-local UI choices are documented in [the root instructions](../AGENTS.md)
75
- and [view/chat behavior](../docs/view-chats.md). Changing a module's location
76
- must not change its storage paths or persisted formats.
77
+ | State | Location and owner |
78
+ | --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
79
+ | Workspace widget layout and theme | `.moi/.workspace.json`, read and written by `workspaces/layout.ts` |
80
+ | Applet source | `.moi/views/`, `.moi/widgets/`, and shared workspace source |
81
+ | Generated bundles and thumbnails | `.moi/.build/` and `.moi/.cache/`; re-creatable |
82
+ | Scratchpad document and image bytes | `.moi/.scratchpad.json` and `.moi/.scratchpad/`; preserve both |
83
+ | Installation-wide app settings, including `showOnboarding` | `DATA_DIR/settings.json`, owned by `app-settings.ts` |
84
+ | Onboarding discovery results and workspace creation operation records | `DATA_DIR/onboarding/`, owned by [onboarding/jobs.ts](onboarding/jobs.ts) |
85
+ | Registered workspaces | `DATA_DIR/workspaces.json`, owned by `workspaces/registry.ts` |
86
+ | Personal tabs and chat state, including pending views | `DATA_DIR/workspaces/<workspace id>/state.json`, stored by `workspace-state/`; session metadata managed by `sessions/` |
87
+ | Workspace environment preferences and secrets | `workspaces/env.ts`; metadata in `DATA_DIR`, secrets in the OS keychain or file fallback |
88
+ | Provider credentials and conversation history | Owned by each provider; see `harness/README.md` |
89
+
90
+ The active tab and floating-chat visibility live per workspace in sessionStorage (`moi:workspace-session`). Split/fullscreen mode and panel widths live in localStorage (`moi:ui`).
91
+
92
+ See [navigation](../docs/navigation.md) and [view/chat behavior](../docs/view-chats.md) for how
93
+ this state is used. Moving a module must not change its storage paths or persisted formats.
77
94
 
78
95
  ## Paths and process boundaries
79
96