moi-computer 0.11.1-next.4 → 0.12.0

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 (131) hide show
  1. package/client/api/app-config.ts +7 -4
  2. package/client/app/AppRouter.tsx +2 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +27 -19
  4. package/client/features/applets/{AppletMount.tsx → AppletContainer.tsx} +7 -5
  5. package/client/features/applets/WidgetShell.tsx +3 -3
  6. package/client/features/applets/applet-cache.ts +3 -5
  7. package/client/features/applets/applet-runtime.ts +27 -12
  8. package/client/features/applets/applet-thumbnail.ts +2 -1
  9. package/client/features/chat/applet-chat-intents.ts +14 -6
  10. package/client/features/chat/composer/attachments/draft-attachments.ts +21 -4
  11. package/client/features/chat/messages/MarkdownContent.tsx +5 -2
  12. package/client/features/chat/sessions/browser-tab-state.ts +18 -0
  13. package/client/features/chat/sessions/useSelectedSession.ts +55 -21
  14. package/client/features/chat/useChat.ts +4 -0
  15. package/client/features/collab/applet-api.ts +34 -0
  16. package/client/features/collab/client.ts +239 -0
  17. package/client/features/collab/components/cursors.tsx +199 -0
  18. package/client/features/collab/components/presence-avatars.tsx +61 -0
  19. package/client/features/collab/components/presence-frame.tsx +126 -0
  20. package/client/features/collab/components/presence-group.tsx +23 -0
  21. package/client/features/collab/components/presence-helpers.ts +50 -0
  22. package/client/features/collab/components/user-avatar-group.tsx +22 -0
  23. package/client/features/collab/components/user-avatar.tsx +40 -0
  24. package/client/features/collab/components/user.tsx +50 -0
  25. package/client/features/collab/hooks.tsx +164 -0
  26. package/client/features/collab/host-state.ts +254 -0
  27. package/client/features/collab/index.ts +5 -0
  28. package/client/features/collab/local-user.ts +46 -0
  29. package/client/features/collab/presence-publisher.ts +30 -0
  30. package/client/features/collab/presence-target.ts +8 -0
  31. package/client/features/collab/provider.tsx +79 -0
  32. package/client/features/collab/proxy-user.ts +35 -0
  33. package/client/features/collab/store.ts +156 -0
  34. package/client/features/collab/testing/component-fixtures.tsx +54 -0
  35. package/client/features/collab/testing/fake-engine.ts +129 -0
  36. package/client/features/collab/users.ts +106 -0
  37. package/client/features/collab/workspace-users-menu.tsx +194 -0
  38. package/client/features/connectors/mcp-icons.ts +0 -2
  39. package/client/features/dev/DevIndexPage.tsx +5 -0
  40. package/client/features/dev/DevRoutes.tsx +16 -4
  41. package/client/features/dev/collab/collab-page.tsx +24 -0
  42. package/client/features/dev/collab/collab-playground.tsx +614 -0
  43. package/client/features/dev/collab/local-user-settings.tsx +166 -0
  44. package/client/features/dev/collab/playground-room.ts +33 -0
  45. package/client/features/dev/{UiComponentsPage.tsx → ui-components/ui-components-page.tsx} +1 -1
  46. package/client/features/overview/WidgetCanvas.tsx +3 -1
  47. package/client/features/views/ViewManager.tsx +12 -7
  48. package/client/features/views/api.ts +2 -2
  49. package/client/features/views/useViewBuilderActions.ts +3 -0
  50. package/client/features/workspace/WorkspaceContext.tsx +1 -1
  51. package/client/features/workspace/WorkspaceLayoutContext.tsx +8 -2
  52. package/client/features/workspace/WorkspaceScreen.tsx +19 -11
  53. package/client/features/workspace/WorkspaceTabs.tsx +3 -3
  54. package/client/features/workspace/api.ts +2 -1
  55. package/client/features/workspace/browser-tab-state.ts +44 -0
  56. package/client/features/workspace/layout-save.ts +13 -0
  57. package/client/features/workspace/moi-context.ts +2 -1
  58. package/client/features/workspace/useWorkspaceNavigation.ts +20 -8
  59. package/client/index.css +45 -0
  60. package/client/index.tsx +9 -4
  61. package/client/main.tsx +1 -11
  62. package/client/theme.css +4 -1
  63. package/dist/chunk-2jncyq65.js +1 -0
  64. package/dist/{chunk-brr0zbeh.js → chunk-3a48fyf7.js} +2 -2
  65. package/dist/{chunk-tzz101ea.js → chunk-97eg9mjn.js} +1 -1
  66. package/dist/chunk-e2q5ken7.js +68 -0
  67. package/dist/{chunk-zs4mte79.js → chunk-efdyz6xp.js} +1 -1
  68. package/dist/chunk-h2kj1ysj.js +1 -0
  69. package/dist/chunk-jf6czgrz.js +2 -0
  70. package/dist/chunk-nez8sdta.js +1 -0
  71. package/dist/chunk-nzwgm8vc.css +1 -0
  72. package/dist/chunk-ph0h6h86.js +1 -0
  73. package/dist/chunk-ryg9z3kn.js +10 -0
  74. package/dist/chunk-tpn177bt.js +2 -0
  75. package/dist/chunk-vfpsc75k.js +2 -0
  76. package/dist/{chunk-m1fvqssh.js → chunk-z3byfve5.js} +2 -2
  77. package/dist/index.html +1 -1
  78. package/lib/collab/colors.ts +30 -0
  79. package/lib/collab/protocol.ts +84 -0
  80. package/lib/collab/types.ts +52 -0
  81. package/lib/experimental.ts +14 -0
  82. package/lib/moi-context.ts +11 -3
  83. package/lib/navigation.ts +25 -5
  84. package/lib/types.ts +20 -33
  85. package/package.json +2 -2
  86. package/server/AGENTS.md +1 -1
  87. package/server/api.ts +28 -5
  88. package/server/app-config.ts +127 -34
  89. package/server/applet-typecheck.ts +8 -3
  90. package/server/applets/applet-css.ts +1 -1
  91. package/server/applets/build-applet.ts +9 -3
  92. package/server/applets/declarations/base.d.ts +75 -0
  93. package/server/applets/declarations/collab.d.ts +88 -0
  94. package/server/applets/declarations.ts +46 -0
  95. package/server/applets/index.ts +8 -8
  96. package/server/applets/runtime/collab.ts +94 -0
  97. package/server/applets/runtime/moi.ts +12 -19
  98. package/server/applets/runtime/rpc.ts +2 -4
  99. package/server/chat-selection.ts +22 -0
  100. package/server/cli.ts +86 -21
  101. package/server/collab/cloudflare-access.ts +78 -0
  102. package/server/collab/config.ts +18 -0
  103. package/server/collab/manager.ts +407 -0
  104. package/server/collab/service.ts +136 -0
  105. package/server/collab/skill/index.ts +53 -0
  106. package/server/collab/worker-messages.ts +10 -0
  107. package/server/collab/worker.ts +52 -0
  108. package/server/layout.ts +10 -3
  109. package/server/moi-scaffold.ts +55 -84
  110. package/server/preview.ts +1 -1
  111. package/server/skill-update.ts +7 -9
  112. package/server/skills-template.ts +14 -2
  113. package/server/web.ts +65 -17
  114. package/server/workspace-init.ts +6 -3
  115. package/ui-components/avatar.tsx +24 -11
  116. package/ui-components/button.tsx +9 -9
  117. package/ui-components/docs/avatar.md +11 -30
  118. package/workspace/.claude/skills/moi-workspace/SKILL.md +14 -11
  119. package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +262 -0
  120. package/workspace/.claude/skills/moi-workspace/references/INTENTS.md +10 -7
  121. package/client/assets/mcp/agentation.png +0 -0
  122. package/dist/agentation-4s0nn45p.png +0 -0
  123. package/dist/chunk-2gs8jjx4.css +0 -1
  124. package/dist/chunk-7vvg5fyz.js +0 -68
  125. package/dist/chunk-94m3q9ce.js +0 -1
  126. package/dist/chunk-by2wqgak.js +0 -1
  127. package/dist/chunk-p34hvqt3.js +0 -1
  128. package/dist/chunk-p83f0jnj.js +0 -2
  129. package/dist/chunk-xg01f6pn.js +0 -10
  130. /package/client/features/dev/{UiComponentPreviews.tsx → ui-components/ui-component-previews.tsx} +0 -0
  131. /package/server/applets/{runtime/base.ts → api-base.ts} +0 -0
@@ -0,0 +1,2 @@
1
+ var X=["pink","orange","amber","lime","emerald","cyan","blue","violet"];function V(f){return typeof f==="string"&&X.includes(f)}function Z(f){let A=2166136261;for(let C=0;C<f.length;C++)A^=f.charCodeAt(C),A=Math.imul(A,16777619);return X[(A>>>0)%X.length]??X[0]}var o=1;var w=8192,D=320;function H(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function j(f,A=256){return typeof f==="string"&&f.length>0&&!f.includes("\x00")&&new TextEncoder().encode(f).length<=A}function $(f){return H(f)&&j(f.id,240)&&f.id.trim().length>0&&(f.name===void 0||j(f.name)&&f.name.trim().length>0)&&V(f.color)&&(f.avatar===void 0||j(f.avatar,w))&&(f.email===void 0||j(f.email,D))}var I=["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 y(f,A){let C=f.filter((g)=>g!==A);return C[Math.floor(Math.random()*C.length)]??f[0]}function R(f){return{name:y(I,f?.name),color:y(X,f?.color)}}function m(f,A){let C=A.name.trim();return{id:f,...C?{name:C}:{},color:A.color}}function Y(){return m(`local-${crypto.randomUUID().slice(0,8)}`,R())}var W="moi:collab:dev-profile",T,F=!1,M,J=new Set,_=new Map,E=new Set,b=Object.freeze({}),L=Object.freeze({status:"loading"}),N;function n(f){if(!f||typeof f.id!=="string"||!f.id.trim())throw Error("A user profile needs an id.");if(f.name!==void 0&&typeof f.name!=="string")throw Error("A user profile name must be a string when provided.");if(f.color!==void 0&&!V(f.color))throw Error("A user profile color must be one of the user palette names.");let A=f.id.trim(),C=f.name?.trim(),g={id:A,...C?{name:C}:{},color:f.color??Z(A),...f.avatar!==void 0?{avatar:f.avatar}:{},...f.email!==void 0?{email:f.email}:{}};if(!$(g))throw Error("Invalid user profile.");return Object.freeze(g)}function k(f){if(!Array.isArray(f))throw Error("Workspace users must be an array.");let A=new Set,C=f.map((g)=>{let B=n(g);if(A.has(B.id))throw Error("Workspace users must have unique ids.");return A.add(B.id),B});return Object.freeze(C)}function z(f){if(!f||typeof f!=="object")throw Error("Invalid host state.");let A=f.currentUser===void 0?void 0:n(f.currentUser);if(!f.workspaces||typeof f.workspaces!=="object"||Array.isArray(f.workspaces))throw Error("Host workspaces must be a record.");let C=Object.entries(f.workspaces).map(([g,B])=>{if(!g.trim()||!B||typeof B!=="object")throw Error("Invalid workspace directory.");if(B.status==="loading")return[g,L];if(B.status!=="ready")throw Error("Invalid workspace directory status.");let x=k(B.users),P=Object.freeze(x.map((Q)=>A&&Q.id===A.id?A:Q));return[g,Object.freeze({status:"ready",users:P})]});return Object.freeze({currentUser:A,workspaces:A?Object.freeze(Object.fromEntries(C)):b})}function G(){return N}function O(f){if(!N)return;return(Object.hasOwn(N.workspaces,f)?N.workspaces[f]:void 0)??L}function q(f){let A=z(f),C=new Map([..._.keys()].map((g)=>[g,O(g)]));N=A,M="external",T=A.currentUser,J.forEach((g)=>g());for(let[g,B]of _)if(O(g)!==C.get(g))B.forEach((x)=>x());E.forEach((g)=>g())}function h(f){return E.add(f),()=>{E.delete(f)}}function p(f){let A=h(()=>f(G()));return f(G()),A}function l(f,A){let C=_.get(f);if(!C)C=new Set,_.set(f,C);return C.add(A),()=>{if(C.delete(A),!C.size)_.delete(f)}}function s(){return T}function r(f){return J.add(f),()=>{J.delete(f)}}function e({provider:f,profile:A}){if(M==="external")return;if(f===void 0){if(M===void 0||M==="local")return;M=void 0,T=void 0}else{let C=A===void 0?void 0:n(A);if(M===f&&JSON.stringify(T)===JSON.stringify(C))return;M=f,T=C}J.forEach((C)=>C())}function S(){try{sessionStorage.setItem(W,JSON.stringify(T))}catch{}}function K(f){if(M!==void 0&&M!=="local")return;let A=n(f);M="local",T=A,S(),J.forEach((C)=>C())}function ff(f,A){if(!f||!A||A.provider!==void 0||M!==void 0)return;try{let C=sessionStorage.getItem(W);if(C){K(JSON.parse(C));return}}catch{}K(Y())}function Af(){if(typeof window>"u"||F)return;F=!0;let f=window,A=f.moi?.collab;if(A?.getHostState)try{q(A.getHostState()??{workspaces:{}})}catch{q({workspaces:{}})}f.moi??={};let C={getHostState:G,setHostState:q,subscribeHostState:p};if(f.moi.collab=C,typeof window.dispatchEvent==="function")window.dispatchEvent(new CustomEvent("moi:collab-ready"))}
2
+ export{o as Fc,O as Gc,l as Hc,s as Ic,r as Jc,e as Kc,ff as Lc,Af as Mc};
@@ -0,0 +1,2 @@
1
+ async function s(t,e){let o=await t.text();return Error(o||e)}async function i(t,e,o="Request failed"){let n=await fetch(t,e);if(!n.ok)throw await s(n,o);return n.json()}async function r(t,e,o="Request failed"){let n=await fetch(t,e);if(!n.ok)throw await s(n,o)}function a(t,e){return{method:t,headers:{"Content-Type":"application/json"},body:e===void 0?void 0:JSON.stringify(e)}}
2
+ export{i as Nc,r as Oc,a as Pc};
@@ -1,2 +1,2 @@
1
- import{Nc as J,Oc as Z}from"/chunk-tzz101ea.js";var U=Z((O,G)=>{G.exports=globalThis.__esm.react});var B=J(U(),1);var $=J(U(),1);function K(m){let h=$.useRef(m);return $.useLayoutEffect(()=>{h.current=m},[m]),h}function Q(m){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${m}`}var y=new Set,j=new Set,S=!1,T=null,u=!1,q=1000,X=30000,z=0;function D(){let m=Math.min(q*2**z,X);z++,setTimeout(V,m)}function V(){if(T||u)return;u=!0;let m=new WebSocket(Q("/api/workspaces/ws"));m.onopen=()=>{if(T=m,u=!1,z=0,b(),S)for(let h of j)h();S=!0},m.onmessage=(h)=>{try{let x=JSON.parse(h.data);for(let f of y)f(x)}catch{}},m.onclose=()=>{if(T=null,u=!1,y.size>0)D()},m.onerror=()=>{m.close()}}function _(m){return j.add(m),()=>{j.delete(m)}}function L(m){let h=K(m);B.useEffect(()=>{let x=(f)=>h.current(f);return y.add(x),V(),()=>{if(y.delete(x),y.size===0&&T)T.close(),T=null}},[h])}var H=null;function b(){if(T?.readyState!==WebSocket.OPEN)return;T.send(JSON.stringify({type:"navigation:presence",workspaceId:H,focused:document.visibilityState==="visible"&&document.hasFocus()}))}function g(m,h){B.useEffect(()=>{return H=m,b(),window.addEventListener("focus",b),document.addEventListener("visibilitychange",b),()=>{H=null,b(),window.removeEventListener("focus",b),document.removeEventListener("visibilitychange",b)}},[m]),L((x)=>{if(x.type!=="navigation:request"||x.workspaceId!==m)return;let f=T;try{if(H!==m)throw Error("The browser switched workspaces.");h(x.href),f?.send(JSON.stringify({type:"navigation:result",requestId:x.requestId,ok:!0}))}catch(F){f?.send(JSON.stringify({type:"navigation:result",requestId:x.requestId,error:F instanceof Error?F.message:"Navigation failed"}))}})}
2
- export{U as Hc,Q as Ic,K as Jc,_ as Kc,L as Lc,g as Mc};
1
+ import{Wc as J,Xc as Z}from"/chunk-97eg9mjn.js";var U=Z((O,G)=>{G.exports=globalThis.__esm.react});var B=J(U(),1);var $=J(U(),1);function K(m){let h=$.useRef(m);return $.useLayoutEffect(()=>{h.current=m},[m]),h}function Q(m){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${m}`}var y=new Set,j=new Set,S=!1,T=null,u=!1,q=1000,X=30000,z=0;function D(){let m=Math.min(q*2**z,X);z++,setTimeout(V,m)}function V(){if(T||u)return;u=!0;let m=new WebSocket(Q("/api/workspaces/ws"));m.onopen=()=>{if(T=m,u=!1,z=0,b(),S)for(let h of j)h();S=!0},m.onmessage=(h)=>{try{let x=JSON.parse(h.data);for(let f of y)f(x)}catch{}},m.onclose=()=>{if(T=null,u=!1,y.size>0)D()},m.onerror=()=>{m.close()}}function _(m){return j.add(m),()=>{j.delete(m)}}function L(m){let h=K(m);B.useEffect(()=>{let x=(f)=>h.current(f);return y.add(x),V(),()=>{if(y.delete(x),y.size===0&&T)T.close(),T=null}},[h])}var H=null;function b(){if(T?.readyState!==WebSocket.OPEN)return;T.send(JSON.stringify({type:"navigation:presence",workspaceId:H,focused:document.visibilityState==="visible"&&document.hasFocus()}))}function g(m,h){B.useEffect(()=>{return H=m,b(),window.addEventListener("focus",b),document.addEventListener("visibilitychange",b),()=>{H=null,b(),window.removeEventListener("focus",b),document.removeEventListener("visibilitychange",b)}},[m]),L((x)=>{if(x.type!=="navigation:request"||x.workspaceId!==m)return;let f=T;try{if(H!==m)throw Error("The browser switched workspaces.");h(x.href),f?.send(JSON.stringify({type:"navigation:result",requestId:x.requestId,ok:!0}))}catch(F){f?.send(JSON.stringify({type:"navigation:result",requestId:x.requestId,error:F instanceof Error?F.message:"Navigation failed"}))}})}
2
+ export{U as Qc,Q as Rc,K as Sc,_ as Tc,L as Uc,g as Vc};
package/dist/index.html CHANGED
@@ -36,7 +36,7 @@
36
36
  }
37
37
  </script>
38
38
 
39
- <link rel="stylesheet" crossorigin href="/chunk-2gs8jjx4.css"><script type="module" crossorigin src="/chunk-by2wqgak.js"></script></head>
39
+ <link rel="stylesheet" crossorigin href="/chunk-nzwgm8vc.css"><script type="module" crossorigin src="/chunk-ph0h6h86.js"></script></head>
40
40
  <body>
41
41
  <div id="root"></div>
42
42
 
@@ -0,0 +1,30 @@
1
+ import type { UserColor } from 'moi/collab'
2
+
3
+ export type { UserColor } from 'moi/collab'
4
+
5
+ // The eight Tailwind palette names available for users. Their shades live in CSS.
6
+ export const USER_COLORS = [
7
+ 'pink',
8
+ 'orange',
9
+ 'amber',
10
+ 'lime',
11
+ 'emerald',
12
+ 'cyan',
13
+ 'blue',
14
+ 'violet'
15
+ ] as const satisfies readonly UserColor[]
16
+
17
+ export function isUserColor(value: unknown): value is UserColor {
18
+ return typeof value === 'string' && (USER_COLORS as readonly string[]).includes(value)
19
+ }
20
+
21
+ // A random-looking but stable pick (FNV-1a), so a user id gets the same color
22
+ // on the server and in every browser.
23
+ export function colorForId(id: string): UserColor {
24
+ let hash = 0x811c9dc5
25
+ for (let index = 0; index < id.length; index++) {
26
+ hash ^= id.charCodeAt(index)
27
+ hash = Math.imul(hash, 0x01000193)
28
+ }
29
+ return USER_COLORS[(hash >>> 0) % USER_COLORS.length] ?? USER_COLORS[0]
30
+ }
@@ -0,0 +1,84 @@
1
+ import type { JsonValue } from 'moi'
2
+ import { isUserColor } from './colors'
3
+ import type { CollabClientMessage, ConnectionLocation, UserProfile } from './types'
4
+
5
+ export const COLLAB_PROTOCOL_VERSION = 1
6
+ export const COLLAB_MAX_CONNECTIONS = 64
7
+ export const COLLAB_MAX_REGISTRATIONS = 128
8
+ export const COLLAB_MAX_MESSAGE_BYTES = 256 * 1024
9
+ export const COLLAB_MAX_PRESENCE_BYTES = 4 * 1024
10
+ export const COLLAB_MAX_AVATAR_BYTES = 8 * 1024
11
+ export const COLLAB_MAX_EMAIL_BYTES = 320
12
+
13
+ export function isRecord(value: unknown): value is Record<string, unknown> {
14
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
15
+ }
16
+
17
+ export function isCollabString(value: unknown, max = 256): value is string {
18
+ return (
19
+ typeof value === 'string' &&
20
+ value.length > 0 &&
21
+ !value.includes('\0') &&
22
+ new TextEncoder().encode(value).length <= max
23
+ )
24
+ }
25
+
26
+ export function isCollabJson(value: unknown, depth = 0): value is JsonValue {
27
+ if (depth > 24) return false
28
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return true
29
+ if (typeof value === 'number') return Number.isFinite(value)
30
+ if (Array.isArray(value)) return value.every(item => isCollabJson(item, depth + 1))
31
+ if (!isRecord(value)) return false
32
+ return Object.values(value).every(item => isCollabJson(item, depth + 1))
33
+ }
34
+
35
+ export function isUserProfile(value: unknown): value is UserProfile {
36
+ return (
37
+ isRecord(value) &&
38
+ isCollabString(value.id, 240) &&
39
+ value.id.trim().length > 0 &&
40
+ (value.name === undefined || (isCollabString(value.name) && value.name.trim().length > 0)) &&
41
+ isUserColor(value.color) &&
42
+ (value.avatar === undefined || isCollabString(value.avatar, COLLAB_MAX_AVATAR_BYTES)) &&
43
+ (value.email === undefined || isCollabString(value.email, COLLAB_MAX_EMAIL_BYTES))
44
+ )
45
+ }
46
+
47
+ function isLocation(value: unknown): value is ConnectionLocation | null {
48
+ return (
49
+ value === null ||
50
+ (isRecord(value) &&
51
+ isCollabString(value.page, 1024) &&
52
+ (value.status === 'active' || value.status === 'away'))
53
+ )
54
+ }
55
+
56
+ export function isCollabClientMessage(value: unknown): value is CollabClientMessage {
57
+ if (!isRecord(value)) return false
58
+ switch (value.type) {
59
+ case 'join':
60
+ return (
61
+ value.version === COLLAB_PROTOCOL_VERSION &&
62
+ isUserProfile(value.profile) &&
63
+ (value.location === undefined || isLocation(value.location))
64
+ )
65
+ case 'profile':
66
+ return isUserProfile(value.profile)
67
+ case 'location':
68
+ return isLocation(value.location)
69
+ case 'presence:set':
70
+ return (
71
+ isCollabString(value.registrationId) &&
72
+ isCollabString(value.appletId) &&
73
+ isCollabString(value.channel) &&
74
+ isCollabJson(value.value) &&
75
+ new TextEncoder().encode(JSON.stringify(value.value)).length <= COLLAB_MAX_PRESENCE_BYTES
76
+ )
77
+ case 'presence:delete':
78
+ return isCollabString(value.registrationId)
79
+ case 'ping':
80
+ return true
81
+ default:
82
+ return false
83
+ }
84
+ }
@@ -0,0 +1,52 @@
1
+ import type { JsonValue } from 'moi'
2
+ import type { ConnectionStatus, UserProfile } from 'moi/collab'
3
+
4
+ export type { ConnectionStatus, UserProfile } from 'moi/collab'
5
+
6
+ // An authenticating proxy in front of the deployment that moi trusts.
7
+ export type AuthProvider = 'cloudflare-access'
8
+
9
+ // Complete snapshot from GET /api/proxy-user. No provider means no proxy;
10
+ // a provider without a profile means no verified user.
11
+ export type ProxyUserState = {
12
+ provider?: AuthProvider
13
+ profile?: UserProfile
14
+ }
15
+
16
+ export type ConnectionLocation = { page: string; status: ConnectionStatus }
17
+
18
+ export type PresenceRegistration = {
19
+ registrationId: string
20
+ appletId: string
21
+ channel: string
22
+ value: JsonValue
23
+ }
24
+
25
+ export type Connection = {
26
+ connectionId: string
27
+ userId: string
28
+ location: ConnectionLocation | null
29
+ presence: PresenceRegistration[]
30
+ }
31
+
32
+ export type CollabClientMessage =
33
+ | { type: 'join'; version: 1; profile: UserProfile; location?: ConnectionLocation | null }
34
+ | { type: 'profile'; profile: UserProfile }
35
+ | { type: 'location'; location: ConnectionLocation | null }
36
+ | ({ type: 'presence:set' } & PresenceRegistration)
37
+ | { type: 'presence:delete'; registrationId: string }
38
+ | { type: 'ping' }
39
+
40
+ export type CollabServerMessage =
41
+ | {
42
+ type: 'welcome'
43
+ version: 1
44
+ connectionId: string
45
+ connections: Connection[]
46
+ // Profile fallback for currently connected users only. The host owns
47
+ // the full workspace directory, including users who are offline.
48
+ users: UserProfile[]
49
+ }
50
+ | { type: 'connections'; connections: Connection[]; users: UserProfile[] }
51
+ | { type: 'error'; code: string; message: string }
52
+ | { type: 'pong' }
@@ -0,0 +1,14 @@
1
+ // Add a default here to register an experimental startup feature. The CLI and
2
+ // browser config both use these keys.
3
+ export const EXPERIMENTAL_DEFAULTS = {
4
+ collab: false
5
+ } satisfies Record<string, false>
6
+
7
+ export type ExperimentalFeatures = { [Key in keyof typeof EXPERIMENTAL_DEFAULTS]: boolean }
8
+ export type ExperimentalFeature = keyof ExperimentalFeatures
9
+
10
+ export const EXPERIMENTAL_FEATURES = Object.keys(EXPERIMENTAL_DEFAULTS) as ExperimentalFeature[]
11
+
12
+ export function experimentalFlagName(feature: string): string {
13
+ return `experimental-${feature.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`)}`
14
+ }
@@ -7,9 +7,9 @@
7
7
  //
8
8
  // Flow: a structured `MoiContext` is assembled at send time — by the client
9
9
  // for chat sends (client/features/workspace/moi-context.ts, sent as the chat
10
- // frame's `context`), by the server for view-builder requests — and travels
11
- // structured all the way to the harness, which renders it with the transform
12
- // matching its conventions:
10
+ // frame's `context`), by the server for view-builder requests. The server adds
11
+ // the optional collab reference path before the harness renders the context with
12
+ // the transform matching its conventions:
13
13
  // - Claude Code — `moiContextSystemReminder` as its own leading text block
14
14
  // (mirrors how Claude Code itself injects ambient context; a string
15
15
  // prefix would defeat the SDK's first-prompt extraction, which skips
@@ -45,6 +45,8 @@ export type MoiAppletMessage = {
45
45
  // the server for programmatic sends (the view builder). Extend this (and
46
46
  // `renderMoiContext`) when new ambient fields land.
47
47
  export type MoiContext = {
48
+ // Server-resolved path to the installed COLLAB.md reference for this workspace.
49
+ collabReference?: string
48
50
  // The workspace tab the user is on when they hit send — for a view-builder
49
51
  // request that's the builder's own tab (`view-builders/<id>`).
50
52
  activeTab: WorkspaceTabId
@@ -151,6 +153,10 @@ export function renderMoiContextBody(ctx: MoiContext): string {
151
153
  const tabParams = ctx.tabParams ? renderTabParams(ctx.tabParams) : null
152
154
  if (tabParams) tabLines.push(`Params it is rendering with right now: ${tabParams}`)
153
155
  const sections = [`# Active tab\n${tabLines.join('\n')}`]
156
+ if (ctx.collabReference)
157
+ sections.push(
158
+ `# Collab\nThe collab runtime is available. Before writing collaborative applets, read ${escapeTags(ctx.collabReference)}.`
159
+ )
154
160
  if (ctx.applet) {
155
161
  sections.push(
156
162
  `# Applet message\nThe message above was not typed by the user — the ${describeAppletSource(ctx.applet.source)} sent it when the user acted in its UI.`
@@ -174,6 +180,7 @@ export function renderMoiContext(ctx: MoiContext): string {
174
180
  export function isMoiContext(value: unknown): value is MoiContext {
175
181
  if (typeof value !== 'object' || value === null) return false
176
182
  const v = value as {
183
+ collabReference?: unknown
177
184
  activeTab?: unknown
178
185
  tabTitle?: unknown
179
186
  tabParams?: unknown
@@ -182,6 +189,7 @@ export function isMoiContext(value: unknown): value is MoiContext {
182
189
  }
183
190
  return (
184
191
  typeof v.activeTab === 'string' &&
192
+ (v.collabReference === undefined || typeof v.collabReference === 'string') &&
185
193
  (v.tabTitle === undefined || typeof v.tabTitle === 'string') &&
186
194
  (v.tabParams === undefined || isParamsRecord(v.tabParams)) &&
187
195
  (v.applet === undefined || isMoiAppletMessage(v.applet)) &&
package/lib/navigation.ts CHANGED
@@ -67,13 +67,33 @@ export function workspaceTabPath(workspaceId: string, tab: WorkspaceTabId): stri
67
67
  return addressPath(workspaceId, { tab, search: '' })
68
68
  }
69
69
 
70
- export function resolveWorkspaceHref(workspaceId: string, href: string, base = ''): string {
71
- if (href.startsWith('moi:')) return addressPath(workspaceId, parseMoiHref(href), base)
70
+ type ResolveUrlContext = { apiBase: string; workspacePath?: string }
71
+
72
+ export function resolveUrl(url: string, context: ResolveUrlContext): string {
73
+ if (url.startsWith('moi:/files/')) {
74
+ const tail = url.slice('moi:/files/'.length)
75
+ const suffixIndex = tail.search(/[?#]/)
76
+ const pathname = suffixIndex < 0 ? tail : tail.slice(0, suffixIndex)
77
+ const suffix = suffixIndex < 0 ? '' : tail.slice(suffixIndex)
78
+ const segments = pathname.split('/').map(segment => {
79
+ const decoded = decodeURIComponent(segment)
80
+ if (!decoded || decoded === '.' || decoded === '..' || /[/\\\0]/.test(decoded)) {
81
+ throw new Error('Invalid workspace file path')
82
+ }
83
+ return encodeURIComponent(decoded)
84
+ })
85
+ return `${context.apiBase}/files/${segments.join('/')}${suffix}`
86
+ }
87
+ if (url.startsWith('moi:')) {
88
+ const { tab, search } = parseMoiHref(url)
89
+ return context.workspacePath ? `${context.workspacePath}/${tab}${search}` : ''
90
+ }
72
91
  // Only explicit ordinary web addresses may leave the workspace through the
73
92
  // imperative API. Native anchors keep their existing protocol policy.
74
- const url = new URL(href)
75
- if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('Unsupported URL')
76
- return url.href
93
+ const resolved = new URL(url)
94
+ if (resolved.protocol !== 'https:' && resolved.protocol !== 'http:')
95
+ throw new Error('Unsupported URL')
96
+ return resolved.href
77
97
  }
78
98
 
79
99
  export type NavigationRequest = {
package/lib/types.ts CHANGED
@@ -1,7 +1,11 @@
1
1
  import type { PreviewBlock, StreamEvent } from './format'
2
2
  import type { AppIconId } from './app-icons'
3
+ import type { ExperimentalFeatures } from './experimental'
3
4
  import type { MoiContext } from './moi-context'
4
5
  import type { WorkspaceTheme } from './themes'
6
+ import type { AttachmentInput, ViewConfig, WidgetConfig } from 'moi'
7
+
8
+ export type { AttachmentInput, ViewConfig, WidgetConfig } from 'moi'
5
9
 
6
10
  // A custom UI unit embedded in a workspace.
7
11
  export type AppletKind = 'view' | 'widget'
@@ -10,8 +14,8 @@ export type AppletKind = 'view' | 'widget'
10
14
  // Inputs stay unknown at this trust boundary; the browser host narrows them.
11
15
  export type AppletBridge = {
12
16
  addChatAttachment: (input: unknown) => void
13
- navigate: (href: unknown) => void
14
- resolveHref: (href: unknown) => string
17
+ navigate: (url: unknown) => void
18
+ resolveUrl: (url: unknown) => string
15
19
  sendChatMessage: (input: unknown, context?: unknown) => void
16
20
  }
17
21
 
@@ -22,15 +26,6 @@ export type AppletInfo = {
22
26
  revision?: string
23
27
  }
24
28
 
25
- export type WidgetConfig = {
26
- rowSpan: 1 | 2 | 3 | 4
27
- colSpan: 1 | 2 | 3 | 4
28
- // Env vars this widget's `.server.ts` expects (e.g. `ELEVENLABS_API_KEY`).
29
- // Purely advisory: it lets the UI surface a "missing key" hint. It never
30
- // blocks loading — the server function still just reads `process.env`.
31
- requiredEnv?: string[]
32
- }
33
-
34
29
  export type WidgetInfo = AppletInfo & {
35
30
  config: WidgetConfig
36
31
  }
@@ -38,15 +33,6 @@ export type WidgetInfo = AppletInfo & {
38
33
  // A view is a full-screen, agent-authored "app" (`.moi/views/<name>.tsx`),
39
34
  // shown one-at-a-time in the workspace nav. Same build/RPC machinery as a
40
35
  // widget, minus the grid: no sizing, the view owns its own layout and scroll.
41
- export type ViewConfig = {
42
- // Nav tab label. Falls back to the file name when unset.
43
- title?: string
44
- // App icon registry id used by workspace tabs.
45
- icon?: string
46
- // Advisory env hints, same semantics as WidgetConfig.requiredEnv.
47
- requiredEnv?: string[]
48
- }
49
-
50
36
  export type ViewInfo = AppletInfo & {
51
37
  config: ViewConfig
52
38
  }
@@ -225,13 +211,7 @@ export type Attachment =
225
211
  | ({ type: 'image' } & ImageAttachment)
226
212
 
227
213
  // Caller input: text or a browser file / workspace-relative path.
228
- export type TextAttachmentInput = Pick<TextAttachment, 'label' | 'text'>
229
-
230
- type FileAttachmentInput = { file: File; path?: never } | { path: string; file?: never }
231
-
232
- export type AttachmentInput =
233
- | ({ type: 'text' } & TextAttachmentInput)
234
- | ({ type: 'file' } & FileAttachmentInput)
214
+ export type TextAttachmentInput = Omit<Extract<AttachmentInput, { type: 'text' }>, 'type'>
235
215
 
236
216
  // Upload receipt: returned by the upload API before sending the message.
237
217
  // Bytes or an absolute file path live in the server's workspace-scoped store.
@@ -255,6 +235,8 @@ export type MessageAttachment =
255
235
  | ({ type: 'upload'; uploadId: string; purpose?: DrawingPurpose } & Partial<AttachmentOrigin>)
256
236
 
257
237
  // Client → server messages, routed by workspaceId over the shared WebSocket.
238
+ export type SelectedSessionScope = 'shared' | 'browser-tab'
239
+
258
240
  export type ClientMessage =
259
241
  | {
260
242
  type: 'chat'
@@ -262,6 +244,9 @@ export type ClientMessage =
262
244
  content: string
263
245
  sessionId: string
264
246
  isNew: boolean
247
+ // Where this tab keeps its selected session. Browser-tab selection must
248
+ // not update the workspace's shared selection or switch other tabs.
249
+ selectedSessionScope?: SelectedSessionScope
265
250
  // Text and upload references for this turn. The server resolves uploads
266
251
  // and describes all attachments together, preserving their order.
267
252
  attachments?: MessageAttachment[]
@@ -334,20 +319,20 @@ export type AppSettings = {
334
319
  autoUpdateSkills: boolean
335
320
  }
336
321
 
337
- // Client-safe subset of the startup config (`config.json` in the data dir +
338
- // `MOI_*` env overrides), served by GET /api/config. Frozen for the process
339
- // lifetime — changing it requires a server restart, so clients may cache it
340
- // forever. See server/app-config.ts.
322
+ // Client-safe startup config, served by GET /api/config. Deployment settings
323
+ // come from config.json and MOI_* env overrides; experimental flags come from
324
+ // explicit CLI options. See server/app-config.ts.
341
325
  export type ClientAppConfig = {
342
326
  // Cloud demo deployment: workspace creation is blocked; the UI offers the
343
327
  // cloud-demo promo dialog instead.
344
328
  cloudDemo: boolean
345
- // Enabled experimental features, checked by slug.
346
- experiments: string[]
329
+ experimental: ExperimentalFeatures
347
330
  // Link target for the cloud-demo promo dialog.
348
331
  demoInstallUrl: string
349
332
  }
350
333
 
334
+ export type { ExperimentalFeatures } from './experimental'
335
+
351
336
  export type UpdateStatus = {
352
337
  runningVersion: string
353
338
  availableVersion: string | null
@@ -602,6 +587,8 @@ export type WorkspaceTabsState = {
602
587
 
603
588
  export type { AgentTheme, ColorTheme, FontTheme, RadiusTheme, WorkspaceTheme } from './themes'
604
589
 
590
+ export type WorkspaceLayoutSave = Omit<WorkspaceLayout, 'tabs'> & { tabs?: WorkspaceTabsState }
591
+
605
592
  export type WorkspaceLayout = {
606
593
  version: 1
607
594
  widgetGrid: LayoutGridItem[]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.11.1-next.4",
3
+ "version": "0.12.0",
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",
@@ -72,7 +72,6 @@
72
72
  "@tldraw/tlschema": "5.2.3",
73
73
  "@tldraw/utils": "5.2.3",
74
74
  "@types/bun": "1.3.10",
75
- "agentation": "^2.3.3",
76
75
  "blobatar": "^2.7.0",
77
76
  "bun-plugin-tailwind": "^0.1.2",
78
77
  "citty": "^0.2.2",
@@ -85,6 +84,7 @@
85
84
  "frimousse": "^0.3.0",
86
85
  "highlight.js": "^10.7.3",
87
86
  "hono": "^4.13.7",
87
+ "jose": "^6.2.12",
88
88
  "lru-cache": "^11.5.2",
89
89
  "modern-screenshot": "^4.7.0",
90
90
  "motion": "^12.43.0",
package/server/AGENTS.md CHANGED
@@ -7,5 +7,5 @@ Bun server on port 13337. Serves the client at `/`, upgrades `/ws` to WebSocket.
7
7
  - `applets/` owns shared view/widget machinery: dependency analysis, compilation, CSS scoping, bundle serving, and view source edits/cleanup. `views.ts` and `widgets.ts` own each kind's manifests and events.
8
8
  - `harness/` holds every agent backend (Claude Code, OpenClaw, Codex): per-harness adapter + session + transport + protocol NOTES, colocated. Read `harness/README.md` for the message-type layers, the adapter contract, and the folder conventions before touching agent-backend code.
9
9
  - WebSocket protocol: server sends `ServerMessage`, client sends `ClientMessage` — both defined in `lib/types.ts`.
10
- - Never import `react`, `react-dom`, or the `tldraw` package from `server/` or `lib/` — the server must not evaluate React (a global install can pair mismatched `react`/`react-dom` copies, and `react-dom` then throws at load). The scratchpad writer uses `@tldraw/store` + `@tldraw/tlschema` instead; `server/test/server-react-free.test.ts` enforces this. See `docs/moi-scratchpad.md`.
10
+ - Never import `react`, `react-dom`, or the `tldraw` package into server-evaluated code in `server/` or `lib/`. `applets/runtime/` contains applet runtime sources: `moi.ts`, `rpc.ts`, and `collab.ts` run in browser bundles; tests run in Bun. The shared API base constant lives in `applets/api-base.ts`. The server must not evaluate React (a global install can pair mismatched `react`/`react-dom` copies, and `react-dom` then throws at load). The scratchpad writer uses `@tldraw/store` + `@tldraw/tlschema` instead; `server/test/server-react-free.test.ts` enforces this. See `docs/moi-scratchpad.md`.
11
11
  - Agents run in the workspace directory; Claude Code and Codex approve every permission request by default (a `PreToolUse` allow hook and a transport-level accept, respectively) until UI approvals land. Each backend persists its own session history (see `harness/README.md`).
package/server/api.ts CHANGED
@@ -14,6 +14,7 @@ import type {
14
14
  AppSettings,
15
15
  HarnessAvailability,
16
16
  SessionInfo,
17
+ SelectedSessionScope,
17
18
  UploadInfo,
18
19
  ViewBuilderInput,
19
20
  WorkspaceAgent,
@@ -23,10 +24,14 @@ import type {
23
24
  import type { MoiContext } from '@/lib/moi-context'
24
25
  import { viewBuilderDirectives } from '@/lib/view-builder-directives'
25
26
 
27
+ import { proxyUserState } from './collab/cloudflare-access'
28
+ import { getCollabReferencePath } from './collab/config'
29
+ import { collabManager } from './collab/manager'
26
30
  import { agentStore } from './agent'
27
31
  import { clientAppConfig, getAppConfig } from './app-config'
28
32
  import { getAppSettings, pickAppSettingsPatch, saveAppSettings } from './app-settings'
29
33
  import { appletForModule, recordAppletError } from './applet-log'
34
+ import { selectChatSession } from './chat-selection'
30
35
  import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
31
36
  import { applyEnvChanged } from './env-apply'
32
37
  import { publishEvent } from './events'
@@ -298,6 +303,7 @@ one.post('/view-builders/:builderId/submit', async c => {
298
303
  const body = await c.req.json<{
299
304
  input?: Partial<ViewBuilderInput>
300
305
  optimisticId?: string
306
+ selectedSessionScope?: SelectedSessionScope
301
307
  model?: string
302
308
  effort?: string
303
309
  fastMode?: boolean
@@ -311,6 +317,13 @@ one.post('/view-builders/:builderId/submit', async c => {
311
317
  if (body.optimisticId !== undefined && typeof body.optimisticId !== 'string') {
312
318
  return c.text('Invalid optimisticId', 400)
313
319
  }
320
+ if (
321
+ body.selectedSessionScope !== undefined &&
322
+ body.selectedSessionScope !== 'shared' &&
323
+ body.selectedSessionScope !== 'browser-tab'
324
+ ) {
325
+ return c.text('Invalid selectedSessionScope', 400)
326
+ }
314
327
  const availableIcons = parseAvailableViewIcons(body.availableIcons)
315
328
  if (!availableIcons) return c.text('Available view icons are required', 400)
316
329
  const attachments = body.attachments ?? []
@@ -334,7 +347,9 @@ one.post('/view-builders/:builderId/submit', async c => {
334
347
  // The bootstrap instructions ride the moi-context envelope, injected by
335
348
  // the harness like any other ambient context; the user text stays bare.
336
349
  // The user submits from the builder's own tab, so that's the active tab.
350
+ const collabReference = await getCollabReferencePath(ws.path, ws.type)
337
351
  const context: MoiContext = {
352
+ ...(collabReference ? { collabReference } : {}),
338
353
  activeTab: `view-builders/${builder.id}`,
339
354
  directives: [
340
355
  ...viewBuilderDirectives(builder.id, availableIcons),
@@ -344,7 +359,7 @@ one.post('/view-builders/:builderId/submit', async c => {
344
359
  ]
345
360
  }
346
361
  try {
347
- publishSelectedSession(ws.id, await saveSelectedSession(ws.path, builder.sessionId))
362
+ await selectChatSession(ws, builder.sessionId, body.selectedSessionScope)
348
363
  await harnessFor(ws).sendMessage({
349
364
  workspaceId: ws.id,
350
365
  workspacePath: ws.path,
@@ -385,14 +400,14 @@ one.delete('/view-builders/:builderId', async c => {
385
400
  }
386
401
  })
387
402
 
388
- // Workspace file stream — an applet's `fileUrl(path)` resolves here. Streams a
403
+ // Workspace file stream — `resolveUrl('moi:/files/...')` resolves here. Streams a
389
404
  // media file from the workspace root (range-enabled). Guarded: traversal and
390
405
  // dotfiles (`.env`, `.moi`, `.git`) are rejected and only media/asset extensions
391
406
  // are allowed — the workspace holds secrets, and this route is unauthenticated.
392
407
  // localhost binding is NOT the guard.
393
- one.get('/fs/*', c => {
408
+ one.get('/files/*', c => {
394
409
  const ws = c.get('ws')
395
- const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/fs/`)[1] ?? ''
410
+ const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/files/`)[1] ?? ''
396
411
  return serveWorkspaceFile(ws.path, tail, c.req.header('range'), c.req.header('if-none-match'))
397
412
  })
398
413
 
@@ -453,7 +468,7 @@ one.post('/applet-log', async c => {
453
468
  })
454
469
 
455
470
  // Downscaled image preview of a workspace file. The chat's expanded tool rows
456
- // use this to show the picture an agent `Read` — same guards as /fs/ above,
471
+ // use this to show the picture an agent `Read` — same guards as /files/ above,
457
472
  // images only, resized server-side (see server/preview.ts).
458
473
  one.get('/preview/*', c => {
459
474
  const ws = c.get('ws')
@@ -980,6 +995,7 @@ one.delete('/', async c => {
980
995
  const ok = await removeWorkspace(ws.id)
981
996
  if (!ok) return c.text('Workspace not found', 404)
982
997
  harnessFor(ws).stopWorkspace?.(ws.path)
998
+ await collabManager.stopWorkspace(ws.path)
983
999
  return c.body(null, 204)
984
1000
  })
985
1001
 
@@ -1141,6 +1157,13 @@ api.route('/api/workspaces', workspaces)
1141
1157
  // subset. Immutable for the process lifetime — clients cache it forever.
1142
1158
  api.get('/api/config', c => c.json(clientAppConfig()))
1143
1159
 
1160
+ // The viewer's profile as verified by a configured proxy (Cloudflare Access).
1161
+ // It differs per request, so neither browsers nor Cloudflare's edge may cache it.
1162
+ api.get('/api/proxy-user', async c => {
1163
+ c.header('Cache-Control', 'private, no-store')
1164
+ return c.json(await proxyUserState(c.req.raw))
1165
+ })
1166
+
1144
1167
  // Served from a lazily-refreshed cache: this handler is a memory read, and the
1145
1168
  // registry is consulted on the schedule `getCachedUpdateStatus` owns rather
1146
1169
  // than once per request. `no-store` keeps the browser from adding a second,