moi-computer 0.9.1-next.5 → 0.10.1-next.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 (35) hide show
  1. package/README.md +124 -58
  2. package/client/app/shell/SidebarLayout.tsx +111 -79
  3. package/client/features/chat/ChatEmptyState.tsx +70 -34
  4. package/client/features/chat/ChatPanel.tsx +8 -1
  5. package/client/features/chat/chat-store.ts +4 -0
  6. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +22 -5
  7. package/client/features/update/Update.tsx +78 -0
  8. package/client/features/update/api.ts +35 -0
  9. package/client/features/workspace/WorkspaceScreen.tsx +15 -0
  10. package/dist/{chunk-yt2qjn3m.js → chunk-0set7tmf.js} +2 -2
  11. package/dist/chunk-4057kxht.css +1 -0
  12. package/dist/{chunk-te5sfhvx.js → chunk-5t06zksf.js} +2 -2
  13. package/dist/{chunk-9y2zbzqz.js → chunk-97eg9mjn.js} +1 -1
  14. package/dist/chunk-b5c62p8h.js +1 -0
  15. package/dist/chunk-dfe7qnrp.js +1 -0
  16. package/dist/{chunk-0pcdwjkp.js → chunk-efdyz6xp.js} +1 -1
  17. package/dist/chunk-f6xmz3tn.js +83 -0
  18. package/dist/chunk-h2kj1ysj.js +1 -0
  19. package/dist/{chunk-yhj9bg1s.js → chunk-ht1f95h9.js} +2 -2
  20. package/dist/chunk-qtc5a8qa.js +10 -0
  21. package/dist/index.html +1 -1
  22. package/lib/types.ts +9 -0
  23. package/lib/update.ts +2 -0
  24. package/package.json +1 -1
  25. package/server/api.ts +46 -0
  26. package/server/cli.ts +7 -6
  27. package/server/constants.ts +4 -2
  28. package/server/update.ts +293 -5
  29. package/server/web.ts +1 -1
  30. package/dist/chunk-4xmcsjjv.js +0 -1
  31. package/dist/chunk-9m59hf8p.js +0 -10
  32. package/dist/chunk-dfs36zgc.js +0 -1
  33. package/dist/chunk-hffvjnmj.js +0 -85
  34. package/dist/chunk-pq93pv5z.js +0 -1
  35. package/dist/chunk-xtr8kvqx.css +0 -1
package/dist/index.html CHANGED
@@ -21,7 +21,7 @@
21
21
  }
22
22
  </script>
23
23
 
24
- <link rel="stylesheet" crossorigin href="/chunk-xtr8kvqx.css"><script type="module" crossorigin src="/chunk-pq93pv5z.js"></script></head>
24
+ <link rel="stylesheet" crossorigin href="/chunk-4057kxht.css"><script type="module" crossorigin src="/chunk-b5c62p8h.js"></script></head>
25
25
  <body>
26
26
  <div id="root"></div>
27
27
 
package/lib/types.ts CHANGED
@@ -299,6 +299,15 @@ export type ClientAppConfig = {
299
299
  demoInstallUrl: string
300
300
  }
301
301
 
302
+ export type UpdateStatus = {
303
+ runningVersion: string
304
+ availableVersion: string | null
305
+ }
306
+
307
+ export type UpdateResult = {
308
+ installedVersion: string
309
+ }
310
+
302
311
  // Re-export the display format
303
312
  export type {
304
313
  Citation,
package/lib/update.ts ADDED
@@ -0,0 +1,2 @@
1
+ export const UPDATE_ACTIVE_AGENT_MESSAGE =
2
+ 'Wait for active agents to finish, or stop them before updating moi'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.9.1-next.5",
3
+ "version": "0.10.1-next.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",
package/server/api.ts CHANGED
@@ -4,6 +4,7 @@ import { createMiddleware } from 'hono/factory'
4
4
  import { existsSync } from 'node:fs'
5
5
  import { basename, join, resolve } from 'node:path'
6
6
 
7
+ import { UPDATE_ACTIVE_AGENT_MESSAGE } from '@/lib/update'
7
8
  import type {
8
9
  AppletKind,
9
10
  AppletThumbnailBatch,
@@ -84,6 +85,14 @@ import { resolveWorkspaceImportMetadata } from './workspace-import'
84
85
  import type { WorkspaceImportMetadata } from './workspace-import'
85
86
  import { getWorkspaceEnvView, isValidEnvKey, updateWorkspaceEnv } from './workspace-env'
86
87
  import type { EnvUpdate } from './workspace-env'
88
+ import {
89
+ getCachedUpdateStatus,
90
+ hasRunningAgentSessions,
91
+ installUpdate,
92
+ restartPendingForUpdate,
93
+ scheduleRestartForUpdate,
94
+ updateInProgress
95
+ } from './update'
87
96
 
88
97
  // The resolved workspace is stashed on the context by `withWorkspace`, so every
89
98
  // `/api/workspaces/:id/*` handler can read it without re-querying the registry.
@@ -1059,6 +1068,43 @@ api.route('/api/workspaces', workspaces)
1059
1068
  // subset. Immutable for the process lifetime — clients cache it forever.
1060
1069
  api.get('/api/config', c => c.json(clientAppConfig()))
1061
1070
 
1071
+ // Served from a lazily-refreshed cache: this handler is a memory read, and the
1072
+ // registry is consulted on the schedule `getCachedUpdateStatus` owns rather
1073
+ // than once per request. `no-store` keeps the browser from adding a second,
1074
+ // unrelated cache on top of it.
1075
+ api.get('/api/update', async c => {
1076
+ c.header('Cache-Control', 'no-store')
1077
+ return c.json(await getCachedUpdateStatus())
1078
+ })
1079
+
1080
+ api.post('/api/update', async c => {
1081
+ if (updateInProgress()) {
1082
+ return c.text(
1083
+ restartPendingForUpdate()
1084
+ ? 'An update is installed — moi is restarting.'
1085
+ : 'An update is already in progress.',
1086
+ 409
1087
+ )
1088
+ }
1089
+
1090
+ const agentRunning = hasRunningAgentSessions(
1091
+ allHarnesses().flatMap(harness => harness.activeSessions())
1092
+ )
1093
+ if (agentRunning) {
1094
+ return c.text(UPDATE_ACTIVE_AGENT_MESSAGE, 409)
1095
+ }
1096
+
1097
+ try {
1098
+ const result = await installUpdate()
1099
+ if (!result) return c.text('This moi install cannot be updated from the app.', 409)
1100
+ const response = c.json(result)
1101
+ scheduleRestartForUpdate()
1102
+ return response
1103
+ } catch (error) {
1104
+ return c.text(error instanceof Error ? error.message : 'Could not update moi.', 500)
1105
+ }
1106
+ })
1107
+
1062
1108
  // App-wide settings (settings.json in the data dir). GET returns every key
1063
1109
  // with defaults applied; PATCH merges a partial body and returns the result.
1064
1110
  api.get('/api/settings', c => c.json(getAppSettings()))
package/server/cli.ts CHANGED
@@ -91,6 +91,7 @@ import {
91
91
  isNewer,
92
92
  manualUpdateLines,
93
93
  runPackageManager,
94
+ superviseServerUpdates,
94
95
  updateArgv
95
96
  } from './update'
96
97
  import { VERSION, isPrerelease, versionWithCommit } from './version'
@@ -430,7 +431,8 @@ const init = defineCommand({
430
431
 
431
432
  if (!running && args.web) {
432
433
  console.log(pc.dim(' Starting server…'))
433
- const proc = spawnServer(serverCwd(projectRoot, false))
434
+ const cwd = serverCwd(projectRoot, false)
435
+ const proc = spawnServer(cwd)
434
436
  running = await waitForServer()
435
437
  if (!running) {
436
438
  console.error(pc.red(' Server failed to start\n'))
@@ -442,8 +444,7 @@ const init = defineCommand({
442
444
  if (isInteractive) console.log(' Opening ' + pc.bold(url))
443
445
  console.log(pc.dim(' Press Ctrl+C to stop\n'))
444
446
  if (isInteractive) await openBrowser(url)
445
- await proc.exited
446
- process.exit(proc.exitCode ?? 0)
447
+ process.exit(await superviseServerUpdates(proc, () => spawnServer(cwd)))
447
448
  }
448
449
 
449
450
  if (running) {
@@ -528,9 +529,9 @@ const start = defineCommand({
528
529
  await runDevSupervisor(projectRoot, env)
529
530
  return
530
531
  }
531
- const proc = spawnServer(serverCwd(projectRoot, dev), env)
532
- await proc.exited
533
- process.exit(proc.exitCode ?? 0)
532
+ const cwd = serverCwd(projectRoot, dev)
533
+ const proc = spawnServer(cwd, env)
534
+ process.exit(await superviseServerUpdates(proc, () => spawnServer(cwd, env)))
534
535
  }
535
536
 
536
537
  // This IS the server process (MOI_SERVER=1). cwd is the package root when the
@@ -1,6 +1,8 @@
1
1
  export const PORT = Number(process.env.PORT) || 13337
2
- // M=13, E=5, I=9 -> 13059
3
- export const CONTROL_PORT = 13059
2
+ // M=13, E=5, I=9 -> 13059. Overridable like PORT so a test can bring up a
3
+ // throwaway server beside a real one; server and CLI read this same module, so
4
+ // a process given the override binds and dials the same port either way.
5
+ export const CONTROL_PORT = Number(process.env.MOI_CONTROL_PORT) || 13059
4
6
  // The address the control server binds AND the one every client dials — never
5
7
  // the name `localhost`. Resolution of that name is not guaranteed: container
6
8
  // images ship an /etc/hosts without a `localhost` entry (Bun's resolver, unlike
package/server/update.ts CHANGED
@@ -1,12 +1,17 @@
1
- // `moi update` mechanics: check the npm registry for the latest published
2
- // version, find the package manager that owns the current global install, and
3
- // update through it — never around it, so no second shadowing install appears.
4
- // Manual command only; nothing here runs in the background.
1
+ // Shared `moi update` mechanics for the CLI and the local web UI: check the npm
2
+ // registry, find the package manager that owns the current global install, and
3
+ // update through it so no second shadowing install appears. Checks may run in
4
+ // the background; installing always requires an explicit user action.
5
5
  import { realpathSync } from 'node:fs'
6
6
 
7
- import { PACKAGE_ROOT } from './version'
7
+ import type { SessionActivity, UpdateResult, UpdateStatus } from '@/lib/types'
8
+
9
+ import { analyzeInstall } from './service'
10
+ import type { InstallAnalysis } from './service'
11
+ import { PACKAGE_ROOT, VERSION, isPrerelease } from './version'
8
12
 
9
13
  export const PACKAGE_NAME = 'moi-computer'
14
+ export const UPDATE_RESTART_EXIT_CODE = 75
10
15
 
11
16
  // Test seam: point at a local mock registry (`MOI_NPM_REGISTRY`).
12
17
  function registryBase(): string {
@@ -139,3 +144,286 @@ export async function installedBinVersion(bin: string): Promise<string | null> {
139
144
  return null
140
145
  }
141
146
  }
147
+
148
+ type ServerProcess = {
149
+ exited: Promise<number>
150
+ }
151
+
152
+ // A service manager already respawns failed exits. Foreground launchers use
153
+ // the same exit code to replace their server child with the updated install.
154
+ export async function superviseServerUpdates(
155
+ child: ServerProcess,
156
+ respawn: () => ServerProcess
157
+ ): Promise<number> {
158
+ let exitCode = await child.exited
159
+ while (exitCode === UPDATE_RESTART_EXIT_CODE) {
160
+ child = respawn()
161
+ exitCode = await child.exited
162
+ }
163
+ return exitCode
164
+ }
165
+
166
+ type UpdateOptions = {
167
+ runningVersion?: string
168
+ analysis?: InstallAnalysis
169
+ fetchLatest?: () => Promise<string>
170
+ detectManager?: () => Promise<PackageManager | null>
171
+ runManager?: (argv: string[]) => Promise<number>
172
+ readInstalledVersion?: (bin: string) => Promise<string | null>
173
+ }
174
+
175
+ // Both of these describe where this process was installed from, which cannot
176
+ // change while it runs — and `detectPackageManager` may spawn `npm root -g`, a
177
+ // whole Node process. Probe each once and reuse the answer for every later
178
+ // check; the promise (not the value) is memoized so concurrent callers share
179
+ // the one probe. `null` is a real answer here — an install nobody owns stays
180
+ // unowned — so it is cached like any other.
181
+ let installAnalysis: InstallAnalysis | null = null
182
+ let managerProbe: Promise<PackageManager | null> | null = null
183
+
184
+ export function ownInstall(): InstallAnalysis {
185
+ return (installAnalysis ??= analyzeInstall())
186
+ }
187
+
188
+ export function owningManager(): Promise<PackageManager | null> {
189
+ return (managerProbe ??= detectPackageManager())
190
+ }
191
+
192
+ type AvailableUpdate = {
193
+ version: string
194
+ packageManager: PackageManager
195
+ bin: string
196
+ }
197
+
198
+ export function hasRunningAgentSessions(sessions: { activity: SessionActivity }[]): boolean {
199
+ return sessions.some(session => session.activity === 'running')
200
+ }
201
+
202
+ async function findAvailableUpdate(options: UpdateOptions): Promise<AvailableUpdate | null> {
203
+ const runningVersion = options.runningVersion ?? VERSION
204
+ const analysis = options.analysis ?? ownInstall()
205
+ if (analysis.kind !== 'global' || isPrerelease(runningVersion)) return null
206
+ const version = await (options.fetchLatest ?? fetchLatestVersion)()
207
+ if (!isNewer(version, runningVersion)) return null
208
+ const packageManager = await (options.detectManager ?? owningManager)()
209
+ return packageManager ? { version, packageManager, bin: analysis.bin } : null
210
+ }
211
+
212
+ // Background checks stay quiet: every failure reads to the UI as "nothing to
213
+ // install". The cache still needs to tell the two apart — an unreachable
214
+ // registry should be retried in minutes, a successful "you are current" in
215
+ // hours — so the outcome carries `ok` alongside the status the UI sees.
216
+ type CheckOutcome = { ok: boolean; status: UpdateStatus }
217
+
218
+ async function checkForUpdate(options: UpdateOptions): Promise<CheckOutcome> {
219
+ const runningVersion = options.runningVersion ?? VERSION
220
+ try {
221
+ const update = await findAvailableUpdate(options)
222
+ return { ok: true, status: { runningVersion, availableVersion: update?.version ?? null } }
223
+ } catch {
224
+ return { ok: false, status: { runningVersion, availableVersion: null } }
225
+ }
226
+ }
227
+
228
+ // One uncached check. The cached path below is what the API serves.
229
+ export async function getUpdateStatus(options: UpdateOptions = {}): Promise<UpdateStatus> {
230
+ return (await checkForUpdate(options)).status
231
+ }
232
+
233
+ // ---- cached status ----------------------------------------------------------
234
+
235
+ // There is deliberately no background timer. The check runs when a client asks
236
+ // and the cached answer has aged out, which means: a closed app makes no
237
+ // network calls at all, the cost stays flat no matter how many tabs or reloads
238
+ // there are, and a machine waking from sleep does exactly one check on the next
239
+ // poll instead of firing into a network stack that is not up yet.
240
+ export type UpdateTimings = {
241
+ // Nothing is checked this early into the process — one grace window per
242
+ // server boot, not per tab, so a burst of reloads cannot compound it.
243
+ bootGraceMs: number
244
+ // How long a successful answer is served before it is refreshed.
245
+ cacheTtlMs: number
246
+ // How long a *failed* check is remembered. Without this the client's poll
247
+ // interval becomes the retry interval and an offline machine hammers the
248
+ // registry all day.
249
+ failureBackoffMs: number
250
+ }
251
+
252
+ export const UPDATE_BOOT_GRACE_MS = 60_000
253
+ export const UPDATE_CACHE_TTL_MS = 60 * 60 * 1000
254
+ export const UPDATE_FAILURE_BACKOFF_MS = 5 * 60 * 1000
255
+
256
+ // Test seams (`MOI_UPDATE_*_MS`): the e2e drives real HTTP against a spawned
257
+ // server, so it needs these compressed to milliseconds.
258
+ function envMs(name: string, fallback: number): number {
259
+ const raw = Number(process.env[name])
260
+ return Number.isFinite(raw) && raw >= 0 ? raw : fallback
261
+ }
262
+
263
+ function defaultTimings(): UpdateTimings {
264
+ return {
265
+ bootGraceMs: envMs('MOI_UPDATE_BOOT_GRACE_MS', UPDATE_BOOT_GRACE_MS),
266
+ cacheTtlMs: envMs('MOI_UPDATE_CACHE_TTL_MS', UPDATE_CACHE_TTL_MS),
267
+ failureBackoffMs: envMs('MOI_UPDATE_FAILURE_BACKOFF_MS', UPDATE_FAILURE_BACKOFF_MS)
268
+ }
269
+ }
270
+
271
+ type StatusCache = {
272
+ status: UpdateStatus
273
+ attemptedAt: number
274
+ ok: boolean
275
+ }
276
+
277
+ type CachedStatusOptions = UpdateOptions & {
278
+ now?: () => number
279
+ uptimeMs?: () => number
280
+ timings?: Partial<UpdateTimings>
281
+ }
282
+
283
+ let statusCache: StatusCache | null = null
284
+ let statusInFlight: Promise<UpdateStatus> | null = null
285
+
286
+ // Wall-clock deltas only ever widen an interval here. A clock that jumped
287
+ // backwards (an NTP correction after sleep is the usual cause) would otherwise
288
+ // read as "checked in the future" and pin the cache forever, so treat it as
289
+ // infinitely old: the cost of being wrong is one extra check.
290
+ function elapsed(since: number, now: number): number {
291
+ return now >= since ? now - since : Number.POSITIVE_INFINITY
292
+ }
293
+
294
+ function needsRefresh(
295
+ cache: StatusCache | null,
296
+ now: number,
297
+ uptime: number,
298
+ timings: UpdateTimings
299
+ ): boolean {
300
+ if (uptime < timings.bootGraceMs) return false
301
+ if (!cache) return true
302
+ const age = elapsed(cache.attemptedAt, now)
303
+ return age >= (cache.ok ? timings.cacheTtlMs : timings.failureBackoffMs)
304
+ }
305
+
306
+ // What `GET /api/update` serves: the cached answer, refreshed lazily. Callers
307
+ // that arrive together share one refresh, so N tabs crossing the TTL boundary
308
+ // at the same moment produce one registry request, not N.
309
+ export async function getCachedUpdateStatus(
310
+ options: CachedStatusOptions = {}
311
+ ): Promise<UpdateStatus> {
312
+ const now = (options.now ?? Date.now)()
313
+ const uptime = (options.uptimeMs ?? defaultUptimeMs)()
314
+ const timings = { ...defaultTimings(), ...options.timings }
315
+
316
+ if (!needsRefresh(statusCache, now, uptime, timings)) {
317
+ return (
318
+ statusCache?.status ?? {
319
+ runningVersion: options.runningVersion ?? VERSION,
320
+ availableVersion: null
321
+ }
322
+ )
323
+ }
324
+
325
+ statusInFlight ??= checkForUpdate(options)
326
+ .then(outcome => {
327
+ statusCache = { status: outcome.status, attemptedAt: now, ok: outcome.ok }
328
+ return outcome.status
329
+ })
330
+ .finally(() => {
331
+ statusInFlight = null
332
+ })
333
+ return statusInFlight
334
+ }
335
+
336
+ function defaultUptimeMs(): number {
337
+ return process.uptime() * 1000
338
+ }
339
+
340
+ async function performUpdate(options: UpdateOptions): Promise<UpdateResult | null> {
341
+ const update = await findAvailableUpdate(options)
342
+ if (!update) return null
343
+
344
+ const argv = updateArgv(update.packageManager, update.version)
345
+ const exitCode = await (options.runManager ?? runPackageManager)(argv)
346
+ if (exitCode !== 0) {
347
+ throw new Error(
348
+ `${update.packageManager} exited with code ${exitCode}. Run \`moi update\` in a terminal for details.`
349
+ )
350
+ }
351
+ const installedVersion = await (options.readInstalledVersion ?? installedBinVersion)(update.bin)
352
+ if (installedVersion !== update.version) {
353
+ const detail = installedVersion
354
+ ? `The moi command reports v${installedVersion} instead of v${update.version}.`
355
+ : 'Could not verify the updated moi command.'
356
+ throw new Error(`${detail} Run \`moi update\` in a terminal for details.`)
357
+ }
358
+ return { installedVersion }
359
+ }
360
+
361
+ // Multiple open browser tabs share one install. They also share this promise,
362
+ // so two clicks never launch two global package-manager processes. A successful
363
+ // result stays cached for the few milliseconds until the server restarts.
364
+ //
365
+ // This guards this process only. A `moi update` run in a terminal while the UI
366
+ // installs is still two package managers writing one global tree; that needs a
367
+ // lock file both entry points take, which is not here yet.
368
+ let installInFlight: Promise<UpdateResult | null> | null = null
369
+
370
+ // Lets the API answer a second click with "already in progress" instead of
371
+ // silently reporting someone else's install as its own. Stays true once an
372
+ // install succeeds — the restart it scheduled has not landed yet, and
373
+ // `restartPendingForUpdate` tells those two states apart.
374
+ export function updateInProgress(): boolean {
375
+ return installInFlight !== null
376
+ }
377
+
378
+ export function installUpdate(options: UpdateOptions = {}): Promise<UpdateResult | null> {
379
+ installInFlight ??= performUpdate(options).then(
380
+ result => {
381
+ if (!result) installInFlight = null
382
+ // The install just invalidated whatever the cache says is available.
383
+ else statusCache = null
384
+ return result
385
+ },
386
+ error => {
387
+ installInFlight = null
388
+ throw error
389
+ }
390
+ )
391
+ return installInFlight
392
+ }
393
+
394
+ // ---- restart ----------------------------------------------------------------
395
+
396
+ // Long enough for the HTTP response that triggered it to be flushed to the
397
+ // browser that clicked — it is that response the client waits on before it
398
+ // starts polling for the restarted server.
399
+ export const UPDATE_RESTART_DELAY_MS = 500
400
+
401
+ let restartScheduled = false
402
+
403
+ export function restartPendingForUpdate(): boolean {
404
+ return restartScheduled
405
+ }
406
+
407
+ // Hand the process back to whoever supervises it: the foreground CLI
408
+ // (`superviseServerUpdates`) and service managers alike bring it back on a
409
+ // non-zero exit, and 75 is the code they agree means "updated, come back".
410
+ // Latched, so concurrent callers schedule one SIGTERM rather than one each.
411
+ export function scheduleRestartForUpdate(delayMs = UPDATE_RESTART_DELAY_MS): boolean {
412
+ if (restartScheduled) return false
413
+ restartScheduled = true
414
+ const timer = setTimeout(() => {
415
+ process.exitCode = UPDATE_RESTART_EXIT_CODE
416
+ process.kill(process.pid, 'SIGTERM')
417
+ }, delayMs)
418
+ timer.unref()
419
+ return true
420
+ }
421
+
422
+ export function __resetUpdateStateForTests(): void {
423
+ installInFlight = null
424
+ statusCache = null
425
+ statusInFlight = null
426
+ installAnalysis = null
427
+ managerProbe = null
428
+ restartScheduled = false
429
+ }
package/server/web.ts CHANGED
@@ -225,7 +225,7 @@ function shutdown() {
225
225
  } catch {}
226
226
  for (const h of allHarnesses()) h.shutdown?.()
227
227
  killAllWorkers()
228
- process.exit(0)
228
+ process.exit()
229
229
  }
230
230
  process.on('SIGTERM', shutdown)
231
231
  process.on('SIGINT', shutdown)
@@ -1 +0,0 @@
1
- import{Oc as a,Pc as b}from"/chunk-yt2qjn3m.js";import"/chunk-yhj9bg1s.js";import"/chunk-9y2zbzqz.js";export{b as useAppConfig,a as loadAppConfig};