moi-computer 0.3.0-next.3 → 0.3.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 (58) hide show
  1. package/client/app/routes/WorkspaceRoute.tsx +3 -1
  2. package/client/components/shared/Composer.tsx +61 -0
  3. package/client/components/ui/dropdown-menu.tsx +3 -3
  4. package/client/features/applets/WidgetErrorBoundary.tsx +19 -3
  5. package/client/features/applets/WidgetShell.tsx +8 -1
  6. package/client/features/applets/applet-log.ts +100 -0
  7. package/client/features/applets/useApplet.ts +21 -7
  8. package/client/features/chat/ChatComposer.tsx +9 -16
  9. package/client/features/chat/ModelPicker.tsx +26 -40
  10. package/client/features/chat/chat-frames.ts +1 -0
  11. package/client/features/chat/model-order.ts +47 -0
  12. package/client/features/chat/useChat.ts +4 -0
  13. package/client/features/home/HomePage.tsx +13 -15
  14. package/client/features/home/WorkspacePreview.tsx +179 -31
  15. package/client/features/settings/GeneralSettings.tsx +12 -0
  16. package/client/features/views/ViewBuilderTab.tsx +10 -15
  17. package/client/features/widgets/WidgetFrame.tsx +3 -0
  18. package/client/features/widgets/WidgetGrid.tsx +1 -0
  19. package/client/features/widgets/Widgets.tsx +12 -3
  20. package/client/features/widgets/api.ts +47 -0
  21. package/client/features/widgets/useWidgetThumbnails.ts +107 -0
  22. package/client/features/widgets/widget-snapshot.ts +71 -0
  23. package/client/features/workspace/WorkspaceScreen.tsx +8 -1
  24. package/client/features/workspace/api.ts +6 -2
  25. package/client/index.css +0 -5
  26. package/client/main.tsx +6 -0
  27. package/dist/{chunk-rq0ar7vp.js → chunk-axszxe4c.js} +1 -1
  28. package/dist/chunk-b3ynfk4g.js +62 -0
  29. package/dist/chunk-jen6xcm1.js +14 -0
  30. package/dist/chunk-npwq6jmr.css +1 -0
  31. package/dist/index.html +1 -1
  32. package/lib/types.ts +66 -2
  33. package/package.json +3 -2
  34. package/server/api.ts +87 -3
  35. package/server/applet-log.ts +149 -0
  36. package/server/cli.ts +161 -7
  37. package/server/control.ts +81 -1
  38. package/server/functions.ts +44 -14
  39. package/server/harness/README.md +1 -0
  40. package/server/harness/claude-code/index.ts +3 -1
  41. package/server/harness/claude-code/sessions.ts +51 -0
  42. package/server/harness/codex/NOTES.md +88 -1
  43. package/server/harness/codex/adapter.ts +32 -0
  44. package/server/harness/codex/client.ts +36 -1
  45. package/server/harness/codex/index.ts +3 -0
  46. package/server/harness/openclaw/discovery.ts +139 -6
  47. package/server/harness/openclaw/gateway.ts +40 -18
  48. package/server/harness/openclaw/index.ts +4 -1
  49. package/server/harness/types.ts +15 -0
  50. package/server/layout.ts +81 -51
  51. package/server/scratchpad-assets.ts +41 -6
  52. package/server/scratchpad.ts +30 -0
  53. package/server/views.ts +5 -0
  54. package/server/web.ts +6 -0
  55. package/server/widgets.ts +23 -2
  56. package/workspace/.claude/skills/moi-workspace/SKILL.md +25 -1
  57. package/dist/chunk-6c24yndg.js +0 -61
  58. package/dist/chunk-cwqmay73.css +0 -1
@@ -1,7 +1,7 @@
1
1
  import { IconChevronRight, IconEggCracked, IconLoader2, IconPlus } from '@tabler/icons-react'
2
2
  import { Link, useLocation } from 'wouter'
3
3
 
4
- import { useAddWorkspace, useDiscoveredWorkspaces, useWorkspaces } from './api'
4
+ import { useAddWorkspace, useDiscoveredWorkspaces, useWorkspacePreview, useWorkspaces } from './api'
5
5
  import { HomeLogo } from './HomeLogo'
6
6
  import { Button } from '@/client/components/ui/button'
7
7
  import {
@@ -147,7 +147,8 @@ type WorkspaceCardProps = {
147
147
 
148
148
  function WorkspaceCard({ workspace }: WorkspaceCardProps) {
149
149
  const name = workspaceDisplayName(workspace)
150
- const meta = formatAddedAt(workspace.addedAt)
150
+ const previewQuery = useWorkspacePreview(workspace.id)
151
+ const updatedAt = previewQuery.data?.updatedAt ?? new Date(workspace.addedAt).getTime()
151
152
 
152
153
  return (
153
154
  <Link
@@ -155,8 +156,8 @@ function WorkspaceCard({ workspace }: WorkspaceCardProps) {
155
156
  className="group flex min-w-0 flex-col gap-4 rounded-xl bg-card p-2 shadow-xs transition-shadow hover:shadow-sm"
156
157
  >
157
158
  <WorkspacePreview workspaceId={workspace.id} />
158
- <div className="flex min-w-0 flex-col px-2 pb-2">
159
- <div className="flex min-w-0 items-center gap-2">
159
+ <div className="flex min-w-0 flex-col gap-2 px-2 pb-2">
160
+ <div className="flex min-w-0 items-center gap-1.5">
160
161
  <img
161
162
  src={workspace.icon ?? workspaceProviderIcon[workspace.type ?? 'claude-code']}
162
163
  alt=""
@@ -164,10 +165,7 @@ function WorkspaceCard({ workspace }: WorkspaceCardProps) {
164
165
  />
165
166
  <span className="truncate text-sm font-medium text-foreground">{name}</span>
166
167
  </div>
167
- <div title={workspace.path} className="mt-2 truncate text-xs text-muted-foreground">
168
- {workspace.displayPath ?? workspace.path}
169
- </div>
170
- <div className="mt-2 text-xs text-muted-foreground">{meta}</div>
168
+ <span className="text-xs text-muted-foreground">{formatUpdatedAt(updatedAt)}</span>
171
169
  </div>
172
170
  </Link>
173
171
  )
@@ -201,14 +199,14 @@ function SuggestedRow({ suggestion, onAdd, loading }: SuggestedRowProps) {
201
199
  )
202
200
  }
203
201
 
204
- function formatAddedAt(iso: string): string {
205
- const ms = Date.now() - new Date(iso).getTime()
202
+ function formatUpdatedAt(timestamp: number): string {
203
+ const ms = Date.now() - timestamp
206
204
  const mins = Math.floor(ms / 60000)
207
- if (mins < 1) return 'Added just now'
208
- if (mins < 60) return `Added ${mins} min${mins === 1 ? '' : 's'} ago`
205
+ if (mins < 1) return 'Updated just now'
206
+ if (mins < 60) return `Updated ${mins} min${mins === 1 ? '' : 's'} ago`
209
207
  const hours = Math.floor(mins / 60)
210
- if (hours < 24) return `Added ${hours} hour${hours === 1 ? '' : 's'} ago`
208
+ if (hours < 24) return `Updated ${hours} hour${hours === 1 ? '' : 's'} ago`
211
209
  const days = Math.floor(hours / 24)
212
- if (days < 30) return `Added ${days} day${days === 1 ? '' : 's'} ago`
213
- return `Added ${new Date(iso).toLocaleDateString()}`
210
+ if (days < 30) return `Updated ${days} day${days === 1 ? '' : 's'} ago`
211
+ return `Updated ${new Date(timestamp).toLocaleDateString()}`
214
212
  }
@@ -1,4 +1,6 @@
1
- import { IconGhost } from '@tabler/icons-react'
1
+ import { useLayoutEffect, useRef, useState } from 'react'
2
+
3
+ import { cn } from '@/client/lib/cn'
2
4
 
3
5
  import { useWorkspacePreview } from './api'
4
6
 
@@ -6,43 +8,189 @@ type WorkspacePreviewProps = {
6
8
  workspaceId: string
7
9
  }
8
10
 
11
+ const FOLDER = {
12
+ width: 320,
13
+ height: 160,
14
+ radius: 24,
15
+ topLeftRadius: 12,
16
+ bodyTop: 24,
17
+ tabEnd: 124,
18
+ shoulder: {
19
+ width: 48,
20
+ roundness: 20
21
+ }
22
+ } as const
23
+
24
+ function folderBackdropPath(horizontalRadiusScale: number): string {
25
+ const {
26
+ width,
27
+ height,
28
+ radius: radiusY,
29
+ topLeftRadius: topLeftRadiusY,
30
+ bodyTop,
31
+ tabEnd,
32
+ shoulder
33
+ } = FOLDER
34
+ const radiusX = Math.min(width / 2, radiusY * horizontalRadiusScale)
35
+ const topLeftRadiusX = Math.min(width / 2, topLeftRadiusY * horizontalRadiusScale)
36
+ const shoulderWidth = Math.max(0, shoulder.width)
37
+ const bodyStart = tabEnd + shoulderWidth
38
+ const roundness = Math.max(0, Math.min(shoulder.roundness, shoulderWidth / 2))
39
+
40
+ return [
41
+ `M ${topLeftRadiusX} 0`,
42
+ `H ${tabEnd}`,
43
+ `C ${tabEnd + roundness} 0 ${bodyStart - roundness} ${bodyTop} ${bodyStart} ${bodyTop}`,
44
+ `H ${width - radiusX}`,
45
+ `Q ${width} ${bodyTop} ${width} ${bodyTop + radiusY}`,
46
+ `V ${height - radiusY}`,
47
+ `Q ${width} ${height} ${width - radiusX} ${height}`,
48
+ `H ${radiusX}`,
49
+ `Q 0 ${height} 0 ${height - radiusY}`,
50
+ `V ${topLeftRadiusY}`,
51
+ `Q 0 0 ${topLeftRadiusX} 0`,
52
+ 'Z'
53
+ ].join(' ')
54
+ }
55
+
56
+ function useFolderRadiusScale() {
57
+ const ref = useRef<HTMLDivElement>(null)
58
+ const [horizontalRadiusScale, setHorizontalRadiusScale] = useState(1)
59
+
60
+ useLayoutEffect(() => {
61
+ const element = ref.current
62
+ if (!element) return
63
+
64
+ const update = (width: number, height: number) => {
65
+ if (width <= 0 || height <= 0) return
66
+ const scaleX = width / FOLDER.width
67
+ const scaleY = height / FOLDER.height
68
+ const nextScale = scaleY / scaleX
69
+ setHorizontalRadiusScale(current =>
70
+ Math.abs(current - nextScale) < 0.001 ? current : nextScale
71
+ )
72
+ }
73
+
74
+ const bounds = element.getBoundingClientRect()
75
+ update(bounds.width, bounds.height)
76
+
77
+ const observer = new ResizeObserver(([entry]) => {
78
+ if (entry) update(entry.contentRect.width, entry.contentRect.height)
79
+ })
80
+ observer.observe(element)
81
+ return () => observer.disconnect()
82
+ }, [])
83
+
84
+ return { ref, horizontalRadiusScale }
85
+ }
86
+
87
+ // Bottom-to-top placement for up to three widget screenshots. Each card peeks
88
+ // out of the folder at a slightly different angle and lifts on card hover.
89
+ const STACK = [
90
+ cn(
91
+ 'opacity-40',
92
+ '-translate-x-3 translate-y-3 -rotate-6',
93
+ 'group-hover:translate-y-2 group-focus-visible:translate-y-2'
94
+ ),
95
+ cn(
96
+ 'opacity-50',
97
+ 'translate-x-3 translate-y-2 rotate-5',
98
+ 'group-hover:translate-y-1 group-focus-visible:translate-y-1'
99
+ ),
100
+ cn(
101
+ 'opacity-100',
102
+ '-translate-x-1 translate-y-1 -rotate-2',
103
+ 'group-hover:-translate-y-2 group-focus-visible:-translate-y-2'
104
+ )
105
+ ]
106
+
9
107
  export function WorkspacePreview({ workspaceId }: WorkspacePreviewProps) {
10
108
  const query = useWorkspacePreview(workspaceId)
11
-
12
- const items = query.data?.items ?? []
13
- const cols = query.data?.cols ?? 4
14
- const rows = items.length ? Math.max(...items.map(i => i.y + i.h)) : 0
15
- const hasItems = items.length > 0 && rows > 0
16
- const isEmpty = query.data !== undefined && !hasItems
109
+ const thumbnails = query.data ? [...query.data.thumbnails].reverse() : []
110
+ const slots = STACK.slice(STACK.length - thumbnails.length)
111
+ const firstUserMessage = query.data?.firstUserMessage
112
+ const { ref, horizontalRadiusScale } = useFolderRadiusScale()
113
+ const backdropPath = folderBackdropPath(horizontalRadiusScale)
114
+ const noiseFilterId = `folder-noise-${workspaceId}`
17
115
 
18
116
  return (
19
- <div className="flex aspect-video w-full items-center justify-center rounded-sm bg-muted p-3">
20
- {hasItems && (
21
- <svg
22
- viewBox={`0 0 ${cols} ${rows}`}
23
- preserveAspectRatio="none"
24
- className="size-full animate-in duration-300 fade-in"
25
- >
26
- {items.map((item, i) => (
27
- <rect
28
- key={i}
29
- x={item.x + 0.06}
30
- y={item.y + 0.06}
31
- width={item.w - 0.12}
32
- height={item.h - 0.12}
33
- rx={0.12}
34
- className="fill-muted-foreground/30"
117
+ <div ref={ref} className="relative h-40 w-full">
118
+ <svg
119
+ viewBox={`0 0 ${FOLDER.width} ${FOLDER.height}`}
120
+ preserveAspectRatio="none"
121
+ aria-hidden="true"
122
+ className="absolute inset-0 h-full w-full overflow-visible"
123
+ >
124
+ <defs>
125
+ <filter
126
+ id={noiseFilterId}
127
+ x="0%"
128
+ y="0%"
129
+ width="100%"
130
+ height="100%"
131
+ colorInterpolationFilters="sRGB"
132
+ >
133
+ <feTurbulence
134
+ type="fractalNoise"
135
+ baseFrequency="0.5"
136
+ numOctaves="3"
137
+ seed="7"
138
+ result="noise"
35
139
  />
36
- ))}
37
- </svg>
38
- )}
39
- {isEmpty && (
40
- <IconGhost
41
- size={20}
42
- stroke={1.5}
43
- className="animate-in text-muted-foreground/40 duration-300 fade-in"
140
+ <feColorMatrix in="noise" type="saturate" values="0" result="monochromeNoise" />
141
+ <feComponentTransfer in="monochromeNoise" result="faintNoise">
142
+ <feFuncA type="linear" slope="0.24" />
143
+ </feComponentTransfer>
144
+ <feComposite in="faintNoise" in2="SourceAlpha" operator="in" result="clippedNoise" />
145
+ <feBlend in="SourceGraphic" in2="clippedNoise" mode="soft-light" />
146
+ </filter>
147
+ </defs>
148
+ <path
149
+ d={backdropPath}
150
+ filter={`url(#${noiseFilterId})`}
151
+ className="mask-[linear-gradient(to_bottom,rgba(0,0,0,0.5),black_40%)] fill-accent"
152
+ />
153
+ </svg>
154
+
155
+ {thumbnails.map((src, index) => (
156
+ <img
157
+ key={index}
158
+ src={src}
159
+ alt=""
160
+ loading="lazy"
161
+ className={cn(
162
+ 'absolute top-[12%] left-[14%] aspect-4/3 w-[72%] rounded-sm object-cover object-top shadow-xs',
163
+ 'animate-in transition-transform duration-300 ease-out fade-in',
164
+ slots[index]
165
+ )}
44
166
  />
167
+ ))}
168
+
169
+ {thumbnails.length === 0 && firstUserMessage && (
170
+ <div className="absolute inset-x-[12%] top-[20%] flex justify-end">
171
+ <div
172
+ aria-hidden="true"
173
+ className={cn(
174
+ 'w-max max-w-40 origin-center rounded-sm bg-card px-3 py-2 shadow-xs',
175
+ 'animate-in transition-transform duration-300 ease-out fade-in',
176
+ STACK[STACK.length - 1],
177
+ 'group-hover:translate-y-0.5 group-focus-visible:translate-y-0.5'
178
+ )}
179
+ >
180
+ <p className="line-clamp-3 text-sm leading-normal whitespace-normal">
181
+ {firstUserMessage}
182
+ </p>
183
+ </div>
184
+ </div>
45
185
  )}
186
+
187
+ <div
188
+ className={cn(
189
+ 'absolute inset-x-2 top-[40%] bottom-2 rounded-lg bg-accent',
190
+ 'mask-[linear-gradient(to_bottom,rgba(0,0,0,0.9)_0%,black_50%)] backdrop-blur-lg',
191
+ 'inset-shadow-[0_0_12px_color-mix(in_oklab,var(--background)_20%,transparent)]'
192
+ )}
193
+ />
46
194
  </div>
47
195
  )
48
196
  }
@@ -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>
@@ -3,6 +3,8 @@ import { type FormEvent, type KeyboardEvent, useEffect, useRef, useState } from
3
3
  import { IconArrowUp, IconLoader2 } from '@tabler/icons-react'
4
4
 
5
5
  import { Button } from '@/client/components/ui/button'
6
+ import { Composer, ComposerFooter, ComposerTextarea } from '@/client/components/shared/Composer'
7
+ import { ModelPicker } from '@/client/features/chat/ModelPicker'
6
8
  import type { ViewBuilder } from '@/lib/types'
7
9
 
8
10
  type ViewBuilderTabProps = {
@@ -62,20 +64,12 @@ export function ViewBuilderTab({
62
64
  Describe the content, data, and actions you need.
63
65
  </p>
64
66
  </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
- >
67
+ <Composer composerRef={composerRef} onSubmit={submit}>
74
68
  <label className="sr-only" htmlFor={`view-builder-${builder.id}`}>
75
69
  View requirements
76
70
  </label>
77
- <textarea
78
- ref={composerRef}
71
+ <ComposerTextarea
72
+ textareaRef={composerRef}
79
73
  id={`view-builder-${builder.id}`}
80
74
  value={requirements}
81
75
  onChange={event => setRequirements(event.target.value)}
@@ -87,12 +81,13 @@ export function ViewBuilderTab({
87
81
  }}
88
82
  placeholder="Build a customer dashboard with…"
89
83
  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"
84
+ className="min-h-16"
91
85
  aria-describedby={saveError ? `view-builder-error-${builder.id}` : undefined}
92
86
  aria-invalid={Boolean(saveError)}
93
87
  autoFocus
94
88
  />
95
- <div className="flex items-center justify-end gap-1.5">
89
+ <ComposerFooter>
90
+ <ModelPicker scope="workspace" />
96
91
  <Button
97
92
  type="submit"
98
93
  size="icon"
@@ -105,8 +100,8 @@ export function ViewBuilderTab({
105
100
  <IconArrowUp stroke={1.5} />
106
101
  )}
107
102
  </Button>
108
- </div>
109
- </form>
103
+ </ComposerFooter>
104
+ </Composer>
110
105
  {saveError && (
111
106
  <p
112
107
  id={`view-builder-error-${builder.id}`}
@@ -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
+ }