moi-computer 0.11.1-next.2 → 0.11.1-next.4

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 (222) hide show
  1. package/README.md +2 -2
  2. package/client/app/AppRouter.tsx +2 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +7 -9
  4. package/client/app/shell/SidebarLayout.tsx +18 -15
  5. package/client/components/shared/BottomPanel.tsx +26 -14
  6. package/client/components/shared/PanelHeader.tsx +1 -1
  7. package/client/components/shared/ReorderableList.tsx +7 -2
  8. package/client/components/shared/WorkspaceIcon.tsx +92 -0
  9. package/client/components/ui/alert-dialog.tsx +1 -0
  10. package/client/components/ui/checkbox.tsx +1 -0
  11. package/client/components/ui/inline-input.tsx +84 -0
  12. package/client/components/ui/toast.tsx +2 -2
  13. package/client/features/applets/AppletMount.tsx +1 -1
  14. package/client/features/applets/applet-cache.ts +3 -3
  15. package/client/features/applets/applet-runtime.ts +147 -108
  16. package/client/features/applets/applet-styles.ts +2 -2
  17. package/client/features/applets/applet-thumbnail.ts +6 -8
  18. package/client/features/applets/useApplet.ts +10 -9
  19. package/client/features/chat/ChatPanel.tsx +19 -10
  20. package/client/features/chat/ChatPopup.tsx +7 -2
  21. package/client/features/chat/applet-chat-intents.ts +170 -0
  22. package/client/features/chat/chat-send.ts +103 -62
  23. package/client/features/chat/chat-store.ts +50 -59
  24. package/client/features/chat/composer/ChatComposer.tsx +43 -132
  25. package/client/features/chat/composer/ModelPicker.tsx +3 -16
  26. package/client/features/chat/composer/attachments/AttachmentChip.tsx +99 -0
  27. package/client/features/chat/composer/attachments/DrawingAttachmentChip.tsx +37 -0
  28. package/client/features/chat/composer/attachments/FileAttachmentChip.tsx +22 -0
  29. package/client/features/chat/composer/attachments/TextAttachmentChip.tsx +11 -0
  30. package/client/features/chat/composer/attachments/draft-attachments.ts +168 -0
  31. package/client/features/chat/composer/attachments/types.ts +25 -0
  32. package/client/features/chat/composer/attachments/uploads.ts +26 -0
  33. package/client/features/chat/{chat-connection.ts → connection/chat-connection.ts} +1 -1
  34. package/client/features/chat/{chat-frames.ts → connection/chat-frames.ts} +2 -2
  35. package/client/features/chat/{ChatEmptyState.tsx → messages/ChatEmptyState.tsx} +16 -11
  36. package/client/features/chat/{MarkdownContent.tsx → messages/MarkdownContent.tsx} +16 -1
  37. package/client/features/chat/{TurnView.tsx → messages/TurnView.tsx} +22 -15
  38. package/client/features/chat/{tool-group → messages/tool-group}/SubagentCard.tsx +1 -1
  39. package/client/features/chat/{tool-group → messages/tool-group}/TimelineRow.tsx +2 -2
  40. package/client/features/chat/{tool-group → messages/tool-group}/ToolCallGroup.tsx +1 -1
  41. package/client/features/chat/{ChatSelector.tsx → sessions/ChatSelector.tsx} +3 -3
  42. package/client/features/chat/{api.ts → sessions/api.ts} +1 -1
  43. package/client/features/chat/useChat.ts +32 -15
  44. package/client/features/dev/ChatStatesPage.tsx +5 -6
  45. package/client/features/dev/HarnessDebugPage.tsx +10 -7
  46. package/client/features/dev/ToolCallsPage.tsx +1 -1
  47. package/client/features/dev/UiComponentPreviews.tsx +21 -0
  48. package/client/features/dev/chat-states-fixtures.ts +13 -2
  49. package/client/features/drawings/useChatAnnotation.ts +17 -17
  50. package/client/features/drawings/useDrawingLayer.ts +7 -9
  51. package/client/features/drawings/useViewBuilderSketch.ts +18 -15
  52. package/client/features/home/HomePage.tsx +8 -7
  53. package/client/features/home/WorkspacePreview.tsx +1 -1
  54. package/client/features/home/workspace-presentation.tsx +1 -11
  55. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +2 -4
  56. package/client/features/overview/HiddenPanel.tsx +109 -0
  57. package/client/features/overview/Overview.tsx +302 -0
  58. package/client/features/overview/WidgetCanvas.tsx +164 -0
  59. package/client/features/{widgets → overview}/WidgetFrame.tsx +24 -16
  60. package/client/features/overview/WorkspaceName.tsx +60 -0
  61. package/client/features/overview/api.ts +30 -0
  62. package/client/features/overview/default/ViewsWidget.tsx +252 -0
  63. package/client/features/overview/default/registry.tsx +36 -0
  64. package/client/features/{widgets → overview}/grid.ts +36 -0
  65. package/client/features/overview/useGridReconcile.ts +94 -0
  66. package/client/features/scratchpad/Scratchpad.tsx +7 -8
  67. package/client/features/scratchpad/ScratchpadControls.tsx +0 -1
  68. package/client/features/scratchpad/useScratchpadSnapshot.tsx +23 -13
  69. package/client/features/settings/GeneralSettings.tsx +55 -58
  70. package/client/features/settings/SettingsLayout.tsx +2 -2
  71. package/client/features/settings/WorkspaceIconPicker.tsx +318 -0
  72. package/client/features/settings/WorkspaceSettingsDialog.tsx +65 -0
  73. package/client/features/settings/api.ts +48 -24
  74. package/client/features/views/ViewBuilder.tsx +5 -4
  75. package/client/features/views/ViewManager.tsx +11 -13
  76. package/client/features/views/api.ts +36 -2
  77. package/client/features/views/useViewBuilderActions.ts +8 -5
  78. package/client/features/views/useViewBuilderDrafts.ts +23 -21
  79. package/client/features/views/view-presentation.ts +13 -0
  80. package/client/features/workspace/{CustomizePanel.tsx → ThemePanel.tsx} +26 -31
  81. package/client/features/workspace/UnavailablePage.tsx +21 -0
  82. package/client/features/workspace/WorkspaceLayoutContext.tsx +4 -7
  83. package/client/features/workspace/WorkspaceScreen.tsx +205 -161
  84. package/client/features/workspace/WorkspaceSplitLayout.tsx +1 -1
  85. package/client/features/workspace/WorkspaceTabs.tsx +2 -0
  86. package/client/features/workspace/api.ts +0 -26
  87. package/client/features/workspace/moi-context.ts +8 -9
  88. package/client/features/workspace/tab-resolution.ts +10 -33
  89. package/client/features/workspace/useWorkspaceNavigation.ts +164 -101
  90. package/client/index.css +1 -1
  91. package/client/lib/app-icon-registry.ts +2 -0
  92. package/client/lib/use-latest-ref.ts +11 -0
  93. package/client/main.tsx +1 -1
  94. package/client/runtime/useWorkspaceEvents.ts +59 -14
  95. package/client/theme.css +5 -5
  96. package/dist/chunk-2gs8jjx4.css +1 -0
  97. package/dist/chunk-7vvg5fyz.js +68 -0
  98. package/dist/chunk-94m3q9ce.js +1 -0
  99. package/dist/{chunk-w482ew2c.js → chunk-brr0zbeh.js} +73 -73
  100. package/dist/chunk-by2wqgak.js +1 -0
  101. package/dist/chunk-m1fvqssh.js +2 -0
  102. package/dist/chunk-p34hvqt3.js +1 -0
  103. package/dist/{chunk-4s15axjs.js → chunk-p83f0jnj.js} +2 -2
  104. package/dist/{chunk-j3wvxjr7.js → chunk-tzz101ea.js} +1 -1
  105. package/dist/chunk-xg01f6pn.js +10 -0
  106. package/dist/{chunk-53a7pxcz.js → chunk-zs4mte79.js} +1 -1
  107. package/dist/index.html +1 -1
  108. package/lib/app-icons.ts +1 -0
  109. package/lib/applet-selector.ts +24 -0
  110. package/lib/chat-title.ts +6 -1
  111. package/lib/default-widgets.ts +32 -0
  112. package/lib/format.ts +12 -1
  113. package/lib/message-attachments.ts +40 -0
  114. package/lib/moi-attachments.ts +204 -0
  115. package/lib/moi-context.ts +20 -35
  116. package/lib/navigation.ts +84 -0
  117. package/lib/types.ts +81 -25
  118. package/lib/workspace-icon.ts +20 -0
  119. package/lib/workspace-layout.ts +22 -2
  120. package/lib/workspace-tabs.ts +9 -33
  121. package/package.json +27 -27
  122. package/registry.json +13 -0
  123. package/server/AGENTS.md +1 -0
  124. package/server/api.ts +114 -37
  125. package/server/applet-typecheck.ts +95 -0
  126. package/server/{bundler → applets}/build-applet.ts +13 -246
  127. package/server/applets/config.ts +226 -0
  128. package/server/applets/dependencies.ts +206 -0
  129. package/server/{applets.ts → applets/index.ts} +15 -161
  130. package/server/applets/runtime/base.ts +4 -0
  131. package/server/applets/runtime/moi.ts +42 -0
  132. package/server/applets/runtime/rpc.ts +17 -0
  133. package/server/applets/view-source.ts +67 -0
  134. package/server/attachment-message.ts +95 -0
  135. package/server/cli.ts +163 -97
  136. package/server/control.ts +63 -42
  137. package/server/harness/README.md +4 -2
  138. package/server/harness/acp/adapter.ts +7 -21
  139. package/server/harness/acp/session.ts +31 -50
  140. package/server/harness/claude-code/NOTES.md +8 -2
  141. package/server/harness/claude-code/adapter.ts +8 -25
  142. package/server/harness/claude-code/index.ts +2 -0
  143. package/server/harness/claude-code/session.ts +42 -47
  144. package/server/harness/claude-code/sessions.ts +9 -4
  145. package/server/harness/codex/adapter.ts +8 -7
  146. package/server/harness/codex/index.ts +1 -0
  147. package/server/harness/codex/permissions.ts +1 -1
  148. package/server/harness/codex/session.ts +20 -47
  149. package/server/harness/hermes/NOTES.md +1 -1
  150. package/server/harness/hermes/index.ts +4 -0
  151. package/server/harness/openclaw/NOTES.md +1 -1
  152. package/server/harness/openclaw/adapter.ts +22 -4
  153. package/server/harness/openclaw/gateway.ts +5 -3
  154. package/server/harness/openclaw/session.ts +27 -27
  155. package/server/harness/types.ts +5 -3
  156. package/server/layout.ts +9 -14
  157. package/server/moi-scaffold.ts +21 -13
  158. package/server/navigation-relay.ts +110 -0
  159. package/server/registry.ts +8 -0
  160. package/server/selected-session.ts +24 -4
  161. package/server/skill-update.ts +5 -3
  162. package/server/skill-version.ts +4 -7
  163. package/server/skills-template.ts +48 -9
  164. package/server/tabs.ts +19 -33
  165. package/server/uploads.ts +0 -0
  166. package/server/view-builders.ts +18 -1
  167. package/server/views.ts +126 -6
  168. package/server/web.ts +35 -9
  169. package/server/widgets.ts +12 -5
  170. package/server/workspace-config.ts +13 -9
  171. package/ui-components/button.tsx +2 -2
  172. package/ui-components/docs/kbd.md +191 -0
  173. package/ui-components/dropdown-menu.tsx +1 -1
  174. package/ui-components/kbd.tsx +32 -0
  175. package/ui-components/slider.tsx +1 -1
  176. package/ui-components/switch.tsx +1 -1
  177. package/ui-components/tabs.tsx +1 -1
  178. package/workspace/.claude/skills/moi-workspace/SKILL.md +284 -228
  179. package/workspace/.claude/skills/moi-workspace/references/DESIGN.md +100 -153
  180. package/workspace/.claude/skills/moi-workspace/references/INTENTS.md +156 -0
  181. package/client/features/chat/attachment-staging.ts +0 -153
  182. package/client/features/chat/uploads.ts +0 -18
  183. package/client/features/chat/useAppletChatMessage.ts +0 -68
  184. package/client/features/settings/IconPicker.tsx +0 -442
  185. package/client/features/settings/WorkspaceSettings.tsx +0 -95
  186. package/client/features/settings/render-icon.ts +0 -173
  187. package/client/features/widgets/HiddenPanel.tsx +0 -80
  188. package/client/features/widgets/WidgetGrid.tsx +0 -123
  189. package/client/features/widgets/Widgets.tsx +0 -262
  190. package/client/features/widgets/useGridReconcile.ts +0 -73
  191. package/dist/chunk-245wt82v.css +0 -1
  192. package/dist/chunk-87thzbtw.js +0 -2
  193. package/dist/chunk-a6jad1a6.js +0 -1
  194. package/dist/chunk-dghwstd2.js +0 -9
  195. package/dist/chunk-eg120aca.js +0 -1
  196. package/dist/chunk-j7hh2ab4.js +0 -70
  197. package/dist/chunk-y8eyahwx.js +0 -1
  198. /package/client/features/chat/{ChatPromptBubbles.tsx → messages/ChatPromptBubbles.tsx} +0 -0
  199. /package/client/features/chat/{ShimmerText.tsx → messages/ShimmerText.tsx} +0 -0
  200. /package/client/features/chat/{group-turns.ts → messages/group-turns.ts} +0 -0
  201. /package/client/features/chat/{interleave-notices.ts → messages/interleave-notices.ts} +0 -0
  202. /package/client/features/chat/{preview-turn.ts → messages/preview-turn.ts} +0 -0
  203. /package/client/features/chat/{tool-group → messages/tool-group}/CodeBlock.tsx +0 -0
  204. /package/client/features/chat/{tool-group → messages/tool-group}/Collapse.tsx +0 -0
  205. /package/client/features/chat/{tool-group → messages/tool-group}/ReadImagePreview.tsx +0 -0
  206. /package/client/features/chat/{tool-group → messages/tool-group}/ToolOutput.tsx +0 -0
  207. /package/client/features/chat/{tool-group → messages/tool-group}/detect.ts +0 -0
  208. /package/client/features/chat/{tool-group → messages/tool-group}/fixtures.ts +0 -0
  209. /package/client/features/chat/{tool-group → messages/tool-group}/format/claude.ts +0 -0
  210. /package/client/features/chat/{tool-group → messages/tool-group}/format/codex.ts +0 -0
  211. /package/client/features/chat/{tool-group → messages/tool-group}/format/hermes.ts +0 -0
  212. /package/client/features/chat/{tool-group → messages/tool-group}/format/index.ts +0 -0
  213. /package/client/features/chat/{tool-group → messages/tool-group}/format/mcp.ts +0 -0
  214. /package/client/features/chat/{tool-group → messages/tool-group}/format/openclaw.ts +0 -0
  215. /package/client/features/chat/{tool-group → messages/tool-group}/format/shared.ts +0 -0
  216. /package/client/features/chat/{tool-group → messages/tool-group}/format/shell.ts +0 -0
  217. /package/client/features/chat/{tool-group → messages/tool-group}/index.ts +0 -0
  218. /package/client/features/chat/{useStickToBottom.ts → messages/useStickToBottom.ts} +0 -0
  219. /package/client/features/chat/{session-view.ts → sessions/session-view.ts} +0 -0
  220. /package/client/features/chat/{useSelectedSession.ts → sessions/useSelectedSession.ts} +0 -0
  221. /package/server/{bundler → applets}/applet-css.ts +0 -0
  222. /package/server/{bundler → applets}/build-worker.ts +0 -0
@@ -0,0 +1,170 @@
1
+ // Connect validated applet intents to the active chat: stage attachments in the
2
+ // draft or send a message immediately, then reveal and focus chat.
3
+ // The runtime owns argument validation, source attribution, and intent rate limits;
4
+ // these handlers own draft staging, preparation, and cancellation of immediate sends.
5
+ import { stageChatAttachment } from './composer/attachments/draft-attachments'
6
+ import { reportAppletError } from '@/client/features/applets/applet-log'
7
+ import {
8
+ type AppletChatMessage,
9
+ appletRuntime,
10
+ useAppletEvent
11
+ } from '@/client/features/applets/applet-runtime'
12
+ import { prepareChatAttachments, type ChatSendOptions, type PreparedAttachments } from './chat-send'
13
+ import { useLayoutEffect } from 'react'
14
+ import { useQueryClient, type QueryClient } from '@tanstack/react-query'
15
+ import { appUiKeys } from '@/client/api/app-ui-keys'
16
+ import { toast } from '@/client/components/ui/toast'
17
+ import { useLatestRef } from '@/client/lib/use-latest-ref'
18
+ import type { SelectedSessionState } from '@/lib/types'
19
+ import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
20
+ import type { AgentAvailability } from '@/client/lib/agent-availability'
21
+
22
+ type UseAppletChatMessageOptions = {
23
+ sessionId: string | null
24
+ send: (draft: string, options?: ChatSendOptions) => void
25
+ // Bring the chat on screen before the run starts. On a view tab in
26
+ // full-screen mode the chat is a popover that is closed by default, so
27
+ // without this the agent would start working somewhere the user can't see.
28
+ revealChat: () => void
29
+ // Same explicit availability state the composer's send button uses.
30
+ agentAvailability: AgentAvailability
31
+ }
32
+
33
+ // Why an applet message can't go out right now, or null when it can. The gate
34
+ // is exactly the composer's. Starting a run the visible UI would have refused
35
+ // is worse than dropping a click the user can repeat a moment later.
36
+ export function appletSendBlockedReason(availability: AgentAvailability): string | null {
37
+ if (availability.status === 'available') return null
38
+ if (availability.status === 'checking') {
39
+ return 'The agent is still connecting'
40
+ }
41
+ if (availability.status === 'disconnected') return 'This workspace is disconnected from moi'
42
+ if (availability.status === 'login-required') {
43
+ return 'Sign in to the agent to send this message'
44
+ }
45
+ return 'The agent is unavailable in this workspace'
46
+ }
47
+
48
+ // One handler lifetime belongs to one workspace screen. Listen to selection
49
+ // changes in the query cache itself: switching away and back can happen before
50
+ // React renders, and must still cancel the pending send.
51
+ export function createAppletMessageHandler(
52
+ workspaceId: string,
53
+ queryClient: QueryClient,
54
+ getOptions: () => UseAppletChatMessageOptions
55
+ ) {
56
+ const pending = new Set<() => void>()
57
+ let disposed = false
58
+ const selectedSession = () =>
59
+ queryClient.getQueryData<SelectedSessionState>(appUiKeys.selectedSession(workspaceId))
60
+ ?.sessionId ?? null
61
+
62
+ async function handle(event: AppletChatMessage): Promise<void> {
63
+ if (disposed) return
64
+ const reportFailure = (message: string) => {
65
+ toast.add({ title: 'Couldn’t send message', description: message, type: 'error' })
66
+ reportAppletError(workspaceId, {
67
+ source: 'runtime',
68
+ message: `sendChatMessage() from ${event.source}: ${message}`
69
+ })
70
+ }
71
+ const blocked = appletSendBlockedReason(getOptions().agentAvailability)
72
+ if (blocked) {
73
+ reportFailure(blocked)
74
+ return
75
+ }
76
+
77
+ const sessionId = selectedSession()
78
+ let active = true
79
+ let loadingToast: string | undefined
80
+ const finish = () => {
81
+ active = false
82
+ unsubscribe()
83
+ pending.delete(cancel)
84
+ if (loadingToast) toast.close(loadingToast)
85
+ }
86
+ const cancel = () => {
87
+ if (!active) return
88
+ finish()
89
+ toast.add({
90
+ title: 'Message canceled',
91
+ description: 'The active chat changed before attachments were ready',
92
+ type: 'info'
93
+ })
94
+ }
95
+ const unsubscribe = queryClient.getQueryCache().subscribe(() => {
96
+ if (selectedSession() !== sessionId) cancel()
97
+ })
98
+ pending.add(cancel)
99
+ // A selection change can reach the cache before React has replaced the
100
+ // send callback. Never invoke a callback that still targets the old chat.
101
+ if (getOptions().sessionId !== sessionId) {
102
+ cancel()
103
+ return
104
+ }
105
+ getOptions().revealChat()
106
+
107
+ let preparedAttachments: PreparedAttachments
108
+ try {
109
+ if (event.attachments.some(attachment => attachment.type === 'file')) {
110
+ loadingToast = toast.add({ title: 'Preparing attachments…', type: 'loading', timeout: 0 })
111
+ }
112
+ preparedAttachments = await prepareChatAttachments(workspaceId, event.attachments)
113
+ if (!active) return
114
+ const options = getOptions()
115
+ const blocked = appletSendBlockedReason(options.agentAvailability)
116
+ if (blocked) throw new Error(blocked)
117
+ if (options.sessionId !== sessionId) {
118
+ cancel()
119
+ return
120
+ }
121
+ } catch (error) {
122
+ if (active) {
123
+ finish()
124
+ reportFailure(error instanceof Error ? error.message : 'Couldn’t prepare the attachments')
125
+ }
126
+ return
127
+ }
128
+ // Stop watching before sending: a new chat gets its first session ID here.
129
+ finish()
130
+ try {
131
+ getOptions().send(event.message, { applet: { source: event.source }, preparedAttachments })
132
+ } catch (error) {
133
+ reportFailure(
134
+ error instanceof Error ? error.message : 'Something went wrong while sending this message'
135
+ )
136
+ }
137
+ }
138
+
139
+ return {
140
+ handle,
141
+ dispose() {
142
+ disposed = true
143
+ for (const cancel of pending) cancel()
144
+ }
145
+ }
146
+ }
147
+
148
+ export function useAppletChatMessage(options: UseAppletChatMessageOptions): void {
149
+ const workspaceId = useWorkspaceId()
150
+ const queryClient = useQueryClient()
151
+ const latest = useLatestRef(options)
152
+ useLayoutEffect(() => {
153
+ const handler = createAppletMessageHandler(workspaceId, queryClient, () => latest.current)
154
+ const unsubscribe = appletRuntime(workspaceId).on('sendChatMessage', event => {
155
+ void handler.handle(event)
156
+ })
157
+ return () => {
158
+ unsubscribe()
159
+ handler.dispose()
160
+ }
161
+ }, [workspaceId, queryClient, latest])
162
+ }
163
+
164
+ export function useAppletChatAttachment(sessionId: string | null, revealChat: () => void): void {
165
+ const workspaceId = useWorkspaceId()
166
+ useAppletEvent(workspaceId, 'addChatAttachment', attachment => {
167
+ void stageChatAttachment({ workspaceId, sessionId }, attachment)
168
+ revealChat()
169
+ })
170
+ }
@@ -1,24 +1,120 @@
1
+ import type {
2
+ AttachmentInput,
3
+ AttachmentOrigin,
4
+ DrawingPurpose,
5
+ MessageAttachment,
6
+ TextAttachment,
7
+ UploadInfo
8
+ } from '@/lib/types'
9
+ import { uploadChatFile } from './composer/attachments/uploads'
10
+ import { attachmentPart } from '@/lib/moi-attachments'
1
11
  import type { QueryClient } from '@tanstack/react-query'
2
12
 
3
13
  import { workspaceKeys } from '@/client/api/workspace-keys'
4
- import { attachmentKey, type ChatAttachment, liveStore } from '@/client/features/chat/chat-store'
14
+ import { attachmentKey, liveStore } from '@/client/features/chat/chat-store'
15
+ import type { StagedAttachment } from '@/client/features/chat/composer/attachments/types'
5
16
  import { resolveSelectedModel } from '@/client/features/chat/composer/model-order'
6
17
  import type { MoiUserMessageOptions } from '@/client/features/workspace/moi-context'
7
18
  import { STREAM_RESPONSES } from '@/client/lib/flags'
8
19
  import { formatChatTitle } from '@/lib/chat-title'
9
20
  import { applyEvent, emptyViewState } from '@/lib/format'
21
+ import { messageAttachmentLimitError } from '@/lib/message-attachments'
10
22
  import type { Part, SessionInfo, ViewState, WorkspaceAgent } from '@/lib/types'
11
23
 
12
- // What a caller may attach to one message beyond its text. All of it is
13
- // envelope material — the agent sees it, the chat bubble does not.
14
- export type ChatSendOptions = MoiUserMessageOptions
24
+ // Explicit attachments belong to this send, independently of the user's draft.
25
+ export type PreparedAttachments = {
26
+ attachments: MessageAttachment[]
27
+ parts: Part[]
28
+ }
29
+
30
+ export type ChatSendOptions = MoiUserMessageOptions & {
31
+ preparedAttachments?: PreparedAttachments
32
+ }
33
+
34
+ // Both send paths derive the wire reference and optimistic display together.
35
+ function prepareAttachment(
36
+ input: TextAttachment | UploadInfo,
37
+ previewUrl?: string,
38
+ options: Partial<AttachmentOrigin> & { purpose?: DrawingPurpose } = {}
39
+ ): { attachment: MessageAttachment; part: Part } {
40
+ if ('id' in input) {
41
+ const metadata = {
42
+ source: options.source,
43
+ ...(input.kind === 'image' ? { purpose: options.purpose } : {})
44
+ }
45
+ return {
46
+ attachment: { type: 'upload', uploadId: input.id, ...metadata },
47
+ part: {
48
+ type: 'file-attachment',
49
+ mediaType: input.mediaType,
50
+ label: input.filename,
51
+ ...metadata,
52
+ previewUrl: input.kind === 'image' ? previewUrl : undefined
53
+ }
54
+ }
55
+ }
56
+ const { source, label, text } = input
57
+ return {
58
+ attachment: { type: 'text', source, label, text },
59
+ part: attachmentPart({ type: 'text', source, label, text })
60
+ }
61
+ }
62
+
63
+ function collectPreparedAttachments(
64
+ items: ReturnType<typeof prepareAttachment>[]
65
+ ): PreparedAttachments {
66
+ return {
67
+ attachments: items.map(item => item.attachment),
68
+ parts: items.map(item => item.part)
69
+ }
70
+ }
71
+
72
+ export async function prepareChatAttachments(
73
+ workspaceId: string,
74
+ inputs: readonly (AttachmentInput & AttachmentOrigin)[]
75
+ ): Promise<PreparedAttachments> {
76
+ const limitError = messageAttachmentLimitError(inputs)
77
+ if (limitError) throw new Error(limitError)
78
+ return collectPreparedAttachments(
79
+ await Promise.all(
80
+ inputs.map(async input => {
81
+ if (input.type === 'text') return prepareAttachment(input)
82
+ const upload = await uploadChatFile(workspaceId, input.file ?? input.path)
83
+ return prepareAttachment(upload, `/api/workspaces/${workspaceId}/uploads/${upload.id}`, {
84
+ source: input.source
85
+ })
86
+ })
87
+ )
88
+ )
89
+ }
90
+
91
+ export function prepareDraftAttachments(
92
+ attachments: readonly StagedAttachment[]
93
+ ): PreparedAttachments {
94
+ return collectPreparedAttachments(
95
+ attachments.flatMap(attachment => {
96
+ if (attachment.kind === 'text') return [prepareAttachment(attachment)]
97
+ if (!attachment.upload) return []
98
+ return [
99
+ prepareAttachment(
100
+ { ...attachment.upload, filename: attachment.label, mediaType: attachment.mediaType },
101
+ attachment.previewUrl,
102
+ {
103
+ source: attachment.source,
104
+ purpose: attachment.kind === 'drawing' ? attachment.purpose : undefined
105
+ }
106
+ )
107
+ ]
108
+ })
109
+ )
110
+ }
15
111
 
16
112
  // Whether this send owns what the user has staged in the composer. Only a send
17
113
  // FROM the composer does. An applet's message is not the message the user is
18
114
  // building, so it must neither carry files they staged for their own message
19
115
  // nor clear ones still uploading out from under them.
20
116
  export function ownsComposerAttachments(options?: ChatSendOptions): boolean {
21
- return !options?.applet
117
+ return !options?.applet && !options?.preparedAttachments
22
118
  }
23
119
 
24
120
  // The fully-uploaded attachments this send should carry — none for a send that
@@ -27,65 +123,10 @@ export function attachmentsForSend(
27
123
  workspaceId: string,
28
124
  sessionId: string | null,
29
125
  options?: ChatSendOptions
30
- ): ChatAttachment[] {
126
+ ): StagedAttachment[] {
31
127
  if (!ownsComposerAttachments(options)) return []
32
128
  const pending = liveStore.getState().attachments[attachmentKey(workspaceId, sessionId)] ?? []
33
- return pending.filter(a => a.status === 'ready' && a.upload)
34
- }
35
-
36
- export function attachmentPartsForOptimisticTurn(attachments: readonly ChatAttachment[]): Part[] {
37
- return attachments.map(attachment => {
38
- if (attachment.upload?.kind === 'image' && attachment.previewUrl) {
39
- return {
40
- type: 'file',
41
- mediaType: attachment.mediaType,
42
- url: attachment.previewUrl,
43
- filename: attachment.name
44
- }
45
- }
46
- return {
47
- type: 'file',
48
- mediaType: attachment.mediaType,
49
- url: '',
50
- filename: attachment.name
51
- }
52
- })
53
- }
54
-
55
- export function withAttachmentDirectives(
56
- options: ChatSendOptions | undefined,
57
- attachments: readonly ChatAttachment[]
58
- ): ChatSendOptions | undefined {
59
- if (!ownsComposerAttachments(options)) return options
60
- const annotations: string[] = []
61
- const sketches: string[] = []
62
- let imagePosition = 0
63
- for (const attachment of attachments) {
64
- if (attachment.upload?.kind !== 'image') continue
65
- imagePosition += 1
66
- if (attachment.kind === 'drawing' && attachment.purpose === 'annotation') {
67
- annotations.push(`${imagePosition}. ${JSON.stringify(attachment.sourceTab)}`)
68
- }
69
- if (attachment.kind === 'drawing' && attachment.purpose === 'sketch') {
70
- sketches.push(`${imagePosition}. ${JSON.stringify(attachment.sourceTab)}`)
71
- }
72
- }
73
- if (annotations.length === 0 && sketches.length === 0) return options
74
-
75
- const directives = [...(options?.directives ?? [])]
76
- if (annotations.length > 0) {
77
- directives.push(`Annotation attachment sources in attachment order: ${annotations.join('; ')}.`)
78
- }
79
- if (sketches.length > 0) {
80
- directives.push(
81
- `Sketch attachment sources in attachment order: ${sketches.join('; ')}. Each sketch shows the intended layout of a new view.`
82
- )
83
- }
84
-
85
- return {
86
- ...options,
87
- directives
88
- }
129
+ return pending.filter(a => a.kind === 'text' || (a.status === 'ready' && a.upload))
89
130
  }
90
131
 
91
132
  type StartOptimisticTurnInput = {
@@ -1,41 +1,8 @@
1
+ import type { StagedAttachment, StagedAttachmentPatch } from './composer/attachments/types'
1
2
  import { useStore } from 'zustand'
2
3
  import { createStore } from 'zustand/vanilla'
3
4
 
4
- import type {
5
- PreviewBlock,
6
- PreviewFrame,
7
- SessionActivity,
8
- UploadInfo,
9
- WorkspaceTabId
10
- } from '@/lib/types'
11
-
12
- // One composer attachment, tracked per session until the message is sent. A
13
- // file uploads as soon as it's added (drop/paste/pick); an annotation stays a
14
- // local `draft` while it's being drawn and uploads once when the drawing
15
- // session ends. `status` reflects that lifecycle, and `upload` holds the server
16
- // handle once ready. `previewUrl` is a local object URL for image thumbnails
17
- // (revoked on remove/clear).
18
- type ChatAttachmentBase = {
19
- localId: string
20
- name: string
21
- mediaType: string
22
- previewUrl?: string
23
- status: 'draft' | 'uploading' | 'ready' | 'error'
24
- upload?: UploadInfo
25
- error?: string
26
- }
27
-
28
- export type DrawingPurpose = 'annotation' | 'sketch'
29
-
30
- export type ChatAttachment = ChatAttachmentBase &
31
- (
32
- | { kind: 'file'; purpose?: never; sourceTab?: never }
33
- | { kind: 'drawing'; purpose: DrawingPurpose; sourceTab: WorkspaceTabId }
34
- )
35
-
36
- type ChatAttachmentPatch = Partial<
37
- Pick<ChatAttachmentBase, 'name' | 'mediaType' | 'previewUrl' | 'status' | 'upload' | 'error'>
38
- >
5
+ import type { PreviewBlock, PreviewFrame, SessionActivity } from '@/lib/types'
39
6
 
40
7
  // App-level ephemeral chat state — the bits that are *pushed* from the server
41
8
  // over the WebSocket and can't be re-fetched as request/response data:
@@ -121,7 +88,7 @@ export type LiveStore = {
121
88
  previews: Record<string, LivePreview>
122
89
  // Composer attachments are per chat, survive composer remounts, and clear on
123
90
  // send. Draft text is workspace-local persisted UI state (client/store/ui).
124
- attachments: Record<string, ChatAttachment[]>
91
+ attachments: Record<string, StagedAttachment[]>
125
92
 
126
93
  setActivity: (workspaceId: string, sessionId: string, value: SessionActivity) => void
127
94
  // Authoritative reconcile from a server `status_snapshot`: exactly the listed
@@ -131,16 +98,12 @@ export type LiveStore = {
131
98
  sessions: { workspaceId: string; sessionId: string; activity: SessionActivity }[]
132
99
  ) => void
133
100
  setError: (workspaceId: string, sessionId: string, message: string | null) => void
134
- addAttachments: (workspaceId: string, sessionId: string | null, items: ChatAttachment[]) => void
135
- updateAttachment: (
136
- workspaceId: string,
137
- sessionId: string | null,
138
- localId: string,
139
- patch: ChatAttachmentPatch
140
- ) => void
141
- removeAttachment: (workspaceId: string, sessionId: string | null, localId: string) => void
101
+ addAttachments: (workspaceId: string, sessionId: string | null, items: StagedAttachment[]) => void
102
+ updateAttachment: (workspaceId: string, localId: string, patch: StagedAttachmentPatch) => void
103
+ removeAttachment: (workspaceId: string, localId: string) => void
142
104
  clearAttachments: (workspaceId: string, sessionId: string | null) => void
143
- renameSession: (workspaceId: string, from: string, to: string) => void
105
+ // `null` assigns the new-chat draft its first session id.
106
+ renameSession: (workspaceId: string, from: string | null, to: string) => void
144
107
 
145
108
  // Upsert a preview snapshot (last write wins — blocks are cumulative).
146
109
  setPreview: (frame: Omit<PreviewFrame, 'type'>) => void
@@ -156,6 +119,19 @@ export type LiveStore = {
156
119
  sweepPreviews: (maxAgeMs: number, now: number) => void
157
120
  }
158
121
 
122
+ // Stable IDs keep asynchronous attachment work attached to a renamed session.
123
+ export function findAttachment(
124
+ attachments: LiveStore['attachments'],
125
+ workspaceId: string,
126
+ localId: string
127
+ ) {
128
+ for (const [key, items] of Object.entries(attachments)) {
129
+ if (!key.startsWith(`${workspaceId}:`)) continue
130
+ const attachment = items.find(item => item.localId === localId)
131
+ if (attachment) return { key, attachment }
132
+ }
133
+ }
134
+
159
135
  export const liveStore = createStore<LiveStore>()(set => ({
160
136
  activity: {},
161
137
  errors: {},
@@ -224,30 +200,35 @@ export const liveStore = createStore<LiveStore>()(set => ({
224
200
  return { attachments: { ...s.attachments, [k]: [...(s.attachments[k] ?? []), ...items] } }
225
201
  }),
226
202
 
227
- updateAttachment: (workspaceId, sessionId, localId, patch) =>
203
+ updateAttachment: (workspaceId, localId, patch) =>
228
204
  set(s => {
229
- const k = attachmentKey(workspaceId, sessionId)
205
+ const found = findAttachment(s.attachments, workspaceId, localId)
206
+ if (!found) return {}
207
+ const { key: k, attachment: target } = found
230
208
  const list = s.attachments[k]
231
- if (!list) return {}
232
- const target = list.find(attachment => attachment.localId === localId)
233
- if (target?.previewUrl && 'previewUrl' in patch && patch.previewUrl !== target.previewUrl) {
209
+ if (
210
+ target.kind !== 'text' &&
211
+ target.previewUrl &&
212
+ 'previewUrl' in patch &&
213
+ patch.previewUrl !== target.previewUrl
214
+ ) {
234
215
  URL.revokeObjectURL(target.previewUrl)
235
216
  }
236
217
  return {
237
218
  attachments: {
238
219
  ...s.attachments,
239
- [k]: list.map(a => (a.localId === localId ? { ...a, ...patch } : a))
220
+ [k]: list.map(a => (a.localId === localId && a.kind !== 'text' ? { ...a, ...patch } : a))
240
221
  }
241
222
  }
242
223
  }),
243
224
 
244
- removeAttachment: (workspaceId, sessionId, localId) =>
225
+ removeAttachment: (workspaceId, localId) =>
245
226
  set(s => {
246
- const k = attachmentKey(workspaceId, sessionId)
227
+ const found = findAttachment(s.attachments, workspaceId, localId)
228
+ if (!found) return {}
229
+ const { key: k, attachment: target } = found
247
230
  const list = s.attachments[k]
248
- if (!list) return {}
249
- const target = list.find(a => a.localId === localId)
250
- if (target?.previewUrl) URL.revokeObjectURL(target.previewUrl)
231
+ if (target.kind !== 'text' && target.previewUrl) URL.revokeObjectURL(target.previewUrl)
251
232
  return { attachments: { ...s.attachments, [k]: list.filter(a => a.localId !== localId) } }
252
233
  }),
253
234
 
@@ -255,7 +236,7 @@ export const liveStore = createStore<LiveStore>()(set => ({
255
236
  set(s => {
256
237
  const k = attachmentKey(workspaceId, sessionId)
257
238
  for (const a of s.attachments[k] ?? []) {
258
- if (a.previewUrl) URL.revokeObjectURL(a.previewUrl)
239
+ if (a.kind !== 'text' && a.previewUrl) URL.revokeObjectURL(a.previewUrl)
259
240
  }
260
241
  const next = { ...s.attachments }
261
242
  delete next[k]
@@ -264,7 +245,7 @@ export const liveStore = createStore<LiveStore>()(set => ({
264
245
 
265
246
  renameSession: (workspaceId, from, to) =>
266
247
  set(s => {
267
- const fromKey = key(workspaceId, from)
248
+ const fromKey = attachmentKey(workspaceId, from)
268
249
  const toKey = key(workspaceId, to)
269
250
  const activity = { ...s.activity }
270
251
  const errors = { ...s.errors }
@@ -289,7 +270,17 @@ export const liveStore = createStore<LiveStore>()(set => ({
289
270
  previews[id] = { ...p, sessionId: to }
290
271
  }
291
272
  }
292
- return { activity, errors, previews }
273
+ // Upload completions use stable attachment IDs, so every draft item can
274
+ // follow the chat through both temporary and provider session IDs.
275
+ let attachments = s.attachments
276
+ if (fromKey !== toKey && attachments[fromKey]) {
277
+ attachments = {
278
+ ...attachments,
279
+ [toKey]: [...(attachments[toKey] ?? []), ...attachments[fromKey]]
280
+ }
281
+ delete attachments[fromKey]
282
+ }
283
+ return { activity, errors, previews, attachments }
293
284
  })
294
285
  }))
295
286