moi-computer 0.7.0 → 0.8.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 (123) hide show
  1. package/README.md +2 -2
  2. package/client/api/workspace-keys.ts +1 -2
  3. package/client/app/AppRouter.tsx +10 -3
  4. package/client/app/routes/HomeRoute.tsx +1 -1
  5. package/client/app/shell/SidebarLayout.tsx +2 -14
  6. package/client/components/shared/BottomPanel.tsx +2 -1
  7. package/client/components/shared/Composer.tsx +20 -7
  8. package/client/components/shared/PanelHeader.tsx +8 -1
  9. package/client/components/ui/button.tsx +3 -3
  10. package/client/components/ui/dialog.tsx +1 -1
  11. package/client/components/ui/dropdown-menu.tsx +2 -2
  12. package/client/components/ui/hover-card.tsx +1 -1
  13. package/client/components/ui/popover.tsx +1 -1
  14. package/client/components/ui/resizable.tsx +40 -0
  15. package/client/features/applets/AppletMount.tsx +9 -22
  16. package/client/features/applets/applet-cache.ts +7 -0
  17. package/client/features/applets/applet-styles.ts +21 -1
  18. package/client/features/applets/useApplet.ts +1 -1
  19. package/client/features/chat/ChatEmptyState.tsx +9 -11
  20. package/client/features/chat/ChatPanel.tsx +76 -48
  21. package/client/features/chat/ChatPopup.tsx +16 -2
  22. package/client/features/chat/ChatPromptBubbles.tsx +6 -8
  23. package/client/features/chat/ChatSelector.tsx +25 -8
  24. package/client/features/chat/ModelPicker.tsx +5 -4
  25. package/client/features/chat/TurnView.tsx +108 -13
  26. package/client/features/chat/api.ts +1 -18
  27. package/client/features/chat/chat-send.ts +2 -2
  28. package/client/features/chat/{ChatComposer.tsx → composer/ChatComposer.tsx} +24 -9
  29. package/client/features/chat/composer/banners/ChatErrorBanner.tsx +28 -0
  30. package/client/features/chat/composer/banners/ComposerBanner.tsx +30 -0
  31. package/client/features/chat/composer/banners/WorkspaceAgentAvailabilityBanner.tsx +91 -0
  32. package/client/features/{workspace → chat/composer/banners}/WorkspaceSkillUpdateBanner.tsx +9 -7
  33. package/client/features/chat/composer/useWorkspaceComposerState.tsx +74 -0
  34. package/client/features/{workspace → chat/composer}/useWorkspaceSkillUpdates.ts +1 -1
  35. package/client/features/chat/group-turns.ts +46 -28
  36. package/client/features/chat/interleave-notices.ts +84 -0
  37. package/client/features/chat/model-order.ts +9 -3
  38. package/client/features/chat/tool-group/TimelineRow.tsx +23 -11
  39. package/client/features/chat/tool-group/ToolCallGroup.tsx +38 -3
  40. package/client/features/chat/tool-group/format.ts +23 -7
  41. package/client/features/chat/useAppletChatMessage.ts +11 -16
  42. package/client/features/chat/useChat.ts +3 -7
  43. package/client/features/dev/ChatStatesPage.tsx +428 -0
  44. package/client/features/dev/DevIndexPage.tsx +52 -0
  45. package/client/features/dev/DevRoutes.tsx +6 -3
  46. package/client/features/dev/HarnessDebugPage.tsx +3 -3
  47. package/client/features/dev/chat-states-fixtures.ts +744 -0
  48. package/client/features/home/api.ts +0 -10
  49. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +21 -64
  50. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +1 -1
  51. package/client/features/scratchpad/Scratchpad.tsx +5 -3
  52. package/client/features/scratchpad/scratch-session.ts +71 -0
  53. package/client/features/views/ViewBuilderTab.tsx +5 -4
  54. package/client/features/views/ViewManager.tsx +258 -0
  55. package/client/features/views/useViewBuilderActions.ts +2 -2
  56. package/client/features/views/view-residency.ts +77 -0
  57. package/client/features/widgets/WidgetFrame.tsx +6 -2
  58. package/client/features/workspace/CustomizePanel.tsx +40 -24
  59. package/client/features/workspace/WorkspaceLayoutContext.tsx +12 -2
  60. package/client/features/workspace/WorkspaceScreen.tsx +131 -201
  61. package/client/features/workspace/WorkspaceSplitLayout.tsx +111 -0
  62. package/client/features/workspace/WorkspaceTabs.tsx +1 -1
  63. package/client/features/workspace/api.ts +33 -8
  64. package/client/features/workspace/useFitsSplitLayout.ts +31 -5
  65. package/client/index.css +5 -2
  66. package/client/lib/flags.ts +4 -3
  67. package/client/runtime/useWorkspaceEvents.ts +18 -1
  68. package/client/runtime/workspace-theme.ts +29 -10
  69. package/client/store/ui.ts +5 -1
  70. package/client/theme.css +96 -6
  71. package/dist/{chunk-0pcdwjkp.js → chunk-2vaafjp4.js} +1 -1
  72. package/dist/{chunk-9y2zbzqz.js → chunk-35fq49qa.js} +1 -1
  73. package/dist/chunk-gny990qx.css +1 -0
  74. package/dist/chunk-gt7n06ef.js +1 -0
  75. package/dist/{chunk-rxvx4ta9.js → chunk-kkj86722.js} +75 -75
  76. package/dist/chunk-n7pga5x3.js +80 -0
  77. package/dist/chunk-xeyxk7ep.js +10 -0
  78. package/dist/{chunk-w3tnv51j.js → chunk-xzx7c9hq.js} +1 -1
  79. package/dist/index.html +1 -1
  80. package/lib/format.ts +17 -1
  81. package/lib/themes.ts +123 -51
  82. package/lib/types.ts +40 -13
  83. package/lib/workspace-layout.ts +2 -2
  84. package/package.json +6 -4
  85. package/server/agent.ts +199 -0
  86. package/server/api.ts +38 -90
  87. package/server/bundler/build-applet.ts +7 -4
  88. package/server/cli.ts +46 -15
  89. package/server/control.ts +13 -6
  90. package/server/env-apply.ts +4 -0
  91. package/server/harness/README.md +28 -12
  92. package/server/harness/claude-code/auth.ts +54 -0
  93. package/server/harness/claude-code/index.ts +6 -1
  94. package/server/harness/codex/adapter.ts +9 -1
  95. package/server/harness/codex/auth.ts +50 -0
  96. package/server/harness/codex/index.ts +6 -1
  97. package/server/harness/codex/session.ts +33 -14
  98. package/server/harness/openclaw/NOTES.md +518 -187
  99. package/server/harness/openclaw/adapter.ts +125 -31
  100. package/server/harness/openclaw/compat.ts +99 -0
  101. package/server/harness/openclaw/cron-view.ts +78 -0
  102. package/server/harness/openclaw/discovery.ts +145 -52
  103. package/server/harness/openclaw/gateway.ts +224 -36
  104. package/server/harness/openclaw/index.ts +56 -21
  105. package/server/harness/openclaw/session.ts +971 -55
  106. package/server/harness/openclaw/strip.ts +87 -15
  107. package/server/harness/openclaw/thinking.ts +198 -0
  108. package/server/harness/types.ts +10 -5
  109. package/server/layout.ts +5 -2
  110. package/server/moi-scaffold.ts +1 -1
  111. package/server/registry.ts +0 -20
  112. package/server/theme.ts +24 -27
  113. package/workspace/.claude/skills/moi-workspace/DESIGN.md +100 -53
  114. package/workspace/.claude/skills/moi-workspace/SKILL.md +10 -12
  115. package/client/features/dev/PixelPainter.tsx +0 -94
  116. package/client/features/dev/PlaygroundPage.tsx +0 -69
  117. package/dist/chunk-175bm057.js +0 -27
  118. package/dist/chunk-55sh4dty.js +0 -2
  119. package/dist/chunk-afgbg75t.js +0 -50
  120. package/dist/chunk-agtetn7n.css +0 -1
  121. package/dist/chunk-dfs36zgc.js +0 -1
  122. package/dist/chunk-exj6hr30.js +0 -9
  123. package/dist/chunk-m11ckkxd.js +0 -51
@@ -70,7 +70,6 @@ export type ImportWorkspaceInput = {
70
70
  export type WorkspaceSetupInfo = {
71
71
  root: string
72
72
  displayRoot: string
73
- canChooseFolder: boolean
74
73
  // Per-backend runtime availability (are the Claude/Codex CLIs installed?),
75
74
  // keyed by workspace type. Missing entries mean available.
76
75
  availability?: Partial<Record<WorkspaceType, HarnessAvailability>>
@@ -87,15 +86,6 @@ export function useWorkspaceSetupInfo() {
87
86
  })
88
87
  }
89
88
 
90
- export type ChooseFolderResult = DiscoveredWorkspace | { canceled: true }
91
-
92
- export function useChooseFolder() {
93
- return useMutation<ChooseFolderResult, Error, void>({
94
- mutationFn: () =>
95
- requestJson('/api/workspaces/choose-folder', { method: 'POST' }, 'Failed to choose folder')
96
- })
97
- }
98
-
99
89
  export type CreateWorkspaceInput = {
100
90
  name: string
101
91
  type: WorkspaceType
@@ -2,7 +2,7 @@ import { type FormEvent, type ReactElement, useState } from 'react'
2
2
 
3
3
  import { useLocation } from 'wouter'
4
4
 
5
- import { useChooseFolder, useCreateWorkspace, useWorkspaceSetupInfo } from '../api'
5
+ import { useCreateWorkspace, useWorkspaceSetupInfo } from '../api'
6
6
  import { Button } from '@/client/components/ui/button'
7
7
  import {
8
8
  Dialog,
@@ -12,15 +12,12 @@ import {
12
12
  } from '@/client/components/ui/dialog'
13
13
  import { Input } from '@/client/components/ui/input'
14
14
  import { Tooltip, TooltipContent, TooltipTrigger } from '@/client/components/ui/tooltip'
15
- import { cn } from '@/client/lib/cn'
16
15
  import { validateWorkspaceFolderName } from '@/lib/workspace-name'
17
16
  import { WORKSPACE_TYPE_ORDER } from '@/lib/workspace-types'
18
17
  import type { WorkspaceType } from '@/lib/types'
19
18
 
20
- import { ImportWorkspaceStep } from './ImportWorkspaceDialog'
21
19
  import { WorkspaceAgentStep } from './WorkspaceAgentStep'
22
20
  import { WorkspaceDialogContent } from './WorkspaceDialogContent'
23
- import { useWorkspaceImport } from './useWorkspaceImport'
24
21
 
25
22
  type CreateWorkspaceDialogProps = {
26
23
  trigger: ReactElement
@@ -34,8 +31,6 @@ export function CreateWorkspaceDialog({ trigger }: CreateWorkspaceDialogProps) {
34
31
  const [, navigate] = useLocation()
35
32
  const info = useWorkspaceSetupInfo()
36
33
  const createMutation = useCreateWorkspace()
37
- const chooseFolder = useChooseFolder()
38
- const importFlow = useWorkspaceImport({ onSuccess: entry => finish(entry.id) })
39
34
 
40
35
  const [open, setOpen] = useState(false)
41
36
  const [step, setStep] = useState<CreateWorkspaceStep>('agent')
@@ -44,8 +39,6 @@ export function CreateWorkspaceDialog({ trigger }: CreateWorkspaceDialogProps) {
44
39
 
45
40
  const trimmedName = name.trim()
46
41
  const nameError = trimmedName ? validateWorkspaceFolderName(trimmedName) : null
47
- const canChooseFolder = info.data?.canChooseFolder ?? true
48
- const isImporting = chooseFolder.isPending || importFlow.isPending
49
42
  const isCreating = createMutation.isPending
50
43
 
51
44
  function finish(workspaceId: string) {
@@ -57,23 +50,9 @@ export function CreateWorkspaceDialog({ trigger }: CreateWorkspaceDialogProps) {
57
50
  setStep('agent')
58
51
  setType(DEFAULT_WORKSPACE_TYPE)
59
52
  setName('')
60
- chooseFolder.reset()
61
- importFlow.reset()
62
53
  createMutation.reset()
63
54
  }
64
55
 
65
- async function chooseExistingFolder() {
66
- if (isImporting) return
67
- chooseFolder.reset()
68
-
69
- try {
70
- const result = await chooseFolder.mutateAsync()
71
- if (!('canceled' in result)) importFlow.startImport(result)
72
- } catch {
73
- // The agent step renders the folder-picker error.
74
- }
75
- }
76
-
77
56
  function continueToName() {
78
57
  createMutation.reset()
79
58
  setStep('name')
@@ -95,30 +74,13 @@ export function CreateWorkspaceDialog({ trigger }: CreateWorkspaceDialogProps) {
95
74
  >
96
75
  <DialogTrigger render={trigger} />
97
76
  <WorkspaceDialogContent>
98
- {importFlow.choice ? (
99
- <ImportWorkspaceStep
100
- choice={importFlow.choice}
101
- availability={info.data?.availability}
102
- isPending={importFlow.isPending}
103
- errorMessage={importFlow.error?.message}
104
- onTypeChange={importFlow.selectType}
105
- onCancel={importFlow.reset}
106
- onSubmit={importFlow.submit}
107
- />
108
- ) : step === 'agent' ? (
77
+ {step === 'agent' ? (
109
78
  <WorkspaceAgentStep
110
79
  title="Create new workspace"
111
80
  selectedType={type}
112
81
  availability={info.data?.availability}
113
- isPending={isImporting}
114
- errorMessage={(chooseFolder.error ?? importFlow.error)?.message}
115
- secondaryAction={
116
- <ExistingFolderButton
117
- available={canChooseFolder}
118
- disabled={isImporting}
119
- onClick={chooseExistingFolder}
120
- />
121
- }
82
+ isPending={false}
83
+ secondaryAction={<ExistingFolderButton />}
122
84
  primaryLabel="Next"
123
85
  onTypeChange={setType}
124
86
  onSubmit={continueToName}
@@ -204,39 +166,34 @@ function WorkspaceNameStep({
204
166
  )
205
167
  }
206
168
 
207
- type ExistingFolderButtonProps = {
208
- available: boolean
209
- disabled: boolean
210
- onClick: () => void
211
- }
212
-
213
- function ExistingFolderButton({ available, disabled, onClick }: ExistingFolderButtonProps) {
169
+ // Importing a folder from the app is on hold: the native picker only ever ran on
170
+ // macOS and cannot work at all when moi is opened from another device. The
171
+ // button stays as the signpost for the console route.
172
+ function ExistingFolderButton() {
214
173
  const button = (
215
174
  <Button
216
175
  variant="secondary"
217
- disabled={available && disabled}
218
- aria-disabled={!available || undefined}
219
- onClick={event => {
220
- if (!available) {
221
- event.preventDefault()
222
- return
223
- }
224
- onClick()
225
- }}
226
- className={cn(!available && 'cursor-not-allowed opacity-50')}
176
+ aria-disabled
177
+ onClick={event => event.preventDefault()}
178
+ className="cursor-not-allowed opacity-50"
227
179
  >
228
180
  Use existing folder
229
181
  </Button>
230
182
  )
231
183
 
232
- if (available) return button
233
-
234
184
  return (
235
185
  <Tooltip>
236
186
  <TooltipTrigger render={button} />
237
- <TooltipContent>
238
- Run <code className="rounded-xs bg-accent px-1 py-0.5 font-mono">moi init</code> in the
239
- folder to add it manually
187
+ <TooltipContent className="max-w-64">
188
+ {/* The popup lays its children out in a row — one span keeps the copy
189
+ flowing as a sentence with the command inline. */}
190
+ <span className="text-center">
191
+ Not supported yet — run{' '}
192
+ <code className="rounded-xs bg-accent px-1 py-0.5 font-mono whitespace-nowrap">
193
+ moi init
194
+ </code>{' '}
195
+ in the folder from your console to add it
196
+ </span>
240
197
  </TooltipContent>
241
198
  </Tooltip>
242
199
  )
@@ -19,7 +19,7 @@ type ImportWorkspaceStepProps = {
19
19
  onSubmit: () => void
20
20
  }
21
21
 
22
- export function ImportWorkspaceStep({
22
+ function ImportWorkspaceStep({
23
23
  choice,
24
24
  availability,
25
25
  isPending,
@@ -21,6 +21,7 @@ import 'tldraw/tldraw.css'
21
21
 
22
22
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
23
23
  import { setScratchExecutor } from '@/client/features/scratchpad/scratch-executor'
24
+ import { persistScratchSession } from '@/client/features/scratchpad/scratch-session'
24
25
  import { type WorkspaceEvent, useWorkspaceEvent } from '@/client/runtime/useWorkspaceEvents'
25
26
  import type { ScratchOp, ScratchOpResult } from '@/lib/types'
26
27
  import {
@@ -107,9 +108,7 @@ function makeAssetStore(workspaceId: string): TLAssetStore {
107
108
  // from the panel, leaving just the zoom menu. Kept on defaults: NavigationPanel
108
109
  // (zoom), ContextMenu, KeyboardShortcutsDialog.
109
110
  function ScratchBackground() {
110
- return (
111
- <div className="absolute inset-0 bg-[color-mix(in_oklch,var(--muted),var(--background)_50%)]" />
112
- )
111
+ return <div className="absolute inset-0 bg-background" />
113
112
  }
114
113
 
115
114
  function UniformGrid({ x, y, z, size }: TLGridProps) {
@@ -270,6 +269,8 @@ export function Scratchpad() {
270
269
  // a lock. ('fill' = the style bar's "Solid"; 'solid' there means "Semi".)
271
270
  editor.setStyleForNextShapes(DefaultFillStyle, 'fill')
272
271
  })
272
+ // Restore this browser's camera/zoom for the workspace, then keep it saved.
273
+ const stopSessionSave = persistScratchSession(editor, workspaceId)
273
274
  const unlisten = editor.store.listen(
274
275
  () => {
275
276
  if (applyingRemote.current) {
@@ -309,6 +310,7 @@ export function Scratchpad() {
309
310
  editor.focus()
310
311
  return () => {
311
312
  unlisten()
313
+ stopSessionSave()
312
314
  doc.removeEventListener('pointerdown', onPointerDown, true)
313
315
  if (saveTimer.current) clearTimeout(saveTimer.current)
314
316
  setScratchExecutor(workspaceId, null)
@@ -0,0 +1,71 @@
1
+ import {
2
+ type Editor,
3
+ type TLSessionStateSnapshot,
4
+ createSessionStateSnapshotSignal,
5
+ loadSessionStateSnapshotIntoStore,
6
+ react
7
+ } from 'tldraw'
8
+ import { create } from 'zustand'
9
+ import { persist } from 'zustand/middleware'
10
+
11
+ // Camera/zoom and the rest of tldraw's session state are per-browser UI
12
+ // preferences — never written to `.moi/.scratchpad.json`, which holds only the
13
+ // shared document. They get their own persisted store (`moi:scratch-sessions`)
14
+ // rather than a slot in the `moi:ui` store: the blobs are tldraw's own
15
+ // versioned TLSessionStateSnapshot, migrated by tldraw on load, and saving one
16
+ // rewrites the whole persisted record — better to keep that churn off app prefs.
17
+ type ScratchSessionStore = {
18
+ sessions: Record<string, TLSessionStateSnapshot>
19
+ setSession: (workspaceId: string, session: TLSessionStateSnapshot) => void
20
+ removeSession: (workspaceId: string) => void
21
+ }
22
+
23
+ export const useScratchSessionStore = create<ScratchSessionStore>()(
24
+ persist(
25
+ set => ({
26
+ sessions: {},
27
+ setSession: (workspaceId, session) =>
28
+ set(state => ({ sessions: { ...state.sessions, [workspaceId]: session } })),
29
+ removeSession: workspaceId =>
30
+ set(state => {
31
+ const sessions = { ...state.sessions }
32
+ delete sessions[workspaceId]
33
+ return { sessions }
34
+ })
35
+ }),
36
+ { name: 'moi:scratch-sessions' }
37
+ )
38
+ )
39
+
40
+ const SAVE_DEBOUNCE_MS = 500
41
+
42
+ // Restore this browser's saved session (camera, zoom, selection) into a mounted
43
+ // editor, then keep it saved as it changes. Call from onMount, after the store
44
+ // is hydrated from the server snapshot — loading the session then just moves
45
+ // the viewport. Returns a cleanup that stops the watcher. A corrupt or
46
+ // version-skewed snapshot is discarded and the editor keeps its default
47
+ // viewport.
48
+ export function persistScratchSession(editor: Editor, workspaceId: string): () => void {
49
+ const { sessions, setSession, removeSession } = useScratchSessionStore.getState()
50
+ const saved = sessions[workspaceId]
51
+ if (saved) {
52
+ try {
53
+ loadSessionStateSnapshotIntoStore(editor.store, saved)
54
+ } catch {
55
+ removeSession(workspaceId)
56
+ }
57
+ }
58
+ const signal = createSessionStateSnapshotSignal(editor.store)
59
+ let timer: ReturnType<typeof setTimeout> | null = null
60
+ const stop = react('save scratch session', () => {
61
+ const session = signal.get()
62
+ if (!session) return
63
+ // Debounced: the signal updates on every camera tick while panning/zooming.
64
+ if (timer) clearTimeout(timer)
65
+ timer = setTimeout(() => setSession(workspaceId, session), SAVE_DEBOUNCE_MS)
66
+ })
67
+ return () => {
68
+ stop()
69
+ if (timer) clearTimeout(timer)
70
+ }
71
+ }
@@ -3,6 +3,7 @@ import { type FormEvent, type KeyboardEvent, useEffect, useRef, useState } from
3
3
  import { Button } from '@/client/components/ui/button'
4
4
  import {
5
5
  canSubmitComposerAction,
6
+ type ComposerAvailability,
6
7
  Composer,
7
8
  ComposerFooter,
8
9
  ComposerSubmitButton,
@@ -14,7 +15,7 @@ import { Spinner } from '@/client/components/ui/spinner'
14
15
 
15
16
  type ViewBuilderTabProps = {
16
17
  builder: ViewBuilder
17
- unavailableReason: string | null | undefined
18
+ composerAvailability: ComposerAvailability
18
19
  onSave: (requirements: string) => Promise<unknown>
19
20
  onSubmit: (requirements: string) => Promise<unknown>
20
21
  onOpenChat: () => void
@@ -23,7 +24,7 @@ type ViewBuilderTabProps = {
23
24
 
24
25
  export function ViewBuilderTab({
25
26
  builder,
26
- unavailableReason,
27
+ composerAvailability,
27
28
  onSave,
28
29
  onSubmit,
29
30
  onOpenChat,
@@ -36,7 +37,7 @@ export function ViewBuilderTab({
36
37
  const onSaveRef = useRef(onSave)
37
38
  onSaveRef.current = onSave
38
39
  const hasRequirements = requirements.trim().length > 0
39
- const canSubmit = canSubmitComposerAction(hasRequirements, submitting, unavailableReason)
40
+ const canSubmit = canSubmitComposerAction(hasRequirements, submitting, composerAvailability)
40
41
 
41
42
  useEffect(() => {
42
43
  if (builder.status !== 'draft' || requirements === builder.input.requirements) return
@@ -101,7 +102,7 @@ export function ViewBuilderTab({
101
102
  label="Build view"
102
103
  hasContent={hasRequirements}
103
104
  loading={submitting}
104
- unavailableReason={unavailableReason}
105
+ availability={composerAvailability}
105
106
  />
106
107
  </ComposerFooter>
107
108
  </Composer>
@@ -0,0 +1,258 @@
1
+ // The workspace's view surface: every view the user has open lives here, and
2
+ // switching tabs picks one of them instead of tearing the old one down and
3
+ // building the new one up.
4
+ //
5
+ // Why no transition between views: a view is an agent-authored bundle with its
6
+ // own styles and its own state. Animating the swap means keeping the outgoing
7
+ // DOM alive past the moment React drops the applet's <style> tag, so the view
8
+ // spends its exit unstyled. Keeping views mounted removes the problem instead
9
+ // of timing around it — the switch is instant, and a view only ever loads once.
10
+ //
11
+ // The one animation left is the rebuild dissolve: when the view you are looking
12
+ // at is rebuilt, the new build fades in over the old one. That is safe here
13
+ // because both builds share the slot's style tag (see ViewSlot), and it is
14
+ // worth the 200ms — it is the only signal that the thing under your cursor just
15
+ // changed underneath you.
16
+ import { Activity, type ComponentType, useCallback, useEffect, useRef, useState } from 'react'
17
+
18
+ import { Spinner } from '@/client/components/ui/spinner'
19
+ import { appletScope, appletStyleKey } from '@/client/features/applets/applet-cache'
20
+ import { useAppletStyle } from '@/client/features/applets/applet-styles'
21
+ import {
22
+ type AppletComponentProps,
23
+ type AppletState,
24
+ useView
25
+ } from '@/client/features/applets/useApplet'
26
+ import { WidgetErrorBoundary } from '@/client/features/applets/WidgetErrorBoundary'
27
+ import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
28
+ import { cn } from '@/client/lib/cn'
29
+ import type { ViewInfo } from '@/lib/types'
30
+
31
+ import {
32
+ nextEvictionDelay,
33
+ reconcileResidents,
34
+ type ResidentView,
35
+ sameResidents
36
+ } from './view-residency'
37
+
38
+ type ViewManagerProps = {
39
+ views: ViewInfo[]
40
+ // The view the active tab names, or null when another tab is on screen. The
41
+ // manager stays mounted either way — that is what makes coming back from the
42
+ // agent or widgets tab instant too.
43
+ activeViewId: string | null
44
+ // The active view's addressable state, read from navigation state (focusTab /
45
+ // `moi tab focus`). `{}` on a fresh mount, a new browser tab, or a plain
46
+ // tab-bar click — a view must render sensibly with that.
47
+ params: Record<string, unknown>
48
+ }
49
+
50
+ export function ViewManager({ views, activeViewId, params }: ViewManagerProps) {
51
+ const residents = useResidentViews(activeViewId, views)
52
+ // Render in workspace order, not residency order: the policy ranks views by
53
+ // recency, and reordering the children would make React move live DOM around
54
+ // on every switch. The slots are stacked absolutely with one visible, so
55
+ // their order on the page carries no meaning.
56
+ const resident = new Set(residents.map(entry => entry.id))
57
+
58
+ return (
59
+ // Hidden rather than unmounted when no view tab is on screen: the parked
60
+ // views keep their DOM, and `display: none` keeps this layer out of the
61
+ // layout and out of the way of pointer events on the tab that IS on screen.
62
+ <div className={cn('relative min-h-0 flex-1 overflow-hidden', !activeViewId && 'hidden')}>
63
+ {views
64
+ .filter(view => resident.has(view.id))
65
+ .map(view => (
66
+ <ViewSlot key={view.id} view={view} active={view.id === activeViewId} params={params} />
67
+ ))}
68
+ </div>
69
+ )
70
+ }
71
+
72
+ // The views mounted right now: the active one, plus the recently-visited ones
73
+ // parked offscreen. The policy (and its timing) lives in view-residency.ts.
74
+ function useResidentViews(activeId: string | null, views: ViewInfo[]): ResidentView[] {
75
+ const [residents, setResidents] = useState<ResidentView[]>([])
76
+ // A workspace refetch hands us a new array on every event; residency only
77
+ // cares whether a view appeared or disappeared. So the effect keys off the id
78
+ // set, and the reconcile reads the current list through the ref.
79
+ const viewsRef = useRef(views)
80
+ viewsRef.current = views
81
+ const availableIds = views.map(view => view.id).join('\n')
82
+
83
+ const reconcile = useCallback(() => {
84
+ setResidents(current => {
85
+ const next = reconcileResidents(current, {
86
+ activeId,
87
+ available: new Set(viewsRef.current.map(view => view.id)),
88
+ now: Date.now()
89
+ })
90
+ return sameResidents(current, next) ? current : next
91
+ })
92
+ }, [activeId])
93
+
94
+ // Promote the view the user switched to, and release the one it replaced.
95
+ useEffect(() => {
96
+ reconcile()
97
+ }, [availableIds, reconcile])
98
+
99
+ // Then evict on the retention deadline — one timer, for the nearest one.
100
+ useEffect(() => {
101
+ const delay = nextEvictionDelay(residents, Date.now())
102
+ if (delay === null) return
103
+ const timer = setTimeout(reconcile, delay)
104
+ return () => clearTimeout(timer)
105
+ }, [reconcile, residents])
106
+
107
+ return residents
108
+ }
109
+
110
+ type ViewSlotProps = {
111
+ view: ViewInfo
112
+ active: boolean
113
+ params: Record<string, unknown>
114
+ }
115
+
116
+ // One resident view. The bundle it holds is loaded and kept fresh for as long
117
+ // as the slot lives — a view rebuilt while parked picks the new build up in
118
+ // place, so it is current the moment the user comes back to it.
119
+ function ViewSlot({ view, active, params }: ViewSlotProps) {
120
+ const workspaceId = useWorkspaceId()
121
+ const bundle = useView(view.id)
122
+ const { current, outgoing } = useLoadedBundle(bundle, active)
123
+ // A parked view keeps rendering with the params it was last shown with: the
124
+ // active view's `focusTab` state is not its to render.
125
+ const [shownParams, setShownParams] = useState(params)
126
+ if (active && shownParams !== params) setShownParams(params)
127
+
128
+ // The applet's <style> is acquired HERE, outside the Activity below. Hiding
129
+ // an Activity unmounts its children's effects, which would strip the styles
130
+ // off the page while the DOM they style is still parked — the exact flash
131
+ // this component exists to remove. The tag drops when the slot is evicted.
132
+ // Holding it here is also what lets the dissolve below overlap two builds:
133
+ // the styles belong to the slot, not to either frame. The active view's sheet
134
+ // is raised to the end of <head> so the global at-rule names it shares with
135
+ // the parked views resolve to the one on screen.
136
+ useAppletStyle(
137
+ appletStyleKey('views', workspaceId, view.id),
138
+ current?.version ?? bundle.version,
139
+ active
140
+ )
141
+
142
+ const failed = bundle.status === 'error'
143
+
144
+ return (
145
+ <>
146
+ {active && failed && (
147
+ <p className="absolute inset-0 p-4 text-xs text-destructive">{bundle.error}</p>
148
+ )}
149
+ {active && !failed && !current && <ViewSplash />}
150
+ {current &&
151
+ !failed && (
152
+ // React hides these nodes with `display: none` while the Activity is
153
+ // hidden, so a parked view neither paints nor swallows clicks.
154
+ <Activity mode={active ? 'visible' : 'hidden'}>
155
+ {outgoing && (
156
+ <ViewFrame key={outgoing.version} view={view} build={outgoing} params={shownParams} />
157
+ )}
158
+ <ViewFrame
159
+ key={current.version}
160
+ view={view}
161
+ build={current}
162
+ params={shownParams}
163
+ entering={outgoing !== null}
164
+ />
165
+ </Activity>
166
+ )}
167
+ </>
168
+ )
169
+ }
170
+
171
+ type ViewFrameProps = {
172
+ view: ViewInfo
173
+ build: ViewBuild
174
+ params: Record<string, unknown>
175
+ // Play the rebuild dissolve. Set on the incoming build only, and only while
176
+ // the build it replaced is still rendered underneath it.
177
+ entering?: boolean
178
+ }
179
+
180
+ // One build of one view, in its style scope. Frames stack absolutely, so during
181
+ // a rebuild the incoming one dissolves in over the outgoing one still on screen.
182
+ function ViewFrame({ view, build, params, entering }: ViewFrameProps) {
183
+ const workspaceId = useWorkspaceId()
184
+
185
+ return (
186
+ <div
187
+ data-applet={appletScope('views', view.id)}
188
+ className={cn(
189
+ 'absolute inset-0 overflow-auto',
190
+ entering && 'animate-in duration-200 ease-out blur-in-4 fade-in'
191
+ )}
192
+ >
193
+ <WidgetErrorBoundary
194
+ name={view.id}
195
+ kind="view"
196
+ workspaceId={workspaceId}
197
+ resetKey={build.version}
198
+ >
199
+ <build.Component params={params} />
200
+ </WidgetErrorBoundary>
201
+ </div>
202
+ )
203
+ }
204
+
205
+ type ViewBuild = {
206
+ Component: ComponentType<AppletComponentProps>
207
+ version: number
208
+ }
209
+
210
+ type LoadedBundle = {
211
+ // The build to render, held across reloads. A rebuild flips the bundle back
212
+ // to `loading` for as long as the fetch takes, and swapping a live view for a
213
+ // spinner every time the agent edits it is worse than showing the previous
214
+ // build for that moment. The splash is for a view with nothing to show yet —
215
+ // the first time it is opened.
216
+ current: ViewBuild | null
217
+ // The build `current` just replaced, kept underneath for the length of the
218
+ // dissolve so the new one fades in over the view instead of over an empty
219
+ // panel. Null except during a rebuild swap on screen.
220
+ outgoing: ViewBuild | null
221
+ }
222
+
223
+ // How long the outgoing build stays underneath. Matches the `duration-200` the
224
+ // incoming frame animates with.
225
+ const DISSOLVE_MS = 200
226
+
227
+ function useLoadedBundle(bundle: AppletState, dissolve: boolean): LoadedBundle {
228
+ const [loaded, setLoaded] = useState<LoadedBundle>({ current: null, outgoing: null })
229
+
230
+ if (bundle.status === 'ready' && loaded.current?.version !== bundle.version) {
231
+ const build = { Component: bundle.Component, version: bundle.version }
232
+ // The first build of a view has nothing to dissolve from, and a parked view
233
+ // has nobody watching — both swap straight in.
234
+ setLoaded(previous => ({ current: build, outgoing: dissolve ? previous.current : null }))
235
+ }
236
+
237
+ useEffect(() => {
238
+ if (!loaded.outgoing) return
239
+ const timer = setTimeout(
240
+ () => setLoaded(previous => ({ ...previous, outgoing: null })),
241
+ DISSOLVE_MS
242
+ )
243
+ return () => clearTimeout(timer)
244
+ }, [loaded.outgoing])
245
+
246
+ return loaded
247
+ }
248
+
249
+ // A view's one loading moment: the first open, while its bundle is fetched. The
250
+ // delay keeps it off screen entirely for a fast load — the common case, since
251
+ // the module cache outlives eviction and only the network trip is new.
252
+ function ViewSplash() {
253
+ return (
254
+ <div className="absolute inset-0 flex animate-in items-center justify-center delay-150 duration-200 fill-mode-both fade-in">
255
+ <Spinner className="text-muted-foreground" />
256
+ </div>
257
+ )
258
+ }
@@ -1,9 +1,9 @@
1
1
  import { useQueryClient } from '@tanstack/react-query'
2
2
 
3
- import { useWorkspaceModels } from '@/client/features/chat/api'
4
3
  import { resolveChatRunOptions, startOptimisticTurn } from '@/client/features/chat/chat-send'
5
4
  import { liveStore } from '@/client/features/chat/chat-store'
6
5
  import { useSelectedSession } from '@/client/features/chat/useSelectedSession'
6
+ import { useWorkspaceAgent } from '@/client/features/workspace/api'
7
7
  import { useWorkspaceLayoutCtx } from '@/client/features/workspace/WorkspaceLayoutContext'
8
8
  import {
9
9
  useCreateViewBuilder,
@@ -17,7 +17,7 @@ export function useViewBuilderActions() {
17
17
  const queryClient = useQueryClient()
18
18
  const { workspaceId, layout } = useWorkspaceLayoutCtx()
19
19
  const [, selectSession] = useSelectedSession()
20
- const modelData = useWorkspaceModels(workspaceId).data
20
+ const modelData = useWorkspaceAgent(workspaceId).data
21
21
  const createMutation = useCreateViewBuilder(workspaceId)
22
22
  const saveMutation = useSaveViewBuilder(workspaceId)
23
23
  const submitMutation = useSubmitViewBuilder(workspaceId)