moi-computer 0.3.0-next.1 → 0.3.0-next.2

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 (146) hide show
  1. package/bunfig.toml +5 -1
  2. package/client/AGENTS.md +15 -0
  3. package/client/accept-hmr-dependencies.ts +22 -0
  4. package/client/api/http.ts +31 -0
  5. package/client/api/query-options.ts +6 -0
  6. package/client/api/workspace-keys.ts +17 -0
  7. package/client/app/AppRouter.tsx +35 -0
  8. package/client/app/routes/HomeRoute.tsx +13 -0
  9. package/client/app/routes/WorkspaceRoute.tsx +89 -0
  10. package/client/app/shell/SidebarLayout.tsx +191 -0
  11. package/client/assets.d.ts +9 -0
  12. package/client/components/playground/PixelPainter.tsx +10 -21
  13. package/client/components/playground/PlaygroundPage.tsx +9 -11
  14. package/client/components/playground/ToolCallsPage.tsx +9 -11
  15. package/client/components/{BottomPanel.tsx → shared/BottomPanel.tsx} +1 -1
  16. package/client/components/shared/PanelHeader.tsx +9 -0
  17. package/client/components/shared/ReorderableList.tsx +199 -0
  18. package/client/components/ui/button.tsx +10 -7
  19. package/client/components/ui/collapsible.tsx +15 -0
  20. package/client/components/ui/dialog.tsx +2 -2
  21. package/client/components/ui/dropdown-menu.tsx +5 -5
  22. package/client/components/ui/hover-card.tsx +1 -1
  23. package/client/components/ui/popover.tsx +1 -1
  24. package/client/components/ui/skeleton.tsx +13 -0
  25. package/client/components/ui/tooltip.tsx +1 -1
  26. package/client/externalize-react.ts +7 -1
  27. package/client/{components → features/applets}/WidgetErrorBoundary.tsx +1 -1
  28. package/client/{components → features/applets}/WidgetShell.tsx +1 -1
  29. package/client/{hooks → features/applets}/useApplet.ts +6 -7
  30. package/client/{components/ChatInput.tsx → features/chat/ChatComposer.tsx} +29 -23
  31. package/client/features/chat/ChatPanel.tsx +188 -0
  32. package/client/{components → features/chat}/ChatPopup.tsx +23 -12
  33. package/client/{components → features/chat}/MarkdownContent.tsx +1 -1
  34. package/client/{components → features/chat}/ModelPicker.tsx +68 -17
  35. package/client/{components → features/chat}/ThreadSelector.tsx +11 -9
  36. package/client/{components → features/chat}/TurnView.tsx +16 -9
  37. package/client/features/chat/api.ts +78 -0
  38. package/client/features/chat/chat-connection.ts +107 -0
  39. package/client/features/chat/chat-frames.ts +131 -0
  40. package/client/{lib → features/chat}/preview-turn.ts +1 -1
  41. package/client/{components → features/chat}/tool-group/ReadImagePreview.tsx +1 -1
  42. package/client/{components → features/chat}/tool-group/SubagentCard.tsx +12 -10
  43. package/client/{components → features/chat}/tool-group/TimelineRow.tsx +5 -5
  44. package/client/{components → features/chat}/tool-group/ToolCallGroup.tsx +12 -4
  45. package/client/{components → features/chat}/tool-group/ToolOutput.tsx +12 -18
  46. package/client/{hooks → features/chat}/useChat.ts +7 -11
  47. package/client/features/connectors/ConnectorsPage.tsx +92 -0
  48. package/client/features/connectors/McpMenu.tsx +162 -0
  49. package/client/features/connectors/api.ts +28 -0
  50. package/client/features/home/CreateWorkspaceDialog.tsx +224 -0
  51. package/client/features/home/HomePage.tsx +220 -0
  52. package/client/{components → features/home}/WorkspacePreview.tsx +2 -2
  53. package/client/features/home/api.ts +148 -0
  54. package/client/features/home/workspace-presentation.tsx +44 -0
  55. package/client/features/scratchpad/Scratchpad.tsx +312 -0
  56. package/client/features/scratchpad/ScratchpadControls.tsx +503 -0
  57. package/client/features/scratchpad/useScratchpadSnapshot.tsx +115 -0
  58. package/client/features/settings/EnvironmentSettings.tsx +149 -0
  59. package/client/features/settings/GeneralSettings.tsx +90 -0
  60. package/client/{components → features}/settings/IconPicker.tsx +73 -222
  61. package/client/features/settings/SettingsLayout.tsx +53 -0
  62. package/client/{components → features}/settings/WorkspaceSettings.tsx +12 -16
  63. package/client/features/settings/api.ts +88 -0
  64. package/client/features/settings/icon-picker-options.ts +161 -0
  65. package/client/{hooks → features/settings}/useEnvVars.ts +4 -4
  66. package/client/{components → features/widgets}/HiddenPanel.tsx +3 -3
  67. package/client/{components → features/widgets}/WidgetFrame.tsx +3 -8
  68. package/client/{components → features/widgets}/WidgetGrid.tsx +2 -9
  69. package/client/features/widgets/Widgets.tsx +215 -0
  70. package/client/{lib/grid-pack.ts → features/widgets/grid.ts} +7 -1
  71. package/client/{hooks → features/widgets}/useGridReconcile.ts +1 -1
  72. package/client/{components → features/workspace}/CustomizePanel.tsx +5 -6
  73. package/client/{lib → features/workspace}/WorkspaceLayoutContext.tsx +15 -8
  74. package/client/features/workspace/WorkspaceScreen.tsx +536 -0
  75. package/client/features/workspace/WorkspaceTabs.tsx +205 -0
  76. package/client/features/workspace/api.ts +56 -0
  77. package/client/features/workspace/useFitsSplitLayout.ts +37 -0
  78. package/client/global.d.ts +5 -0
  79. package/client/index.css +6 -10
  80. package/client/index.html +1 -1
  81. package/client/index.tsx +14 -31
  82. package/client/main.tsx +2 -2
  83. package/client/runtime/hmr-watchdog.ts +39 -0
  84. package/client/{hooks/useMeiEvents.ts → runtime/useWorkspaceEvents.ts} +9 -6
  85. package/client/store/ui.ts +5 -1
  86. package/client/theme.css +0 -2
  87. package/dist/chunk-11cab5dq.css +1 -0
  88. package/dist/chunk-23cgr1tz.css +1 -0
  89. package/dist/chunk-3hy3qy6d.js +10 -0
  90. package/dist/chunk-c4j722at.js +546 -0
  91. package/dist/chunk-dyfaffyz.js +119 -0
  92. package/dist/chunk-kpe40hm8.js +1 -0
  93. package/dist/chunk-p68fnz3q.js +2 -0
  94. package/dist/chunk-pcnahct1.js +5 -0
  95. package/dist/chunk-tqd3pkg8.css +1 -0
  96. package/dist/chunk-ty6dvda0.js +1 -0
  97. package/dist/index.html +2 -2
  98. package/lib/types.ts +18 -7
  99. package/lib/workspace-name.ts +14 -0
  100. package/package.json +3 -2
  101. package/server/api.ts +119 -14
  102. package/server/cli.ts +11 -5
  103. package/server/layout.ts +38 -7
  104. package/server/mcp.ts +72 -15
  105. package/server/moi-scaffold.ts +55 -10
  106. package/server/registry.ts +16 -0
  107. package/server/web.ts +1 -0
  108. package/server/workspace-init.ts +5 -19
  109. package/tsconfig.json +1 -1
  110. package/workspace/.claude/skills/moi-workspace/DESIGN.md +1 -1
  111. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +1 -1
  112. package/client/api/workspaces.ts +0 -427
  113. package/client/components/App.tsx +0 -41
  114. package/client/components/ChatPanel.tsx +0 -275
  115. package/client/components/HomePage.tsx +0 -17
  116. package/client/components/McpMenu.tsx +0 -125
  117. package/client/components/Scratchpad.tsx +0 -935
  118. package/client/components/Widgets.tsx +0 -132
  119. package/client/components/WorkspacesPage.tsx +0 -245
  120. package/client/components/layout/SidebarLayout.tsx +0 -258
  121. package/client/components/routes/workspace/[id].tsx +0 -675
  122. package/client/components/routes/workspace/create.tsx +0 -155
  123. package/client/components/settings/SettingsPages.tsx +0 -255
  124. package/client/hooks/useFitsSidebar.ts +0 -34
  125. package/client/lib/connection.ts +0 -238
  126. package/dist/chunk-07qf2tv1.css +0 -1
  127. package/dist/chunk-w18801vn.js +0 -672
  128. /package/client/components/{playground → shared}/LedLogo.tsx +0 -0
  129. /package/client/{lib → features/applets}/applet-cache.ts +0 -0
  130. /package/client/{components → features/chat}/ShimmerText.tsx +0 -0
  131. /package/client/{store/live.ts → features/chat/chat-store.ts} +0 -0
  132. /package/client/{lib → features/chat}/group-turns.ts +0 -0
  133. /package/client/{components → features/chat}/tool-group/CodeBlock.tsx +0 -0
  134. /package/client/{components → features/chat}/tool-group/Collapse.tsx +0 -0
  135. /package/client/{components → features/chat}/tool-group/detect.ts +0 -0
  136. /package/client/{components → features/chat}/tool-group/fixtures.ts +0 -0
  137. /package/client/{components → features/chat}/tool-group/format.ts +0 -0
  138. /package/client/{components → features/chat}/tool-group/index.ts +0 -0
  139. /package/client/{lib → features/chat}/uploads.ts +0 -0
  140. /package/client/{hooks → features/chat}/useStickToBottom.ts +0 -0
  141. /package/client/{components → features/connectors}/IconMcp.tsx +0 -0
  142. /package/client/{lib → features/connectors}/mcp-icons.ts +0 -0
  143. /package/client/{lib → features/scratchpad}/scratch-executor.ts +0 -0
  144. /package/client/{lib → features/settings}/render-icon.ts +0 -0
  145. /package/client/{lib → features/workspace}/WorkspaceContext.tsx +0 -0
  146. /package/client/{hooks → features/workspace}/useWorkspaceTheme.ts +0 -0
@@ -0,0 +1,148 @@
1
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
2
+
3
+ import { jsonRequest, requestJson, requestVoid } from '@/client/api/http'
4
+ import { workspaceKeys } from '@/client/api/workspace-keys'
5
+ import type {
6
+ DiscoveredWorkspace,
7
+ WorkspaceEntry,
8
+ WorkspacePreview,
9
+ WorkspaceType
10
+ } from '@/lib/types'
11
+
12
+ export function upsertWorkspaceEntry(
13
+ entries: WorkspaceEntry[] | undefined,
14
+ entry: WorkspaceEntry
15
+ ): WorkspaceEntry[] {
16
+ const current = entries ?? []
17
+ const existing = current.findIndex(item => item.id === entry.id || item.path === entry.path)
18
+ if (existing === -1) return [...current, entry]
19
+ return current.map((item, index) => (index === existing ? { ...item, ...entry } : item))
20
+ }
21
+
22
+ export function useWorkspaces() {
23
+ return useQuery<WorkspaceEntry[]>({
24
+ queryKey: workspaceKeys.all,
25
+ queryFn: () => requestJson('/api/workspaces'),
26
+ staleTime: Infinity,
27
+ refetchOnMount: 'always'
28
+ })
29
+ }
30
+
31
+ export function useWorkspacePreview(workspaceId: string) {
32
+ return useQuery<WorkspacePreview>({
33
+ queryKey: workspaceKeys.preview(workspaceId),
34
+ queryFn: () => requestJson(`/api/workspaces/${workspaceId}/preview`),
35
+ staleTime: 60_000
36
+ })
37
+ }
38
+
39
+ export function useDiscoveredWorkspaces() {
40
+ return useQuery<DiscoveredWorkspace[]>({
41
+ queryKey: workspaceKeys.discover,
42
+ queryFn: () => requestJson('/api/workspaces/discover')
43
+ })
44
+ }
45
+
46
+ export function useAddWorkspace() {
47
+ const queryClient = useQueryClient()
48
+ return useMutation<WorkspaceEntry, Error, DiscoveredWorkspace>({
49
+ mutationFn: discovered =>
50
+ requestJson('/api/workspaces', jsonRequest('POST', discovered), 'Failed to add space'),
51
+ onSuccess: (entry, suggestion) => {
52
+ queryClient.setQueryData<WorkspaceEntry[]>(workspaceKeys.all, previous =>
53
+ upsertWorkspaceEntry(previous, entry)
54
+ )
55
+ queryClient.setQueryData<DiscoveredWorkspace[]>(workspaceKeys.discover, previous =>
56
+ (previous ?? []).filter(item => item.path !== suggestion.path)
57
+ )
58
+ }
59
+ })
60
+ }
61
+
62
+ export type CreateWorkspaceInfo = {
63
+ root: string
64
+ displayRoot: string
65
+ canChooseFolder: boolean
66
+ }
67
+
68
+ export function useCreateWorkspaceInfo() {
69
+ return useQuery<CreateWorkspaceInfo>({
70
+ queryKey: workspaceKeys.createInfo,
71
+ queryFn: () => requestJson('/api/workspaces/create'),
72
+ staleTime: Infinity
73
+ })
74
+ }
75
+
76
+ export type ChooseFolderResult = { path: string } | { canceled: true }
77
+
78
+ export function useChooseFolder() {
79
+ return useMutation<ChooseFolderResult, Error, void>({
80
+ mutationFn: () =>
81
+ requestJson('/api/workspaces/choose-folder', { method: 'POST' }, 'Failed to choose folder')
82
+ })
83
+ }
84
+
85
+ export type CreateWorkspaceInput = {
86
+ name: string
87
+ type: WorkspaceType
88
+ }
89
+
90
+ export function useCreateWorkspace() {
91
+ const queryClient = useQueryClient()
92
+ return useMutation<WorkspaceEntry, Error, CreateWorkspaceInput>({
93
+ mutationFn: input =>
94
+ requestJson('/api/workspaces/create', jsonRequest('POST', input), 'Failed to create space'),
95
+ onSuccess: entry => {
96
+ queryClient.setQueryData<WorkspaceEntry[]>(workspaceKeys.all, previous => [
97
+ ...(previous ?? []),
98
+ entry
99
+ ])
100
+ }
101
+ })
102
+ }
103
+
104
+ export function useReorderWorkspaces() {
105
+ const queryClient = useQueryClient()
106
+ return useMutation<WorkspaceEntry[], Error, string[], { previous?: WorkspaceEntry[] }>({
107
+ mutationFn: ids =>
108
+ requestJson('/api/workspaces/order', jsonRequest('PUT', { ids }), 'Failed to reorder spaces'),
109
+ onMutate: async ids => {
110
+ // Exact: only pause the workspace list itself — a prefix cancel would
111
+ // abort unrelated in-flight fetches (transcripts, widgets) that never
112
+ // retry on their own.
113
+ await queryClient.cancelQueries({ queryKey: workspaceKeys.all, exact: true })
114
+ const previous = queryClient.getQueryData<WorkspaceEntry[]>(workspaceKeys.all)
115
+ if (previous) {
116
+ const byId = new Map(previous.map(entry => [entry.id, entry]))
117
+ const ordered = ids
118
+ .map(id => byId.get(id))
119
+ .filter((entry): entry is WorkspaceEntry => Boolean(entry))
120
+ if (ordered.length === previous.length) {
121
+ queryClient.setQueryData(workspaceKeys.all, ordered)
122
+ }
123
+ }
124
+ return { previous }
125
+ },
126
+ onError: (_error, _ids, context) => {
127
+ if (context?.previous) queryClient.setQueryData(workspaceKeys.all, context.previous)
128
+ queryClient.invalidateQueries({ queryKey: workspaceKeys.all, exact: true })
129
+ },
130
+ onSuccess: entries => {
131
+ queryClient.setQueryData(workspaceKeys.all, entries)
132
+ }
133
+ })
134
+ }
135
+
136
+ export function useRemoveWorkspace() {
137
+ const queryClient = useQueryClient()
138
+ return useMutation<void, Error, string>({
139
+ mutationFn: workspaceId =>
140
+ requestVoid(`/api/workspaces/${workspaceId}`, { method: 'DELETE' }, 'Failed to remove space'),
141
+ onSuccess: (_result, workspaceId) => {
142
+ queryClient.setQueryData<WorkspaceEntry[]>(workspaceKeys.all, previous =>
143
+ (previous ?? []).filter(workspace => workspace.id !== workspaceId)
144
+ )
145
+ queryClient.invalidateQueries({ queryKey: workspaceKeys.discover })
146
+ }
147
+ })
148
+ }
@@ -0,0 +1,44 @@
1
+ import claudeIcon from '@/client/assets/claude.svg'
2
+ import hermesIcon from '@/client/assets/hermes-nous.png'
3
+ import openclawIcon from '@/client/assets/openclaw.svg'
4
+ import { cn } from '@/client/lib/cn'
5
+ import type { DiscoveredWorkspace, WorkspaceEntry, WorkspaceType } from '@/lib/types'
6
+
7
+ export const workspaceProviderIcon: Record<WorkspaceType, string> = {
8
+ 'claude-code': claudeIcon,
9
+ openclaw: openclawIcon,
10
+ hermes: hermesIcon
11
+ }
12
+
13
+ export const workspaceTypeLabel: Record<WorkspaceType, string> = {
14
+ 'claude-code': 'Claude Code',
15
+ openclaw: 'OpenClaw',
16
+ hermes: 'Hermes'
17
+ }
18
+
19
+ type WorkspaceTypeIconProps = {
20
+ type: WorkspaceType
21
+ className?: string
22
+ }
23
+
24
+ export function WorkspaceTypeIcon({ type, className }: WorkspaceTypeIconProps) {
25
+ return (
26
+ <img
27
+ src={workspaceProviderIcon[type]}
28
+ alt=""
29
+ aria-label={workspaceTypeLabel[type]}
30
+ className={cn('size-4 shrink-0', className)}
31
+ />
32
+ )
33
+ }
34
+
35
+ type WorkspaceDisplaySource = Pick<
36
+ WorkspaceEntry | DiscoveredWorkspace,
37
+ 'name' | 'path' | 'type' | 'agentId'
38
+ >
39
+
40
+ export function workspaceDisplayName(workspace: WorkspaceDisplaySource): string {
41
+ if (workspace.name) return workspace.name
42
+ if (workspace.type === 'openclaw') return workspace.agentId ?? 'OpenClaw agent'
43
+ return workspace.path.split('/').pop() || workspace.path
44
+ }
@@ -0,0 +1,312 @@
1
+ import { useCallback, useRef, useState } from 'react'
2
+
3
+ import {
4
+ type Editor,
5
+ type TLAssetStore,
6
+ type TLComponents,
7
+ type TLEditorSnapshot,
8
+ type TLUiOverrides,
9
+ DefaultFillStyle,
10
+ DefaultFontStyle,
11
+ DefaultHorizontalAlignStyle,
12
+ DefaultVerticalAlignStyle,
13
+ Tldraw,
14
+ getSnapshot,
15
+ loadSnapshot
16
+ } from 'tldraw'
17
+ import 'tldraw/tldraw.css'
18
+
19
+ import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
20
+ import { setScratchExecutor } from '@/client/features/scratchpad/scratch-executor'
21
+ import { type WorkspaceEvent, useWorkspaceEvent } from '@/client/runtime/useWorkspaceEvents'
22
+ import type { ScratchOp, ScratchOpResult } from '@/lib/types'
23
+ import {
24
+ type ScratchpadFetch,
25
+ ScratchpadSkewNotice,
26
+ detectScratchpadSkew,
27
+ useScratchpadSnapshot
28
+ } from './useScratchpadSnapshot'
29
+ import { ScratchStyleBar, ScratchToolbar } from './ScratchpadControls'
30
+
31
+ // Identifies this tab's writes so it can ignore the `scratchpad:updated` echo of
32
+ // its own save (see the MEI reload below). Per page load.
33
+ const ORIGIN_ID = Math.random().toString(36).slice(2)
34
+
35
+ const AUTOSAVE_MS = 500
36
+
37
+ // tldraw license key, inlined at build time from the PUBLIC_TLDRAW_LICENSE_KEY
38
+ // env var (Bun's prefix-based env inlining — see bunfig.toml `[serve.static] env`
39
+ // for dev and scripts/build-client.ts for prod). The key is public by design
40
+ // (domain-scoped, ships in the client bundle). Empty/unset → undefined →
41
+ // tldraw's default unlicensed watermark. See docs/moi-scratchpad.md.
42
+ // Inlining requires the var to be set when the server process starts — the CLI
43
+ // launcher defaults it (server/cli.ts); a bare ref here throws in the browser.
44
+ const LICENSE_KEY = process.env.PUBLIC_TLDRAW_LICENSE_KEY || undefined
45
+
46
+ // Execute a relayed op in this tab. Only `view` is relayed now — rasterizing the
47
+ // canvas to a PNG needs the browser (`editor.toImageDataUrl`); every mutation runs
48
+ // server-side against the disk snapshot (see server/scratchpad-executor.ts), so a
49
+ // non-view op arriving here is unexpected.
50
+ function makeExecutor(editor: Editor) {
51
+ return async (op: ScratchOp): Promise<ScratchOpResult> => {
52
+ if (op.kind !== 'view') {
53
+ throw new Error(`Scratchpad op "${op.kind}" runs on the server, not the browser.`)
54
+ }
55
+ const ids = [...editor.getCurrentPageShapeIds()]
56
+ if (ids.length === 0) throw new Error('Canvas is empty — nothing to view.')
57
+ const { url } = await editor.toImageDataUrl(ids, {
58
+ format: 'png',
59
+ background: true,
60
+ padding: 32
61
+ })
62
+ return { image: url }
63
+ }
64
+ }
65
+
66
+ // File-backed assets: without this, tldraw inlines every pasted/dropped image as
67
+ // a base64 data URL inside the document — megabytes re-serialized into
68
+ // `.moi/.scratchpad.json` on every autosave and shipped over every GET/PUT.
69
+ // Instead `upload` POSTs the bytes once and stores a tiny `asset:<file>` src on
70
+ // the record; `resolve` maps it back to the serving URL at render time. Legacy
71
+ // snapshots still holding data URLs pass through `resolve` untouched (the
72
+ // server extracts them to files on the next save). See server/scratchpad-assets.ts.
73
+ function makeAssetStore(workspaceId: string): TLAssetStore {
74
+ const base = `/api/workspaces/${workspaceId}/scratchpad/assets`
75
+ return {
76
+ async upload(_asset, file) {
77
+ const res = await fetch(base, {
78
+ method: 'POST',
79
+ headers: { 'Content-Type': file.type || 'application/octet-stream' },
80
+ body: file
81
+ })
82
+ if (!res.ok) throw new Error(`Upload failed: ${await res.text()}`)
83
+ const { src } = (await res.json()) as { src: string }
84
+ return { src }
85
+ },
86
+ resolve(asset) {
87
+ const src = asset.props.src
88
+ if (src?.startsWith('asset:')) return `${base}/${src.slice('asset:'.length)}`
89
+ return src
90
+ }
91
+ }
92
+ }
93
+
94
+ // --- Scratchpad UI shell --------------------------------------------------
95
+ // We replace tldraw's full UI with a curated subset (see docs/moi-scratchpad.md
96
+ // for the prioritization). Backbone v1: a custom vertical tool bar on the left,
97
+ // most menus dropped, pages disabled, export hard-removed, grid on. The default
98
+ // (contextual) style panel and zoom control are kept as-is for now; style
99
+ // trimming is a follow-up.
100
+
101
+ // Drop tldraw's built-in chrome we replace with custom overlays (tool bar, style
102
+ // bar). `null` removes a component entirely. NavigationPanel is kept — we like its
103
+ // native zoom control — but Minimap is nulled, which also strips its toggle button
104
+ // from the panel, leaving just the zoom menu. Kept on defaults: NavigationPanel
105
+ // (zoom), ContextMenu, KeyboardShortcutsDialog.
106
+ const SCRATCH_COMPONENTS: TLComponents = {
107
+ Toolbar: null,
108
+ StylePanel: null,
109
+ Minimap: null,
110
+ MainMenu: null,
111
+ PageMenu: null,
112
+ ActionsMenu: null,
113
+ QuickActions: null,
114
+ HelpMenu: null,
115
+ DebugMenu: null
116
+ }
117
+
118
+ // Remove dropped tools (kills their shortcuts too) and hard-disable export/print.
119
+ // Deleting an unknown action id is a harmless no-op.
120
+ const SCRATCH_OVERRIDES: TLUiOverrides = {
121
+ tools(_editor, tools) {
122
+ delete tools.frame
123
+ delete tools.laser
124
+ return tools
125
+ },
126
+ actions(_editor, actions) {
127
+ for (const id of ['export-as-svg', 'export-as-png', 'copy-as-svg', 'copy-as-png', 'print']) {
128
+ delete actions[id]
129
+ }
130
+ return actions
131
+ }
132
+ }
133
+
134
+ // One page only — disables the page selector and all multi-page UI.
135
+ const SCRATCH_OPTIONS = { maxPages: 1 }
136
+
137
+ // Browser drag/drop/paste limits (tldraw defaults: reject >10MB, no rescale). We
138
+ // accept larger drops and rescale big images to fit so a phone-sized photo lands
139
+ // as a lightweight asset instead of bloating the snapshot's sidecar files. The
140
+ // size check runs BEFORE the rescale, so a 32MB drop is admitted and then shrunk.
141
+ // (The agent's `moi scratch add image` path has its own presets — see the
142
+ // executor's IMAGE_PRESETS; this only governs what the browser accepts.)
143
+ const MAX_DROP_BYTES = 32 * 1024 * 1024
144
+ const MAX_IMAGE_DIMENSION = 2048
145
+
146
+ // The Scratchpad surface: a real tldraw editor, hydrated from and autosaved to
147
+ // `.moi/.scratchpad.json` via REST. One canvas shared by the user and the agent —
148
+ // the agent reaches it through `moi scratch` (relayed ops execute here). See
149
+ // docs/moi-scratchpad.md.
150
+ export function Scratchpad() {
151
+ const workspaceId = useWorkspaceId()
152
+ const editorRef = useRef<Editor | null>(null)
153
+ // The whole scratchpad region (canvas + tool bar + style bar). Focus is driven
154
+ // off whether a pointerdown lands inside this, so clicking a tool keeps the
155
+ // editor focused — see the pointerdown handler in onMount.
156
+ const rootRef = useRef<HTMLDivElement>(null)
157
+ const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
158
+ // Set before a remote `loadSnapshot`; the autosave listener consumes it on the
159
+ // first (throttled) flush so the load doesn't echo back out as a save. (Store
160
+ // listeners fire on the next frame, not synchronously, so a timer-based clear
161
+ // would race — consuming it in the listener is timing-independent.)
162
+ const applyingRemote = useRef(false)
163
+ // Reactive handle to the mounted editor, used to render the custom tool bar.
164
+ const [editor, setEditor] = useState<Editor | null>(null)
165
+ const { loaded, snapshot, skew, flagSkew } = useScratchpadSnapshot(workspaceId)
166
+ // Stable identity per workspace, held in a ref rather than useMemo (which React
167
+ // may discard): a fresh `assets` identity makes <Tldraw> rebuild its store and
168
+ // remount the editor, dropping unsaved edits and resetting the camera.
169
+ const assetStoreRef = useRef<{ id: string; store: TLAssetStore } | null>(null)
170
+ if (assetStoreRef.current?.id !== workspaceId) {
171
+ assetStoreRef.current = { id: workspaceId, store: makeAssetStore(workspaceId) }
172
+ }
173
+ const assetStore = assetStoreRef.current.store
174
+
175
+ const save = useCallback(() => {
176
+ const editor = editorRef.current
177
+ if (!editor) return
178
+ let document: TLEditorSnapshot['document']
179
+ try {
180
+ document = getSnapshot(editor.store).document
181
+ } catch {
182
+ return
183
+ }
184
+ void fetch(`/api/workspaces/${workspaceId}/scratchpad`, {
185
+ method: 'PUT',
186
+ headers: { 'Content-Type': 'application/json' },
187
+ body: JSON.stringify({ document, origin: ORIGIN_ID })
188
+ }).catch(() => {})
189
+ }, [workspaceId])
190
+
191
+ // A remote save (another tab, or an agent draw landing in another tab) — pull
192
+ // the new snapshot and load it into the live store. Skip our own echo. The
193
+ // fetched document is pre-flighted like the initial load: if the server was
194
+ // swapped for a newer moi mid-session, `loadSnapshot` here would throw — flip
195
+ // the skew notice instead (unmounting the editor, which also stops the
196
+ // autosave timer) so this stale tab can't save over the newer file.
197
+ useWorkspaceEvent((e: WorkspaceEvent) => {
198
+ if (e.type !== 'scratchpad:updated' || e.workspaceId !== workspaceId) return
199
+ if (e.origin && e.origin === ORIGIN_ID) return
200
+ if (!editorRef.current) return
201
+ fetch(`/api/workspaces/${workspaceId}/scratchpad`)
202
+ .then(r => r.json())
203
+ .then((d: ScratchpadFetch) => {
204
+ const editor = editorRef.current
205
+ if (!editor || !d?.document) return
206
+ const found = detectScratchpadSkew(d.document, d.writer)
207
+ if (found) {
208
+ if (saveTimer.current) clearTimeout(saveTimer.current)
209
+ flagSkew(found)
210
+ return
211
+ }
212
+ applyingRemote.current = true
213
+ loadSnapshot(editor.store, { document: d.document })
214
+ })
215
+ .catch(() => {})
216
+ })
217
+
218
+ const onMount = useCallback(
219
+ (editor: Editor) => {
220
+ editorRef.current = editor
221
+ setEditor(editor)
222
+ // Grid on by default (no toggle in the UI).
223
+ editor.updateInstanceState({ isGridMode: true })
224
+ // Locked defaults that have no UI control: hand-drawn font, centered text.
225
+ editor.run(() => {
226
+ editor.setStyleForNextShapes(DefaultFontStyle, 'draw')
227
+ editor.setStyleForNextShapes(DefaultHorizontalAlignStyle, 'middle')
228
+ editor.setStyleForNextShapes(DefaultVerticalAlignStyle, 'middle')
229
+ // Rectangles start solid-filled. Still user-adjustable via the style bar —
230
+ // applyToolLocks deliberately never re-pins fill, so this is a default, not
231
+ // a lock. ('fill' = the style bar's "Solid"; 'solid' there means "Semi".)
232
+ editor.setStyleForNextShapes(DefaultFillStyle, 'fill')
233
+ })
234
+ const unlisten = editor.store.listen(
235
+ () => {
236
+ if (applyingRemote.current) {
237
+ applyingRemote.current = false
238
+ return
239
+ }
240
+ if (saveTimer.current) clearTimeout(saveTimer.current)
241
+ saveTimer.current = setTimeout(save, AUTOSAVE_MS)
242
+ },
243
+ { source: 'user', scope: 'document' }
244
+ )
245
+ setScratchExecutor(workspaceId, makeExecutor(editor))
246
+ // Focus management: tldraw only fires keyboard shortcuts while the editor's
247
+ // instance `isFocused` is set, but with `autoFocus={false}` it never flips
248
+ // that on its own. We drive it from where the pointer lands — a pointerdown
249
+ // inside the scratchpad (canvas, tool bar, or style bar, all under rootRef)
250
+ // focuses the editor; one anywhere else (e.g. the chat) blurs it, so hotkeys
251
+ // are live only when the scratchpad is the active surface. Guarded on the
252
+ // current state so a click already inside (e.g. double-click to edit a
253
+ // shape's text) doesn't re-focus the container and steal focus from the
254
+ // text field. Capture phase so we see it regardless of downstream handlers.
255
+ const onPointerDown = (e: PointerEvent) => {
256
+ const target = e.target as Node | null
257
+ const inside = !!target && !!rootRef.current?.contains(target)
258
+ if (inside) {
259
+ if (!editor.getIsFocused()) editor.focus()
260
+ } else if (editor.getIsFocused()) {
261
+ editor.blur()
262
+ }
263
+ }
264
+ const doc = editor.getContainer().ownerDocument
265
+ doc.addEventListener('pointerdown', onPointerDown, true)
266
+ // First open: grab focus so the user can reach for the keyboard right away.
267
+ // `focus()` both sets `isFocused` and DOM-focuses the canvas container, so it
268
+ // becomes the active element — clearing tldraw's secondary guard that mutes
269
+ // shortcuts while an input/textarea (e.g. the chat) holds focus.
270
+ editor.focus()
271
+ return () => {
272
+ unlisten()
273
+ doc.removeEventListener('pointerdown', onPointerDown, true)
274
+ if (saveTimer.current) clearTimeout(saveTimer.current)
275
+ setScratchExecutor(workspaceId, null)
276
+ setEditor(null)
277
+ editorRef.current = null
278
+ }
279
+ },
280
+ [workspaceId, save]
281
+ )
282
+
283
+ if (!loaded) return <div className="min-h-0 flex-1 bg-muted/40" />
284
+ if (skew) return <ScratchpadSkewNotice skew={skew} />
285
+
286
+ return (
287
+ <div ref={rootRef} className="relative min-h-0 flex-1 overflow-hidden">
288
+ <div className="absolute inset-0">
289
+ <Tldraw
290
+ snapshot={snapshot}
291
+ assets={assetStore}
292
+ licenseKey={LICENSE_KEY}
293
+ onMount={onMount}
294
+ components={SCRATCH_COMPONENTS}
295
+ overrides={SCRATCH_OVERRIDES}
296
+ options={SCRATCH_OPTIONS}
297
+ // Accept drops up to 32MB and rescale big images to fit (tldraw checks
298
+ // the size before rescaling, so a large photo is admitted then shrunk).
299
+ maxAssetSize={MAX_DROP_BYTES}
300
+ maxImageDimension={MAX_IMAGE_DIMENSION}
301
+ // Hand focus control entirely to us: tldraw's own `autoFocus` only seeds
302
+ // the `isFocused` flag (hotkeys would fire window-wide, even from the
303
+ // chat) without ever DOM-focusing the canvas. Instead onMount focuses
304
+ // the editor on open and a pointerdown handler toggles it thereafter.
305
+ autoFocus={false}
306
+ />
307
+ </div>
308
+ {editor && <ScratchToolbar editor={editor} />}
309
+ {editor && <ScratchStyleBar editor={editor} />}
310
+ </div>
311
+ )
312
+ }