moi-computer 0.9.1-next.0 → 0.9.1-next.1

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 (59) hide show
  1. package/client/api/app-config.ts +51 -0
  2. package/client/api/workspace-keys.ts +1 -0
  3. package/client/app/routes/WorkspaceRoute.tsx +4 -2
  4. package/client/features/applets/api.ts +38 -0
  5. package/client/features/applets/applet-thumbnail.ts +208 -0
  6. package/client/features/chat/ChatEmptyState.tsx +5 -3
  7. package/client/features/chat/ChatPanel.tsx +2 -8
  8. package/client/features/chat/ChatSelector.tsx +29 -10
  9. package/client/features/chat/MarkdownContent.tsx +2 -2
  10. package/client/features/home/HomePage.tsx +13 -0
  11. package/client/features/home/WorkspacePreview.tsx +10 -5
  12. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +9 -0
  13. package/client/features/home/workspace-setup/InstallMoiDialog.tsx +245 -0
  14. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +1 -1
  15. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +1 -1
  16. package/client/features/views/ViewBuilder.tsx +18 -4
  17. package/client/features/views/ViewManager.tsx +18 -2
  18. package/client/features/widgets/WidgetFrame.tsx +1 -1
  19. package/client/features/widgets/WidgetGrid.tsx +1 -1
  20. package/client/features/widgets/Widgets.tsx +16 -15
  21. package/client/features/workspace/CustomizePanel.tsx +29 -8
  22. package/client/features/workspace/WorkspaceScreen.tsx +8 -14
  23. package/client/index.tsx +6 -1
  24. package/client/runtime/useWorkspaceEvents.ts +17 -0
  25. package/client/runtime/workspace-theme.ts +29 -6
  26. package/dist/chunk-5c19v3zr.js +10 -0
  27. package/dist/chunk-6wx91x8j.js +1 -0
  28. package/dist/chunk-8s41nd3g.js +1 -0
  29. package/dist/{chunk-6w6j9g4b.js → chunk-a7fzp0z0.js} +2 -2
  30. package/dist/{chunk-pp62fnxh.js → chunk-b959mdkj.js} +1 -1
  31. package/dist/chunk-cagtq45k.js +1 -0
  32. package/dist/chunk-cva7jpt4.js +82 -0
  33. package/dist/chunk-sapvd7he.css +1 -0
  34. package/dist/{chunk-sxc24vfp.js → chunk-zbeq02yc.js} +1 -1
  35. package/dist/chunk-zbt8emsw.js +2 -0
  36. package/dist/chunk-zfz3b4xg.js +2 -0
  37. package/dist/index.html +1 -1
  38. package/lib/types.ts +60 -41
  39. package/package.json +1 -1
  40. package/server/api.ts +69 -31
  41. package/server/app-config.ts +144 -0
  42. package/server/applets.ts +17 -0
  43. package/server/cli.ts +47 -11
  44. package/server/layout.ts +40 -45
  45. package/server/moi-scaffold.ts +37 -1
  46. package/server/thumbnails.ts +197 -0
  47. package/server/views.ts +10 -1
  48. package/server/widgets.ts +4 -18
  49. package/workspace/.claude/skills/moi-workspace/SKILL.md +13 -1
  50. package/workspace/.claude/skills/moi-workspace/references/DESIGN.md +153 -253
  51. package/client/features/drawings/annotation-availability.ts +0 -10
  52. package/client/features/widgets/api.ts +0 -47
  53. package/client/features/widgets/useWidgetThumbnails.ts +0 -107
  54. package/client/features/widgets/widget-snapshot.ts +0 -71
  55. package/dist/chunk-3becmq75.js +0 -81
  56. package/dist/chunk-8ew39cvq.js +0 -10
  57. package/dist/chunk-c8gtrjwp.js +0 -1
  58. package/dist/chunk-v964b5g7.js +0 -1
  59. package/dist/chunk-zx33ts9d.css +0 -1
@@ -1,2 +1,2 @@
1
1
  var j=Object.create;var{getPrototypeOf:k,defineProperty:f,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,s=(a,b,c)=>{var g=a!=null&&typeof a==="object";if(g){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of l(a))if(!m.call(d,e))f(d,e,{get:n.bind(a,e),enumerable:!0});if(g)h.set(a,d);return d};var t=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var u=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var v=((a)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});
2
- export{s as Kc,t as Lc,u as Mc,v as Nc};
2
+ export{s as Sc,t as Tc,u as Uc,v as Vc};
@@ -0,0 +1,2 @@
1
+ import{Oc as w,Qc as s}from"/chunk-zfz3b4xg.js";import{Sc as q}from"/chunk-zbeq02yc.js";var R=q(w(),1);async function i(o,t){let a=await o.text();return Error(a||t)}async function u(o,t,a="Request failed"){let n=await fetch(o,t);if(!n.ok)throw await i(n,a);return n.json()}async function T(o,t,a="Request failed"){let n=await fetch(o,t);if(!n.ok)throw await i(n,a)}function y(o,t){return{method:o,headers:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t)}}var r={cloudDemo:!1,experiments:[],demoInstallUrl:"https://moi.computer"},d=r,e=new Set;function I(o){return e.add(o),()=>{e.delete(o)}}async function f(){try{d=await u("/api/config");for(let o of e)o()}catch{}}async function c(){await f(),s(()=>{f()})}function h(){return R.useSyncExternalStore(I,()=>d)}
2
+ export{u as Jc,T as Kc,y as Lc,c as Mc,h as Nc};
@@ -0,0 +1,2 @@
1
+ import{Sc as H,Tc as w}from"/chunk-zbeq02yc.js";var t=w((S,b)=>{b.exports=globalThis.__esm.react});var a=H(t(),1);function y(o){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${o}`}var i=new Set,T=new Set,$=!1,p=null,h=!1;function u(){if(p||h)return;h=!0;let o=new WebSocket(y("/api/workspaces/ws"));o.onopen=()=>{if(p=o,h=!1,$)for(let m of T)m();$=!0},o.onmessage=(m)=>{try{let g=JSON.parse(m.data);for(let x of i)x(g)}catch{}},o.onclose=()=>{if(p=null,h=!1,i.size>0)setTimeout(u,2000)},o.onerror=()=>{o.close()}}function B(o){return T.add(o),()=>{T.delete(o)}}function P(o){let m=a.useRef(o);m.current=o,a.useEffect(()=>{let g=(x)=>m.current(x);return i.add(g),u(),()=>{if(i.delete(g),i.size===0&&p)p.close(),p=null}},[])}
2
+ export{t as Oc,y as Pc,B as Qc,P as Rc};
package/dist/index.html CHANGED
@@ -21,7 +21,7 @@
21
21
  }
22
22
  </script>
23
23
 
24
- <link rel="stylesheet" crossorigin href="/chunk-zx33ts9d.css"><script type="module" crossorigin src="/chunk-v964b5g7.js"></script></head>
24
+ <link rel="stylesheet" crossorigin href="/chunk-sapvd7he.css"><script type="module" crossorigin src="/chunk-6wx91x8j.js"></script></head>
25
25
  <body>
26
26
  <div id="root"></div>
27
27
 
package/lib/types.ts CHANGED
@@ -1,5 +1,15 @@
1
1
  import type { PreviewBlock, StreamEvent } from './format'
2
2
 
3
+ // A custom UI unit embedded in a workspace.
4
+ export type AppletKind = 'view' | 'widget'
5
+
6
+ export type AppletInfo = {
7
+ id: string
8
+ // Content revision of the built bundle (`<size>-<mtime>` of index.js).
9
+ // Absent when the build output cannot be statted.
10
+ revision?: string
11
+ }
12
+
3
13
  export type WidgetConfig = {
4
14
  rowSpan: 1 | 2 | 3 | 4
5
15
  colSpan: 1 | 2 | 3 | 4
@@ -9,14 +19,8 @@ export type WidgetConfig = {
9
19
  requiredEnv?: string[]
10
20
  }
11
21
 
12
- export type WidgetInfo = {
13
- id: string
22
+ export type WidgetInfo = AppletInfo & {
14
23
  config: WidgetConfig
15
- // Content tag of the built bundle (`<size>-<mtime>` of its index.js) —
16
- // changes whenever the widget is rebundled. Clients compare it against
17
- // `WidgetThumbnail.tag` to decide which thumbnails are stale. Absent when
18
- // the build output can't be statted.
19
- tag?: string
20
24
  }
21
25
 
22
26
  // A view is a full-screen, agent-authored "app" (`.moi/views/<name>.tsx`),
@@ -31,19 +35,12 @@ export type ViewConfig = {
31
35
  requiredEnv?: string[]
32
36
  }
33
37
 
34
- export type ViewInfo = {
35
- id: string
38
+ export type ViewInfo = AppletInfo & {
36
39
  config: ViewConfig
37
40
  }
38
41
 
39
42
  export type ViewBuilderStatus = 'draft' | 'building' | 'waiting' | 'ready'
40
43
 
41
- // The kind of an applet — a custom UI unit embedded in a workspace. Shared by
42
- // the bundler pipeline and the build-status records. On a builder record the
43
- // field is absent for rows written before it existed; treat a missing kind as
44
- // 'view' (only views surface in the UI — the view builder page is view-only).
45
- export type AppletKind = 'view' | 'widget'
46
-
47
44
  export type ViewBuilderInput = {
48
45
  requirements: string
49
46
  }
@@ -288,6 +285,20 @@ export type AppSettings = {
288
285
  autoUpdateSkills: boolean
289
286
  }
290
287
 
288
+ // Client-safe subset of the startup config (`config.json` in the data dir +
289
+ // `MOI_*` env overrides), served by GET /api/config. Frozen for the process
290
+ // lifetime — changing it requires a server restart, so clients may cache it
291
+ // forever. See server/app-config.ts.
292
+ export type ClientAppConfig = {
293
+ // Cloud demo deployment: workspace creation is blocked; the UI offers the
294
+ // install-moi dialog instead.
295
+ cloudDemo: boolean
296
+ // Enabled experimental features, checked by slug.
297
+ experiments: string[]
298
+ // Link target for the install-moi dialog in the cloud demo.
299
+ demoInstallUrl: string
300
+ }
301
+
291
302
  // Re-export the display format
292
303
  export type {
293
304
  Citation,
@@ -551,32 +562,40 @@ export type WorkspaceLayout = {
551
562
  // Fast-mode default for new sessions. Undefined inherits the provider setting.
552
563
  selectedFastMode?: boolean
553
564
  theme?: import('./themes').WorkspaceTheme
554
- // Widget thumbnails captured client-side from the live grid, used for
555
- // home-screen previews. Saved through their own endpoint (PUT
556
- // .../thumbnails), never through the layout PUT.
557
- widgetThumbnails?: WidgetThumbnails
558
- }
559
-
560
- export type WidgetThumbnails = {
561
- // Fingerprint of the grid state the set was captured from (visible widget
562
- // ids + their bundle tags — see widgetThumbnailsKey()). A mismatch with the
563
- // live grid re-captures the whole set.
564
- key?: string
565
- // Server-stamped ISO time of the last save. Widget DATA drifts even when
566
- // bundles don't (a dashboard captured in January still shows January), so
567
- // an old-enough set re-captures despite a matching key.
568
- at?: string
569
- // Widget id → WebP data URL (white background, the widget's own aspect
570
- // ratio). Entries merge, never prune: a removed widget keeps its last image
571
- // in case it comes back. Heavy — the layout GET strips this field; images
572
- // reach the home screen via the preview endpoint.
573
- images?: Record<string, string>
574
- }
575
-
576
- // Home-screen workspace card preview: a few captured widget thumbnails (WebP
577
- // data URLs) from the stored layout, rendered as a loose stack, plus the latest
578
- // provider session activity. A workspace with no widgets may instead carry its
579
- // oldest session's first user message.
565
+ }
566
+
567
+ // One applet's thumbnail freshness record. Image bytes live as files in the
568
+ // workspace's `.moi/.cache/thumbnails/` (server/thumbnails.ts), never in
569
+ // `.workspace.json` — the layout file stays small and commit-safe.
570
+ export type AppletThumbnail = {
571
+ kind: AppletKind
572
+ id: string
573
+ revision: string
574
+ capturedAt: string
575
+ viewedAt: string
576
+ // How long the last successful capture took on this client, in ms. Lets the
577
+ // capture hook skip routine re-captures of applets that are slow to
578
+ // screenshot (see SLOW_CAPTURE_MS) instead of janking the main thread.
579
+ captureMs?: number
580
+ }
581
+
582
+ export type AppletThumbnailUpdate = {
583
+ id: string
584
+ revision: string
585
+ // A string replaces the stored image, null records a failed or skipped
586
+ // attempt (the previous image survives), undefined only touches recency.
587
+ image?: string | null
588
+ captureMs?: number
589
+ }
590
+
591
+ export type AppletThumbnailBatch = {
592
+ kind: AppletKind
593
+ thumbnails: AppletThumbnailUpdate[]
594
+ }
595
+
596
+ // Home-screen workspace card preview: widgets in grid order, then recent views,
597
+ // capped to the loose stack's visible depth. A workspace with no captured
598
+ // applets may instead carry its oldest session's first message.
580
599
  export type WorkspacePreview = {
581
600
  thumbnails: string[]
582
601
  firstUserMessage?: string
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.9.1-next.0",
3
+ "version": "0.9.1-next.1",
4
4
  "description": "Local AI workspace powered by the Claude Agent SDK, Bun, React, and Tailwind. Requires Bun.",
5
5
  "license": "Elastic-2.0",
6
6
  "type": "module",
package/server/api.ts CHANGED
@@ -6,6 +6,7 @@ import { basename, join, resolve } from 'node:path'
6
6
 
7
7
  import type {
8
8
  AppletKind,
9
+ AppletThumbnailBatch,
9
10
  AppSettings,
10
11
  HarnessAvailability,
11
12
  SessionInfo,
@@ -19,6 +20,7 @@ import type { MoiContext } from '@/lib/moi-context'
19
20
  import { viewBuilderDirectives } from '@/lib/view-builder-directives'
20
21
 
21
22
  import { agentStore } from './agent'
23
+ import { clientAppConfig, getAppConfig } from './app-config'
22
24
  import { getAppSettings, pickAppSettingsPatch, saveAppSettings } from './app-settings'
23
25
  import { appletForModule, recordAppletError } from './applet-log'
24
26
  import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
@@ -26,13 +28,13 @@ import { applyEnvChanged } from './env-apply'
26
28
  import { publishEvent } from './events'
27
29
  import { callFunction, parseFunctionPath } from './functions'
28
30
  import { processIcon } from './icon'
31
+ import { getWorkspacePreview, loadLayout, mergeLayoutForSave, saveLayout } from './layout'
29
32
  import {
30
- getWorkspacePreview,
31
- loadLayout,
32
- mergeLayoutForSave,
33
- saveLayout,
34
- saveWidgetThumbnails
35
- } from './layout'
33
+ getAppletThumbnailRecords,
34
+ isValidAppletId,
35
+ saveAppletThumbnails,
36
+ serveAppletThumbnail
37
+ } from './thumbnails'
36
38
  import { getClientFrameLog, getWireLog } from './harness/debug'
37
39
  import { allHarnesses, harnessFor, isHarnessType } from './harness/registry'
38
40
  import { broadcast } from './state'
@@ -150,10 +152,16 @@ one.use('*', withWorkspace)
150
152
 
151
153
  one.get('/preview', async c => {
152
154
  const ws = c.get('ws')
155
+ const wsId = c.req.param('id')
156
+ const views = await getViewList(ws.path)
153
157
  return c.json(
154
- await getWorkspacePreview(ws.path, includeFirstUserMessage =>
155
- harnessFor(ws).workspacePreview(ws, includeFirstUserMessage)
156
- )
158
+ await getWorkspacePreview(ws.path, {
159
+ getProviderPreview: includeFirstUserMessage =>
160
+ harnessFor(ws).workspacePreview(ws, includeFirstUserMessage),
161
+ viewIds: views.map(view => view.id),
162
+ thumbnailUrl: (kind, id) =>
163
+ `/api/workspaces/${wsId}/applet-thumbnails/${kind}/${encodeURIComponent(id)}`
164
+ })
157
165
  )
158
166
  })
159
167
 
@@ -827,16 +835,9 @@ one.delete('/icon', async c => {
827
835
  // DELETE unregisters.
828
836
  one.get('/', async c => {
829
837
  const ws = c.get('ws')
830
- // The thumbnail images are heavy (base64 WebPs) and have their own write
831
- // path (PUT .../thumbnails); the layout ships `widgetThumbnails` without
832
- // them — just `key`/`at`, which clients compare against the live grid to
833
- // decide when to re-capture.
834
- const { widgetThumbnails, ...layout } = await loadLayout(ws.path)
838
+ const layout = await loadLayout(ws.path)
835
839
  return c.json({
836
840
  ...layout,
837
- ...(widgetThumbnails && {
838
- widgetThumbnails: { key: widgetThumbnails.key, at: widgetThumbnails.at }
839
- }),
840
841
  // Resolved display name: the settings override, or the folder name.
841
842
  name: layout.name || basename(ws.path),
842
843
  cwd: ws.path,
@@ -845,21 +846,46 @@ one.get('/', async c => {
845
846
  })
846
847
  })
847
848
 
848
- // Widget thumbnails: a separate write path from the layout PUT below, so grid
849
- // and theme saves never round-trip the base64 map (and this save can't touch
850
- // the grid). Still lands in `.workspace.json` under the hood. Entries merge
851
- // over the stored map; `key` fingerprints the grid state they were captured
852
- // from (see widgetThumbnailsKey() on the client).
853
- one.put('/thumbnails', async c => {
849
+ // Thumbnail freshness records, without image bytes — the capture hook compares
850
+ // these against live bundle revisions. Images are served per-applet below.
851
+ one.get('/applet-thumbnails', async c =>
852
+ c.json({ thumbnails: await getAppletThumbnailRecords(c.get('ws').path) })
853
+ )
854
+
855
+ one.get('/applet-thumbnails/:kind/:name', c => {
856
+ const kind = c.req.param('kind')
857
+ if (kind !== 'widget' && kind !== 'view') return c.text('Not found', 404)
858
+ return serveAppletThumbnail(
859
+ c.get('ws').path,
860
+ kind,
861
+ c.req.param('name'),
862
+ c.req.header('if-none-match')
863
+ )
864
+ })
865
+
866
+ // Settled widget and view visits share one batch endpoint and storage path.
867
+ one.put('/applet-thumbnails', async c => {
854
868
  const body: unknown = await c.req.json().catch(() => null)
855
- if (!body || typeof body !== 'object') return c.text('Bad request', 400)
856
- const { key, thumbnails } = body as { key?: unknown; thumbnails?: unknown }
857
- const validMap =
858
- thumbnails !== null &&
859
- typeof thumbnails === 'object' &&
860
- Object.values(thumbnails as Record<string, unknown>).every(v => typeof v === 'string')
861
- if (typeof key !== 'string' || !validMap) return c.text('Bad request', 400)
862
- await saveWidgetThumbnails(c.get('ws').path, key, thumbnails as Record<string, string>)
869
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return c.text('Bad request', 400)
870
+ const input = body as AppletThumbnailBatch
871
+ const valid =
872
+ (input.kind === 'widget' || input.kind === 'view') &&
873
+ Array.isArray(input.thumbnails) &&
874
+ input.thumbnails.every(
875
+ thumbnail =>
876
+ thumbnail &&
877
+ typeof thumbnail === 'object' &&
878
+ !Array.isArray(thumbnail) &&
879
+ typeof thumbnail.id === 'string' &&
880
+ isValidAppletId(thumbnail.id) &&
881
+ typeof thumbnail.revision === 'string' &&
882
+ (thumbnail.image === undefined ||
883
+ thumbnail.image === null ||
884
+ typeof thumbnail.image === 'string') &&
885
+ (thumbnail.captureMs === undefined || typeof thumbnail.captureMs === 'number')
886
+ )
887
+ if (!valid) return c.text('Bad request', 400)
888
+ await saveAppletThumbnails(c.get('ws').path, input.kind, input.thumbnails)
863
889
  return c.body(null, 204)
864
890
  })
865
891
 
@@ -917,7 +943,14 @@ workspaces.put('/order', async c => {
917
943
  }
918
944
  })
919
945
 
946
+ // One message for both creation routes: in the cloud demo the instance is
947
+ // provisioned with its workspaces; the UI never sends these requests (it opens
948
+ // the install-moi dialog instead), so a 403 here means the API was called
949
+ // directly.
950
+ const DEMO_CREATE_BLOCKED = 'Workspace creation is not available in the moi demo'
951
+
920
952
  workspaces.post('/', async c => {
953
+ if (getAppConfig().cloudDemo) return c.text(DEMO_CREATE_BLOCKED, 403)
921
954
  const body = await c.req.json()
922
955
  if (!body?.path) return c.text('Missing path', 400)
923
956
  const requestedType: unknown = body?.type ?? 'claude-code'
@@ -983,6 +1016,7 @@ workspaces.get('/create', async c =>
983
1016
  // Create a brand-new workspace: a fresh folder under CREATED_WORKSPACES_ROOT,
984
1017
  // provisioned (skills + `.moi/` scaffold) and registered.
985
1018
  workspaces.post('/create', async c => {
1019
+ if (getAppConfig().cloudDemo) return c.text(DEMO_CREATE_BLOCKED, 403)
986
1020
  const body = await c.req.json()
987
1021
  const requestedType: unknown = body?.type ?? 'claude-code'
988
1022
  if (!isHarnessType(requestedType)) {
@@ -1021,6 +1055,10 @@ export const api = new Hono()
1021
1055
 
1022
1056
  api.route('/api/workspaces', workspaces)
1023
1057
 
1058
+ // Startup config (config.json in the data dir + MOI_* env), client-safe
1059
+ // subset. Immutable for the process lifetime — clients cache it forever.
1060
+ api.get('/api/config', c => c.json(clientAppConfig()))
1061
+
1024
1062
  // App-wide settings (settings.json in the data dir). GET returns every key
1025
1063
  // with defaults applied; PATCH merges a partial body and returns the result.
1026
1064
  api.get('/api/settings', c => c.json(getAppSettings()))
@@ -0,0 +1,144 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'path'
3
+
4
+ import type { ClientAppConfig } from '@/lib/types'
5
+
6
+ import { DATA_DIR } from './data-dir'
7
+
8
+ // Startup (deployment) config, read once per process from `config.json` in
9
+ // moi's data dir and overridable by `MOI_*` env vars (env wins). Distinct from
10
+ // `settings.json` (user settings: conf-backed, API-mutable, changes at
11
+ // runtime): config.json describes the deployment itself — nothing here changes
12
+ // without a server restart, and no API writes it.
13
+ //
14
+ // Resolution: defaults < config.json < env. A missing file is the normal local
15
+ // case; a malformed file or wrong-typed key warns on stderr and falls back
16
+ // per-key, so a broken config never takes the CLI or server down with it.
17
+ export type AppConfig = {
18
+ // Cloud demo deployment: workspace creation is blocked (UI shows the
19
+ // install-moi dialog instead) and `moi` system commands are disabled.
20
+ cloudDemo: boolean
21
+ // Gated experimental features, checked by slug.
22
+ experiments: string[]
23
+ // Link target for the install-moi dialog in the cloud demo.
24
+ demoInstallUrl: string
25
+ }
26
+
27
+ const DEFAULTS: AppConfig = {
28
+ cloudDemo: false,
29
+ experiments: [],
30
+ demoInstallUrl: 'https://moi.computer'
31
+ }
32
+
33
+ export const APP_CONFIG_FILE = join(DATA_DIR, 'config.json')
34
+
35
+ function warn(message: string): void {
36
+ console.error(`[moi] config: ${message}`)
37
+ }
38
+
39
+ // '1'/'true' (case-insensitive) are true, '0'/'false' are false, anything
40
+ // else — including empty — leaves the lower-precedence value in place.
41
+ function parseBool(raw: string | undefined): boolean | undefined {
42
+ if (raw === undefined) return undefined
43
+ const value = raw.trim().toLowerCase()
44
+ if (value === '1' || value === 'true') return true
45
+ if (value === '0' || value === 'false') return false
46
+ return undefined
47
+ }
48
+
49
+ // "a, b,c" → ['a','b','c']; empty entries dropped. An empty string clears the
50
+ // list (explicitly setting MOI_EXPERIMENTS= disables file-set experiments).
51
+ function parseList(raw: string | undefined): string[] | undefined {
52
+ if (raw === undefined) return undefined
53
+ return raw
54
+ .split(',')
55
+ .map(item => item.trim())
56
+ .filter(Boolean)
57
+ }
58
+
59
+ function parseString(raw: string | undefined): string | undefined {
60
+ if (raw === undefined || raw.trim() === '') return undefined
61
+ return raw.trim()
62
+ }
63
+
64
+ function fileValues(file: string): Partial<AppConfig> {
65
+ let text: string
66
+ try {
67
+ text = readFileSync(file, 'utf8')
68
+ } catch (err) {
69
+ // Only a missing file is silent (the normal local case). Anything else —
70
+ // permissions, mount errors — is loud: a deployment relying on config.json
71
+ // must not boot un-gated without a diagnostic. Deployments that need the
72
+ // demo gate guaranteed should pin MOI_CLOUD_DEMO=1 in the environment,
73
+ // which has no read-failure mode.
74
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
75
+ warn(`could not read ${file}: ${err instanceof Error ? err.message : String(err)}`)
76
+ }
77
+ return {}
78
+ }
79
+ let parsed: unknown
80
+ try {
81
+ parsed = JSON.parse(text)
82
+ } catch (err) {
83
+ warn(`ignoring ${file} — invalid JSON: ${err instanceof Error ? err.message : String(err)}`)
84
+ return {}
85
+ }
86
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
87
+ warn(`ignoring ${file} — expected a JSON object`)
88
+ return {}
89
+ }
90
+ const raw = parsed as Record<string, unknown>
91
+ const out: Partial<AppConfig> = {}
92
+ if (raw.cloudDemo !== undefined) {
93
+ if (typeof raw.cloudDemo === 'boolean') out.cloudDemo = raw.cloudDemo
94
+ else warn('ignoring "cloudDemo" — expected a boolean')
95
+ }
96
+ if (raw.experiments !== undefined) {
97
+ if (Array.isArray(raw.experiments) && raw.experiments.every(item => typeof item === 'string')) {
98
+ out.experiments = raw.experiments
99
+ } else warn('ignoring "experiments" — expected an array of strings')
100
+ }
101
+ if (raw.demoInstallUrl !== undefined) {
102
+ if (typeof raw.demoInstallUrl === 'string') out.demoInstallUrl = raw.demoInstallUrl
103
+ else warn('ignoring "demoInstallUrl" — expected a string')
104
+ }
105
+ return out
106
+ }
107
+
108
+ // Pure resolver, exported for tests. `getAppConfig` is the cached entrypoint.
109
+ export function loadAppConfig(
110
+ file: string = APP_CONFIG_FILE,
111
+ env: Record<string, string | undefined> = process.env
112
+ ): AppConfig {
113
+ const fromFile = fileValues(file)
114
+ const fromEnv: Partial<AppConfig> = {
115
+ cloudDemo: parseBool(env.MOI_CLOUD_DEMO),
116
+ experiments: parseList(env.MOI_EXPERIMENTS),
117
+ demoInstallUrl: parseString(env.MOI_DEMO_INSTALL_URL)
118
+ }
119
+ const merged = { ...DEFAULTS, ...fromFile }
120
+ for (const key of Object.keys(fromEnv) as (keyof AppConfig)[]) {
121
+ if (fromEnv[key] === undefined) delete fromEnv[key]
122
+ }
123
+ return Object.freeze({ ...merged, ...fromEnv })
124
+ }
125
+
126
+ let _config: AppConfig | null = null
127
+
128
+ export function getAppConfig(): AppConfig {
129
+ _config ??= loadAppConfig()
130
+ return _config
131
+ }
132
+
133
+ // Test seam: drop the cached config so the next getAppConfig() re-resolves
134
+ // (tests point MOI_DATA_DIR elsewhere or set MOI_CLOUD_DEMO).
135
+ export function resetAppConfig(): void {
136
+ _config = null
137
+ }
138
+
139
+ // The only shape that reaches the browser (GET /api/config). Server-only keys
140
+ // added to AppConfig later stay out unless explicitly forwarded here.
141
+ export function clientAppConfig(): ClientAppConfig {
142
+ const { cloudDemo, experiments, demoInstallUrl } = getAppConfig()
143
+ return { cloudDemo, experiments: [...experiments], demoInstallUrl }
144
+ }
package/server/applets.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  buildApplet,
24
24
  scanRelativeImports
25
25
  } from './bundler/build-applet'
26
+ import { pruneAppletThumbnails } from './thumbnails'
26
27
 
27
28
  export type AppletPaths = {
28
29
  moiRoot: string
@@ -40,6 +41,20 @@ export function getAppletPaths(workspacePath: string, kind: AppletKind): AppletP
40
41
  return { moiRoot, sourceDir, buildDir, manifestPath }
41
42
  }
42
43
 
44
+ export function getAppletRevision(
45
+ workspacePath: string,
46
+ kind: AppletKind,
47
+ id: string
48
+ ): string | undefined {
49
+ try {
50
+ const { buildDir } = getAppletPaths(workspacePath, kind)
51
+ const stat = statSync(join(buildDir, id, 'index.js'))
52
+ return `${stat.size}-${Math.trunc(stat.mtimeMs)}`
53
+ } catch {
54
+ return undefined
55
+ }
56
+ }
57
+
43
58
  // Source module names in a kind's directory: `*.tsx`/`*.ts` minus `.server.ts`
44
59
  // and minus `_`-prefixed files (`_utils.tsx`) — those are shared modules for
45
60
  // entries to import, never entry points themselves.
@@ -580,6 +595,8 @@ export async function buildApplets<C>(
580
595
  await mkdir(buildDir, { recursive: true })
581
596
  }
582
597
  await pruneStaleBuilds(buildDir, new Set(names))
598
+ // A deleted applet's thumbnail dies with its bundle.
599
+ await pruneAppletThumbnails(workspacePath, kind, names)
583
600
 
584
601
  const jobs = await Promise.all(
585
602
  names.map(async name => {
package/server/cli.ts CHANGED
@@ -5,10 +5,11 @@ import { formatHex } from 'culori'
5
5
  import { parse as devalueParse } from 'devalue'
6
6
  import { existsSync } from 'node:fs'
7
7
  import { tmpdir } from 'node:os'
8
- import { join, resolve } from 'path'
8
+ import { dirname, join, resolve } from 'path'
9
9
  import pc from './cli-pc'
10
10
 
11
11
  import { isAgentCaller } from './agent-caller'
12
+ import { getAppConfig } from './app-config'
12
13
 
13
14
  import {
14
15
  COLOR_THEMES,
@@ -61,6 +62,7 @@ import { updateWorkspaceSkills } from './skill-update'
61
62
  import {
62
63
  ServiceError,
63
64
  analyzeInstall,
65
+ captureServiceEnv,
64
66
  installService,
65
67
  queryServerInfo,
66
68
  restartService,
@@ -2393,6 +2395,25 @@ const serviceInstall = defineCommand({
2393
2395
  serviceFail(err)
2394
2396
  }
2395
2397
  }
2398
+ const port = args.port ? Number(args.port) : undefined
2399
+ if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) {
2400
+ serviceFail(new ServiceError(`Invalid --port value "${args.port}" — use a port number.`))
2401
+ }
2402
+ // citty hands back an array when the flag repeats — accept both shapes.
2403
+ const envArg = Array.isArray(args.env) ? args.env.join(',') : args.env
2404
+ const extraEnv = (envArg ?? '')
2405
+ .split(',')
2406
+ .map(k => k.trim())
2407
+ .filter(Boolean)
2408
+ const serviceEnv = captureServiceEnv(process.env, dirname(process.execPath), extraEnv)
2409
+ const missingEnv = extraEnv.filter(key => !(key in serviceEnv))
2410
+ if (missingEnv.length > 0) {
2411
+ serviceFail(
2412
+ new ServiceError(
2413
+ `--env ${missingEnv.join(', ')}: not set in this shell (or the value is not capturable).`
2414
+ )
2415
+ )
2416
+ }
2396
2417
  // A foreground `moi start` holds the same ports the service needs. Refuse
2397
2418
  // rather than install a unit that instantly fails on bind.
2398
2419
  const runningInfo = await queryServerInfo()
@@ -2406,16 +2427,6 @@ const serviceInstall = defineCommand({
2406
2427
  )
2407
2428
  )
2408
2429
  }
2409
- const port = args.port ? Number(args.port) : undefined
2410
- if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) {
2411
- serviceFail(new ServiceError(`Invalid --port value "${args.port}" — use a port number.`))
2412
- }
2413
- // citty hands back an array when the flag repeats — accept both shapes.
2414
- const envArg = Array.isArray(args.env) ? args.env.join(',') : args.env
2415
- const extraEnv = (envArg ?? '')
2416
- .split(',')
2417
- .map(k => k.trim())
2418
- .filter(Boolean)
2419
2430
  try {
2420
2431
  const result = await installService({ port, extraEnv })
2421
2432
  console.log(
@@ -2840,6 +2851,31 @@ const main = defineCommand({
2840
2851
  subCommands: { ...workspaceCommands, ...systemCommands }
2841
2852
  })
2842
2853
 
2854
+ // Cloud demo: system commands manage moi itself (service, updates, agent
2855
+ // runtimes) — in a demo container the instance is provisioned, not managed,
2856
+ // so they print a pointer to the real thing instead of running. Two stay:
2857
+ // `start`, because it is how the demo (container or a local test run) boots
2858
+ // at all — against an already-running server it just reports and exits — and
2859
+ // `version`, which is harmless and useful in bug reports.
2860
+ function exitIfDemoBlocked(): void {
2861
+ const invoked = process.argv[2]
2862
+ if (!invoked || invoked === 'version' || invoked === 'start') return
2863
+ if (!(invoked in systemCommands)) return
2864
+ const config = getAppConfig()
2865
+ if (!config.cloudDemo) return
2866
+ console.log(
2867
+ '\n' +
2868
+ pc.yellow('◆') +
2869
+ ` moi ${invoked} is not available in the demo.\n` +
2870
+ pc.dim(' Get moi on your computer: ') +
2871
+ pc.bold(config.demoInstallUrl) +
2872
+ '\n'
2873
+ )
2874
+ process.exit(1)
2875
+ }
2876
+
2877
+ exitIfDemoBlocked()
2878
+
2843
2879
  type HelpCommand = { meta?: unknown }
2844
2880
 
2845
2881
  async function commandDescription(cmd: HelpCommand): Promise<string> {