moi-computer 0.3.0 → 0.3.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 (121) hide show
  1. package/client/api/workspace-keys.ts +2 -2
  2. package/client/app/AppRouter.tsx +0 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +3 -1
  4. package/client/app/shell/SidebarLayout.tsx +3 -16
  5. package/client/assets/openai.svg +1 -3
  6. package/client/components/shared/Composer.tsx +112 -0
  7. package/client/components/ui/button.tsx +1 -1
  8. package/client/components/ui/dropdown-menu.tsx +3 -3
  9. package/client/components/ui/tooltip.tsx +12 -15
  10. package/client/features/applets/WidgetErrorBoundary.tsx +19 -3
  11. package/client/features/applets/WidgetShell.tsx +8 -1
  12. package/client/features/applets/applet-log.ts +100 -0
  13. package/client/features/applets/useApplet.ts +21 -7
  14. package/client/features/chat/ChatComposer.tsx +33 -30
  15. package/client/features/chat/ChatPanel.tsx +5 -2
  16. package/client/features/chat/MarkdownContent.tsx +20 -2
  17. package/client/features/chat/ModelPicker.tsx +29 -41
  18. package/client/features/chat/TurnView.tsx +2 -2
  19. package/client/features/chat/chat-frames.ts +14 -6
  20. package/client/features/chat/chat-send.ts +1 -1
  21. package/client/features/chat/chat-store.ts +22 -17
  22. package/client/features/chat/model-order.ts +47 -0
  23. package/client/features/chat/tool-group/ToolOutput.tsx +4 -12
  24. package/client/features/chat/tool-group/format.ts +0 -6
  25. package/client/features/chat/useChat.ts +15 -2
  26. package/client/features/connectors/McpServerCards.tsx +95 -0
  27. package/client/features/connectors/api.ts +0 -11
  28. package/client/features/home/HomePage.tsx +45 -42
  29. package/client/features/home/WorkspacePreview.tsx +179 -38
  30. package/client/features/home/api.ts +24 -12
  31. package/client/features/home/workspace-presentation.tsx +17 -15
  32. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +243 -0
  33. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +95 -0
  34. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +230 -0
  35. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +35 -0
  36. package/client/features/home/workspace-setup/useWorkspaceImport.ts +61 -0
  37. package/client/features/settings/ConnectorsSettings.tsx +89 -0
  38. package/client/features/settings/GeneralSettings.tsx +12 -0
  39. package/client/features/settings/SettingsLayout.tsx +2 -2
  40. package/client/features/settings/WorkspaceSettings.tsx +8 -4
  41. package/client/features/views/ViewBuilderTab.tsx +28 -29
  42. package/client/features/views/useViewBuilderActions.ts +1 -1
  43. package/client/features/widgets/WidgetFrame.tsx +3 -0
  44. package/client/features/widgets/WidgetGrid.tsx +1 -0
  45. package/client/features/widgets/Widgets.tsx +12 -3
  46. package/client/features/widgets/api.ts +47 -0
  47. package/client/features/widgets/useWidgetThumbnails.ts +107 -0
  48. package/client/features/widgets/widget-snapshot.ts +71 -0
  49. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -4
  50. package/client/features/workspace/WorkspaceScreen.tsx +19 -4
  51. package/client/features/workspace/api.ts +25 -3
  52. package/client/features/workspace/moi-context.ts +85 -0
  53. package/client/index.css +0 -5
  54. package/client/main.tsx +13 -4
  55. package/dist/{chunk-cs8vbert.js → chunk-1dfbr7n2.js} +2 -2
  56. package/dist/chunk-339jds4x.js +15 -0
  57. package/dist/chunk-3xsvsnhr.css +1 -0
  58. package/dist/{chunk-zpxrb1ce.js → chunk-anqmsbjt.js} +2 -2
  59. package/dist/chunk-hbvfb6sk.js +63 -0
  60. package/dist/chunk-jen6xcm1.js +14 -0
  61. package/dist/{chunk-kxmvv1ax.js → chunk-qwm5f6qk.js} +1 -1
  62. package/dist/{chunk-fjksw6xf.js → chunk-sxbfh73c.js} +1 -1
  63. package/dist/chunk-yp4srgqt.js +10 -0
  64. package/dist/index.html +1 -1
  65. package/dist/openai-ep9ht2pq.svg +1 -0
  66. package/lib/ids.ts +15 -0
  67. package/lib/moi-context.ts +170 -0
  68. package/lib/types.ts +95 -13
  69. package/lib/view-builder-directives.ts +16 -0
  70. package/lib/workspace-types.ts +12 -0
  71. package/package.json +4 -2
  72. package/server/api.ts +180 -34
  73. package/server/applet-log.ts +149 -0
  74. package/server/cli.ts +161 -7
  75. package/server/control.ts +81 -1
  76. package/server/functions.ts +44 -14
  77. package/server/harness/README.md +26 -9
  78. package/server/harness/claude-code/NOTES.md +20 -6
  79. package/server/harness/claude-code/adapter.ts +2 -2
  80. package/server/harness/claude-code/git-worktree.ts +32 -0
  81. package/server/harness/claude-code/index.ts +35 -13
  82. package/server/harness/claude-code/mcp.ts +16 -65
  83. package/server/harness/claude-code/models.ts +3 -0
  84. package/server/harness/claude-code/session.ts +196 -61
  85. package/server/harness/claude-code/sessions.ts +51 -0
  86. package/server/harness/codex/NOTES.md +41 -11
  87. package/server/harness/codex/adapter.ts +52 -6
  88. package/server/harness/codex/client.ts +69 -18
  89. package/server/harness/codex/discovery.ts +114 -0
  90. package/server/harness/codex/index.ts +12 -5
  91. package/server/harness/codex/probe.ts +4 -2
  92. package/server/harness/codex/session.ts +57 -5
  93. package/server/harness/executable.ts +82 -0
  94. package/server/harness/openclaw/adapter.ts +8 -1
  95. package/server/harness/openclaw/discovery.ts +139 -6
  96. package/server/harness/openclaw/gateway.ts +40 -18
  97. package/server/harness/openclaw/index.ts +12 -15
  98. package/server/harness/openclaw/session.ts +50 -10
  99. package/server/harness/openclaw/strip.ts +2 -2
  100. package/server/harness/shell-path.ts +79 -0
  101. package/server/harness/types.ts +37 -5
  102. package/server/layout.ts +81 -51
  103. package/server/registry.ts +57 -12
  104. package/server/scratchpad-assets.ts +41 -6
  105. package/server/scratchpad.ts +30 -0
  106. package/server/view-builders.ts +3 -2
  107. package/server/views.ts +5 -0
  108. package/server/web.ts +30 -8
  109. package/server/widgets.ts +23 -2
  110. package/server/workspace-import.ts +45 -0
  111. package/workspace/.claude/skills/moi-workspace/SKILL.md +27 -3
  112. package/client/features/connectors/ConnectorsPage.tsx +0 -92
  113. package/client/features/connectors/McpMenu.tsx +0 -145
  114. package/client/features/home/CreateWorkspaceDialog.tsx +0 -130
  115. package/client/features/home/CreateWorkspaceDialogSteps.tsx +0 -234
  116. package/dist/chunk-4vf1t6v1.js +0 -10
  117. package/dist/chunk-4z52b2av.css +0 -1
  118. package/dist/chunk-b4b276wx.js +0 -15
  119. package/dist/chunk-y82s1jxm.js +0 -61
  120. package/dist/openai-h13pza4b.svg +0 -3
  121. package/lib/view-builder-meta.ts +0 -35
@@ -0,0 +1,61 @@
1
+ import { useState } from 'react'
2
+
3
+ import { useImportWorkspace } from '../api'
4
+ import { WORKSPACE_TYPE_ORDER } from '@/lib/workspace-types'
5
+ import type { DiscoveredWorkspace, WorkspaceEntry, WorkspaceType } from '@/lib/types'
6
+
7
+ export function workspaceImportDefaultType(workspace: DiscoveredWorkspace): WorkspaceType {
8
+ return workspace.types[0] ?? WORKSPACE_TYPE_ORDER[0]
9
+ }
10
+
11
+ type UseWorkspaceImportProps = {
12
+ onSuccess: (entry: WorkspaceEntry) => void
13
+ }
14
+
15
+ export type WorkspaceImportChoice = {
16
+ workspace: DiscoveredWorkspace
17
+ selectedType: WorkspaceType
18
+ }
19
+
20
+ export function useWorkspaceImport({ onSuccess }: UseWorkspaceImportProps) {
21
+ const mutation = useImportWorkspace()
22
+ const [choice, setChoice] = useState<WorkspaceImportChoice | null>(null)
23
+
24
+ function startImport(workspace: DiscoveredWorkspace) {
25
+ mutation.reset()
26
+ setChoice({
27
+ workspace,
28
+ selectedType: workspaceImportDefaultType(workspace)
29
+ })
30
+ }
31
+
32
+ function selectType(type: WorkspaceType) {
33
+ setChoice(current => (current ? { ...current, selectedType: type } : current))
34
+ }
35
+
36
+ function submit() {
37
+ if (!choice || mutation.isPending) return
38
+ mutation.mutate(
39
+ {
40
+ path: choice.workspace.path,
41
+ type: choice.selectedType
42
+ },
43
+ { onSuccess }
44
+ )
45
+ }
46
+
47
+ function reset() {
48
+ setChoice(null)
49
+ mutation.reset()
50
+ }
51
+
52
+ return {
53
+ choice,
54
+ isPending: mutation.isPending,
55
+ error: mutation.error,
56
+ startImport,
57
+ selectType,
58
+ submit,
59
+ reset
60
+ }
61
+ }
@@ -0,0 +1,89 @@
1
+ import type { ReactNode } from 'react'
2
+
3
+ import { IconPlugConnected } from '@tabler/icons-react'
4
+
5
+ import { Button } from '@/client/components/ui/button'
6
+ import {
7
+ McpServerCard,
8
+ McpServerCardSkeleton,
9
+ McpServerGrid,
10
+ sortMcpServers
11
+ } from '@/client/features/connectors/McpServerCards'
12
+ import { useWorkspaceMcp } from '@/client/features/connectors/api'
13
+ import { useWorkspaceLayoutCtx } from '@/client/features/workspace/WorkspaceLayoutContext'
14
+
15
+ import { SettingsPage } from './SettingsLayout'
16
+
17
+ const CONNECTOR_SKELETONS = Array.from({ length: 4 }, (_, index) => index)
18
+
19
+ type ConnectorsContentProps = {
20
+ connectors: ReturnType<typeof useWorkspaceMcp>
21
+ }
22
+
23
+ function ConnectorsContent({ connectors }: ConnectorsContentProps) {
24
+ if (connectors.isPending) {
25
+ return (
26
+ <div role="status" aria-label="Loading connectors">
27
+ <McpServerGrid>
28
+ {CONNECTOR_SKELETONS.map(index => (
29
+ <McpServerCardSkeleton key={index} />
30
+ ))}
31
+ </McpServerGrid>
32
+ </div>
33
+ )
34
+ }
35
+
36
+ if (connectors.isError) {
37
+ return (
38
+ <ConnectorsState>
39
+ <p className="text-sm text-muted-foreground">Could not load connectors.</p>
40
+ <Button variant="outline" size="sm" onClick={() => connectors.refetch()}>
41
+ Retry
42
+ </Button>
43
+ </ConnectorsState>
44
+ )
45
+ }
46
+
47
+ if (connectors.data.length === 0) {
48
+ return (
49
+ <ConnectorsState>
50
+ <IconPlugConnected size={24} stroke={1.5} className="text-muted-foreground" />
51
+ <p className="text-sm text-foreground">No connectors configured.</p>
52
+ </ConnectorsState>
53
+ )
54
+ }
55
+
56
+ return (
57
+ <McpServerGrid>
58
+ {sortMcpServers(connectors.data).map(connector => (
59
+ <McpServerCard key={connector.name} server={connector} />
60
+ ))}
61
+ </McpServerGrid>
62
+ )
63
+ }
64
+
65
+ type ConnectorsStateProps = {
66
+ children: ReactNode
67
+ }
68
+
69
+ function ConnectorsState({ children }: ConnectorsStateProps) {
70
+ return (
71
+ <div className="flex min-h-48 flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-border px-8 py-12 text-center">
72
+ {children}
73
+ </div>
74
+ )
75
+ }
76
+
77
+ export function ConnectorsSettings() {
78
+ const { workspaceId } = useWorkspaceLayoutCtx()
79
+ const connectors = useWorkspaceMcp(workspaceId, true)
80
+
81
+ return (
82
+ <SettingsPage
83
+ title="Connectors"
84
+ description="Connectors available to the agent in this workspace."
85
+ >
86
+ <ConnectorsContent connectors={connectors} />
87
+ </SettingsPage>
88
+ )
89
+ }
@@ -51,6 +51,18 @@ export function GeneralSettings() {
51
51
  />
52
52
  }
53
53
  />
54
+ <SettingsRow
55
+ title="Path"
56
+ control={
57
+ <Input
58
+ value={cwd ?? ''}
59
+ readOnly
60
+ aria-label="Workspace path"
61
+ title={cwd ?? undefined}
62
+ className="w-56"
63
+ />
64
+ }
65
+ />
54
66
  <div className="flex flex-col gap-4 px-3.5 py-3.5">
55
67
  <div className="flex flex-col">
56
68
  <span className="text-sm font-medium">Icon</span>
@@ -9,8 +9,8 @@ type SettingsPageProps = {
9
9
  export function SettingsPage({ title, description, children }: SettingsPageProps) {
10
10
  return (
11
11
  <div className="flex flex-col gap-6">
12
- <header className="flex flex-col gap-1">
13
- <h2 className="text-xl font-semibold tracking-tight">{title}</h2>
12
+ <header className="flex flex-col gap-0.5">
13
+ <h2 className="text-lg font-medium tracking-tight">{title}</h2>
14
14
  {description && <p className="text-sm text-muted-foreground">{description}</p>}
15
15
  </header>
16
16
  {children}
@@ -1,18 +1,20 @@
1
1
  import { useState } from 'react'
2
2
 
3
- import { IconKey, IconSettings, IconX } from '@tabler/icons-react'
3
+ import { IconKey, IconPlugConnected, IconSettings, IconX } from '@tabler/icons-react'
4
4
 
5
5
  import { Button } from '@/client/components/ui/button'
6
6
  import { Dialog, DialogClose, DialogContent, DialogTitle } from '@/client/components/ui/dialog'
7
7
  import { Tooltip, TooltipContent, TooltipTrigger } from '@/client/components/ui/tooltip'
8
8
 
9
+ import { ConnectorsSettings } from './ConnectorsSettings'
9
10
  import { EnvironmentSettings } from './EnvironmentSettings'
10
11
  import { GeneralSettings } from './GeneralSettings'
11
12
 
12
- type SettingsNav = 'general' | 'environment'
13
+ type SettingsNav = 'general' | 'connectors' | 'environment'
13
14
 
14
15
  const NAV: { id: SettingsNav; label: string; icon: typeof IconSettings }[] = [
15
16
  { id: 'general', label: 'General', icon: IconSettings },
17
+ { id: 'connectors', label: 'Connectors', icon: IconPlugConnected },
16
18
  { id: 'environment', label: 'Environment', icon: IconKey }
17
19
  ]
18
20
 
@@ -22,7 +24,7 @@ export function WorkspaceSettings() {
22
24
 
23
25
  return (
24
26
  <>
25
- <Tooltip delay={50}>
27
+ <Tooltip>
26
28
  <TooltipTrigger
27
29
  render={
28
30
  <Button
@@ -78,7 +80,9 @@ export function WorkspaceSettings() {
78
80
  }
79
81
  />
80
82
  <div className="px-8 py-7">
81
- {page === 'general' ? <GeneralSettings /> : <EnvironmentSettings />}
83
+ {page === 'general' && <GeneralSettings />}
84
+ {page === 'connectors' && <ConnectorsSettings />}
85
+ {page === 'environment' && <EnvironmentSettings />}
82
86
  </div>
83
87
  </div>
84
88
  </DialogContent>
@@ -1,12 +1,21 @@
1
1
  import { type FormEvent, type KeyboardEvent, useEffect, useRef, useState } from 'react'
2
2
 
3
- import { IconArrowUp, IconLoader2 } from '@tabler/icons-react'
3
+ import { IconLoader2 } from '@tabler/icons-react'
4
4
 
5
5
  import { Button } from '@/client/components/ui/button'
6
+ import {
7
+ canSubmitComposerAction,
8
+ Composer,
9
+ ComposerFooter,
10
+ ComposerSubmitButton,
11
+ ComposerTextarea
12
+ } from '@/client/components/shared/Composer'
13
+ import { ModelPicker } from '@/client/features/chat/ModelPicker'
6
14
  import type { ViewBuilder } from '@/lib/types'
7
15
 
8
16
  type ViewBuilderTabProps = {
9
17
  builder: ViewBuilder
18
+ unavailableReason: string | null | undefined
10
19
  onSave: (requirements: string) => Promise<unknown>
11
20
  onSubmit: (requirements: string) => Promise<unknown>
12
21
  onOpenChat: () => void
@@ -15,6 +24,7 @@ type ViewBuilderTabProps = {
15
24
 
16
25
  export function ViewBuilderTab({
17
26
  builder,
27
+ unavailableReason,
18
28
  onSave,
19
29
  onSubmit,
20
30
  onOpenChat,
@@ -26,6 +36,8 @@ export function ViewBuilderTab({
26
36
  const composerRef = useRef<HTMLTextAreaElement>(null)
27
37
  const onSaveRef = useRef(onSave)
28
38
  onSaveRef.current = onSave
39
+ const hasRequirements = requirements.trim().length > 0
40
+ const canSubmit = canSubmitComposerAction(hasRequirements, submitting, unavailableReason)
29
41
 
30
42
  useEffect(() => {
31
43
  if (builder.status !== 'draft' || requirements === builder.input.requirements) return
@@ -42,7 +54,7 @@ export function ViewBuilderTab({
42
54
 
43
55
  const submit = async (event: FormEvent) => {
44
56
  event.preventDefault()
45
- if (!requirements.trim() || submitting) return
57
+ if (!canSubmit) return
46
58
  setSubmitting(true)
47
59
  try {
48
60
  await onSubmit(requirements)
@@ -62,20 +74,12 @@ export function ViewBuilderTab({
62
74
  Describe the content, data, and actions you need.
63
75
  </p>
64
76
  </div>
65
- <form
66
- onSubmit={submit}
67
- onMouseDown={event => {
68
- if (event.target instanceof HTMLElement && event.target.closest('button')) return
69
- event.preventDefault()
70
- composerRef.current?.focus()
71
- }}
72
- className="flex w-full cursor-text flex-col gap-1 rounded-lg bg-card p-2 text-card-foreground shadow-xs transition-[color,box-shadow] outline-none focus-within:shadow-sm"
73
- >
77
+ <Composer composerRef={composerRef} onSubmit={submit}>
74
78
  <label className="sr-only" htmlFor={`view-builder-${builder.id}`}>
75
79
  View requirements
76
80
  </label>
77
- <textarea
78
- ref={composerRef}
81
+ <ComposerTextarea
82
+ textareaRef={composerRef}
79
83
  id={`view-builder-${builder.id}`}
80
84
  value={requirements}
81
85
  onChange={event => setRequirements(event.target.value)}
@@ -87,26 +91,21 @@ export function ViewBuilderTab({
87
91
  }}
88
92
  placeholder="Build a customer dashboard with…"
89
93
  rows={1}
90
- className="field-sizing-content max-h-40 min-h-16 w-full resize-none bg-transparent px-2 py-1 text-sm leading-relaxed outline-none placeholder:text-muted-foreground disabled:opacity-50"
94
+ className="min-h-16"
91
95
  aria-describedby={saveError ? `view-builder-error-${builder.id}` : undefined}
92
96
  aria-invalid={Boolean(saveError)}
93
97
  autoFocus
94
98
  />
95
- <div className="flex items-center justify-end gap-1.5">
96
- <Button
97
- type="submit"
98
- size="icon"
99
- disabled={!requirements.trim() || submitting}
100
- aria-label="Build view"
101
- >
102
- {submitting ? (
103
- <IconLoader2 stroke={1.5} className="animate-spin" />
104
- ) : (
105
- <IconArrowUp stroke={1.5} />
106
- )}
107
- </Button>
108
- </div>
109
- </form>
99
+ <ComposerFooter>
100
+ <ModelPicker scope="workspace" />
101
+ <ComposerSubmitButton
102
+ label="Build view"
103
+ hasContent={hasRequirements}
104
+ loading={submitting}
105
+ unavailableReason={unavailableReason}
106
+ />
107
+ </ComposerFooter>
108
+ </Composer>
110
109
  {saveError && (
111
110
  <p
112
111
  id={`view-builder-error-${builder.id}`}
@@ -54,7 +54,7 @@ export function useViewBuilderActions() {
54
54
  stream
55
55
  })
56
56
  } catch (error) {
57
- liveStore.getState().setProcessing(workspaceId, builder.sessionId, false)
57
+ liveStore.getState().setActivity(workspaceId, builder.sessionId, 'idle')
58
58
  liveStore
59
59
  .getState()
60
60
  .setError(
@@ -32,6 +32,9 @@ export function WidgetFrame({ editing, hidden, onRemove, children }: WidgetFrame
32
32
  className="group/widget relative size-full"
33
33
  >
34
34
  <div
35
+ // Stable hook for widget snapshots: the capture clone overrides this
36
+ // element's chrome (radius/shadow/stroke) so thumbnails come out square.
37
+ data-widget-chrome
35
38
  className={cn(
36
39
  'dark absolute inset-0 overflow-hidden rounded-2xl [corner-shape:superellipse(1.2)]',
37
40
  // Outer drop shadow on the wrapper itself.
@@ -79,6 +79,7 @@ export function WidgetGridLayout({
79
79
  <div key={item.i}>
80
80
  <motion.div
81
81
  layoutId={item.i}
82
+ data-snapshot-widget={item.i}
82
83
  className="size-full"
83
84
  transition={{ type: 'spring', duration: 0.35, bounce: 0 }}
84
85
  >
@@ -1,4 +1,4 @@
1
- import { useCallback, useState } from 'react'
1
+ import { useCallback, useRef, useState } from 'react'
2
2
 
3
3
  import { AnimatePresence, LayoutGroup, motion } from 'motion/react'
4
4
 
@@ -15,6 +15,7 @@ import type { WidgetInfo } from '@/lib/types'
15
15
 
16
16
  import { HiddenPanel } from './HiddenPanel'
17
17
  import { WidgetGrid, WidgetGridLayout } from './WidgetGrid'
18
+ import { useWidgetThumbnails } from './useWidgetThumbnails'
18
19
 
19
20
  function renderItem(id: string) {
20
21
  return <WidgetShell name={id} />
@@ -43,7 +44,7 @@ function NoWidgetsCreated({ onCreateWidget }: NoWidgetsCreatedProps) {
43
44
  <WidgetGridLayout items={EMPTY_WIDGET_ITEMS} renderItem={renderEmptyWidget} />
44
45
  </div>
45
46
 
46
- <div className="absolute inset-0 z-1 flex items-center justify-center p-6">
47
+ <div className="absolute inset-0 flex items-center justify-center p-6">
47
48
  <div className="flex h-full w-full max-w-(--column-w) flex-col items-center justify-center gap-4 bg-radial from-background from-50% to-transparent to-75% text-center">
48
49
  <div className="flex flex-col gap-1.5">
49
50
  <h2 className="font-medium">A little empty here</h2>
@@ -181,6 +182,14 @@ export function Widgets({ onCreateWidget, editing, onEditingChange, widgets }: W
181
182
  const [panelRef, panelHeight] = usePanelHeight()
182
183
  const panelOpen = editing && hiddenItems.length > 0
183
184
 
185
+ const containerRef = useRef<HTMLDivElement>(null)
186
+ useWidgetThumbnails({
187
+ containerRef,
188
+ widgets,
189
+ visibleIds: visibleItems.map(item => item.id),
190
+ editing
191
+ })
192
+
184
193
  function hide(id: string) {
185
194
  setLayout({ widgetGrid: layout.widgetGrid.filter(g => g.i !== id) })
186
195
  }
@@ -200,7 +209,7 @@ export function Widgets({ onCreateWidget, editing, onEditingChange, widgets }: W
200
209
  // Shared working area below the header and positioning context for the
201
210
  // bottom panel. Created-widget states scroll; the initial empty state clips
202
211
  // its fixed-height skeleton grid.
203
- <div className="group/widgets relative min-h-0 flex-1">
212
+ <div ref={containerRef} className="group/widgets relative min-h-0 flex-1">
204
213
  <LayoutGroup>
205
214
  <div
206
215
  className={cn(
@@ -0,0 +1,47 @@
1
+ import { useMutation, useQueryClient } from '@tanstack/react-query'
2
+
3
+ import { jsonRequest, requestVoid } from '@/client/api/http'
4
+ import { workspaceKeys } from '@/client/api/workspace-keys'
5
+ import type { WorkspaceLayoutResponse } from '@/client/features/workspace/api'
6
+
7
+ export type SaveWidgetThumbnailsInput = {
8
+ // Fingerprint of the grid state the set was captured from — see
9
+ // widgetThumbnailsKey().
10
+ key: string
11
+ // Widget id → WebP data URL. Merged server-side, never pruned.
12
+ thumbnails: Record<string, string>
13
+ }
14
+
15
+ // Persist captured widget thumbnails. Separate from the layout PUT so grid and
16
+ // theme saves never carry the base64 map; the server merges the entries into
17
+ // `.workspace.json` (PUT /api/workspaces/:id/thumbnails).
18
+ //
19
+ // The local layout cache gets the new key in onMutate, deliberately WITHOUT a
20
+ // rollback on error: a failed save must read as fresh locally, or the capture
21
+ // hook would re-run a full pass every SETTLE_MS until the server recovers.
22
+ // Worst case the thumbnails are re-captured after a reload.
23
+ export function useSaveWidgetThumbnails(workspaceId: string) {
24
+ const queryClient = useQueryClient()
25
+ return useMutation<void, Error, SaveWidgetThumbnailsInput>({
26
+ mutationFn: ({ key, thumbnails }) =>
27
+ requestVoid(
28
+ `/api/workspaces/${workspaceId}/thumbnails`,
29
+ jsonRequest('PUT', { key, thumbnails }),
30
+ 'Failed to save thumbnails'
31
+ ),
32
+ onMutate: ({ key }) => {
33
+ // The timestamp too — without it the cached layout keeps the old age
34
+ // and the capture hook would immediately re-run the pass. The server
35
+ // stamps its own clock on disk; this local echo holds until a refetch.
36
+ queryClient.setQueryData<WorkspaceLayoutResponse>(workspaceKeys.layout(workspaceId), prev =>
37
+ prev ? { ...prev, widgetThumbnails: { key, at: new Date().toISOString() } } : prev
38
+ )
39
+ },
40
+ onSuccess: () => {
41
+ // The home card's preview is served from what this PUT just wrote; its
42
+ // query has a staleTime, so without an explicit invalidation a quick
43
+ // hop back to the home screen would keep showing the pre-capture state.
44
+ queryClient.invalidateQueries({ queryKey: workspaceKeys.preview(workspaceId) })
45
+ }
46
+ })
47
+ }
@@ -0,0 +1,107 @@
1
+ import { useEffect, useRef, useState } from 'react'
2
+
3
+ import { useWorkspaceLayoutCtx } from '@/client/features/workspace/WorkspaceLayoutContext'
4
+ import { useSaveWidgetThumbnails } from '@/client/features/widgets/api'
5
+ import {
6
+ captureWidgetThumbnail,
7
+ widgetThumbnailsKey
8
+ } from '@/client/features/widgets/widget-snapshot'
9
+ import type { RefObject } from 'react'
10
+ import type { WidgetInfo } from '@/lib/types'
11
+
12
+ // Grace period between "the grid changed" and the capture pass — lets widget
13
+ // bundles mount and their data requests land so we don't snapshot skeletons.
14
+ const SETTLE_MS = 5_000
15
+
16
+ // Age-based invalidation: bundle tags only catch CODE changes, but widget
17
+ // DATA drifts on its own (a dashboard captured in January still shows
18
+ // January). A set older than this re-captures even with a matching key.
19
+ const MAX_AGE_MS = 3 * 60 * 60 * 1000
20
+
21
+ type UseWidgetThumbnailsArgs = {
22
+ // Scope for [data-snapshot-widget] cell lookups.
23
+ containerRef: RefObject<HTMLElement | null>
24
+ // Widgets query data — supplies each widget's bundle tag.
25
+ widgets: WidgetInfo[]
26
+ // Widget ids currently on the grid.
27
+ visibleIds: string[]
28
+ // Edit mode pauses capture (cells wiggle, cards can be mid-drag).
29
+ editing: boolean
30
+ }
31
+
32
+ // Keeps the workspace's widget thumbnails fresh while the Widgets tab is open.
33
+ //
34
+ // One-number invalidation: the grid state is fingerprinted into a single key
35
+ // (visible ids + bundle tags). When the stored key differs, ALL visible
36
+ // widgets are re-captured in one pass and saved through their own endpoint
37
+ // (PUT .../thumbnails) — the layout PUT never carries the base64 map. The
38
+ // key is stamped even if some captures fail, so a broken widget can't loop
39
+ // the pass; entries merge server-side and are never pruned.
40
+ export function useWidgetThumbnails({
41
+ containerRef,
42
+ widgets,
43
+ visibleIds,
44
+ editing
45
+ }: UseWidgetThumbnailsArgs) {
46
+ const { layout, workspaceId } = useWorkspaceLayoutCtx()
47
+ const save = useSaveWidgetThumbnails(workspaceId)
48
+ // Latest `mutate` without widening the effect deps (mirrors the saveRef
49
+ // pattern in WorkspaceLayoutProvider).
50
+ const saveRef = useRef(save.mutate)
51
+ saveRef.current = save.mutate
52
+ const busyRef = useRef(false)
53
+ const [pass, setPass] = useState(0)
54
+
55
+ const key = widgetThumbnailsKey(visibleIds, widgets)
56
+ // A missing/unparsable timestamp counts as expired.
57
+ const capturedAt = Date.parse(layout.widgetThumbnails?.at ?? '')
58
+ const expired = !Number.isFinite(capturedAt) || Date.now() - capturedAt > MAX_AGE_MS
59
+ const stale = key !== '' && (key !== layout.widgetThumbnails?.key || expired)
60
+
61
+ useEffect(() => {
62
+ if (!stale || editing) return
63
+
64
+ // Hidden tab: timers are throttled and the captured frame may be stale —
65
+ // wait for visibility instead, then re-run this effect.
66
+ if (document.visibilityState !== 'visible') {
67
+ const onVisible = () => setPass(p => p + 1)
68
+ document.addEventListener('visibilitychange', onVisible, { once: true })
69
+ return () => document.removeEventListener('visibilitychange', onVisible)
70
+ }
71
+
72
+ // Set when the effect re-runs or unmounts mid-pass (grid changed, tab
73
+ // closed). A cancelled pass must not save: its captures are partial, and
74
+ // stamping `key` over them would mark the set fresh with images missing.
75
+ let cancelled = false
76
+ const timer = setTimeout(async () => {
77
+ if (busyRef.current) return
78
+ busyRef.current = true
79
+ try {
80
+ const captured: Record<string, string> = {}
81
+ for (const id of visibleIds) {
82
+ if (cancelled) return
83
+ const cell = containerRef.current?.querySelector<HTMLElement>(
84
+ `[data-snapshot-widget="${CSS.escape(id)}"]`
85
+ )
86
+ const image = cell ? await captureWidgetThumbnail(cell) : null
87
+ if (image) captured[id] = image
88
+ }
89
+ if (cancelled) return
90
+ // The mutation's onMutate stamps the key into the local layout cache;
91
+ // the PUT itself is best-effort (a failed save just means a
92
+ // re-capture after reload).
93
+ saveRef.current({ key, thumbnails: captured })
94
+ } finally {
95
+ busyRef.current = false
96
+ // Re-evaluate: a pass skipped on `busy`, or a key that moved while
97
+ // this pass ran, gets picked up next round; a fresh key is a no-op.
98
+ setPass(p => p + 1)
99
+ }
100
+ }, SETTLE_MS)
101
+ return () => {
102
+ cancelled = true
103
+ clearTimeout(timer)
104
+ }
105
+ // eslint-disable-next-line react-hooks/exhaustive-deps
106
+ }, [key, stale, editing, pass])
107
+ }
@@ -0,0 +1,71 @@
1
+ // Widget thumbnail capture: renders one live grid cell (tagged with
2
+ // `data-snapshot-widget` in WidgetGrid) to a WebP data URL via
3
+ // modern-screenshot — white background, the widget's own aspect ratio, frame
4
+ // chrome stripped. Shared by the automatic invalidation hook
5
+ // (useWidgetThumbnails).
6
+ import type { WidgetInfo } from '@/lib/types'
7
+
8
+ // Long edge of a stored thumbnail, in output px. Placeholder until the real
9
+ // target resolution is decided.
10
+ export const THUMB_MAX_EDGE = 400
11
+
12
+ // How long modern-screenshot waits per image/asset before rendering without
13
+ // it. The library default is 30s, which reads as a hang on any widget whose
14
+ // image never loads (lazy-loaded offscreen, CORS-blocked, dead URL).
15
+ const ASSET_TIMEOUT_MS = 1_000
16
+
17
+ // Hard cap for one widget's whole capture. If it blows past this, the capture
18
+ // resolves null and the caller moves on — a snapshot pass must never wedge.
19
+ const WIDGET_TIMEOUT_MS = 10_000
20
+
21
+ export const thumbnailScale = (cell: HTMLElement) =>
22
+ Math.min(1, THUMB_MAX_EDGE / Math.max(cell.offsetWidth, cell.offsetHeight))
23
+
24
+ // Fingerprint of the grid state a thumbnail set was captured from: which
25
+ // widgets are on the grid and which bundle build (`WidgetInfo.tag`) each one
26
+ // runs. Order-independent. Any change — add, remove, rebundle — changes the
27
+ // key and triggers a full re-capture.
28
+ export const widgetThumbnailsKey = (visibleIds: string[], widgets: WidgetInfo[]) => {
29
+ const tagById = new Map(widgets.map(w => [w.id, w.tag]))
30
+ return [...visibleIds]
31
+ .sort()
32
+ .map(id => `${id}@${tagById.get(id) ?? ''}`)
33
+ .join(' ')
34
+ }
35
+
36
+ const timeoutNull = (ms: number) =>
37
+ new Promise<null>(resolve => {
38
+ setTimeout(() => resolve(null), ms)
39
+ })
40
+
41
+ export async function captureWidgetThumbnail(cell: HTMLElement): Promise<string | null> {
42
+ const { createContext, destroyContext, domToDataUrl } = await import('modern-screenshot')
43
+
44
+ const run = async () => {
45
+ const context = await createContext(cell, {
46
+ scale: thumbnailScale(cell),
47
+ type: 'image/webp',
48
+ quality: 0.8,
49
+ backgroundColor: '#ffffff',
50
+ timeout: ASSET_TIMEOUT_MS,
51
+ // Strip the frame chrome inside the capture only. Computed styles are
52
+ // inlined onto the clone, so a wrapper selector can't reach them — but a
53
+ // stylesheet injected into the generated SVG can: !important rules beat
54
+ // inline styles and the copied ::after.
55
+ onCreateForeignObjectSvg: svg => {
56
+ const style = document.createElement('style')
57
+ style.textContent =
58
+ '[data-widget-chrome] { border-radius: 0 !important; box-shadow: none !important; }' +
59
+ '[data-widget-chrome]::after { display: none !important; }'
60
+ svg.append(style)
61
+ }
62
+ })
63
+ try {
64
+ return await domToDataUrl(context)
65
+ } finally {
66
+ destroyContext(context)
67
+ }
68
+ }
69
+
70
+ return Promise.race([run(), timeoutNull(WIDGET_TIMEOUT_MS)])
71
+ }
@@ -23,10 +23,9 @@ type WorkspaceLayoutContextValue = {
23
23
  // Custom workspace icon (base64 data URL), or null to use the provider icon.
24
24
  icon: string | null
25
25
  cwd: string | null
26
- // The agent backend (claude-code / openclaw …). Exposed here so
27
- // components like McpMenu read it from the shared layout query instead of
28
- // spawning their own observer (a second observer that remounts would trigger
29
- // `refetchOnMount` and clobber an in-flight optimistic layout update).
26
+ // The agent backend (claude-code / openclaw …). Exposed here so descendants
27
+ // can reuse the shared layout query instead of spawning another observer
28
+ // that could refetch on mount and clobber an optimistic layout update.
30
29
  provider: WorkspaceType | null
31
30
  // The workspace's registry id (the route param), so descendants can key
32
31
  // their own queries (e.g. the model picker) without prop-drilling.