moi-computer 0.3.0 → 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 (57) 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 -38
  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-fjksw6xf.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/adapter.ts +32 -0
  43. package/server/harness/codex/client.ts +36 -1
  44. package/server/harness/codex/index.ts +3 -0
  45. package/server/harness/openclaw/discovery.ts +139 -6
  46. package/server/harness/openclaw/gateway.ts +40 -18
  47. package/server/harness/openclaw/index.ts +4 -1
  48. package/server/harness/types.ts +15 -0
  49. package/server/layout.ts +81 -51
  50. package/server/scratchpad-assets.ts +41 -6
  51. package/server/scratchpad.ts +30 -0
  52. package/server/views.ts +5 -0
  53. package/server/web.ts +6 -0
  54. package/server/widgets.ts +23 -2
  55. package/workspace/.claude/skills/moi-workspace/SKILL.md +24 -0
  56. package/dist/chunk-4z52b2av.css +0 -1
  57. package/dist/chunk-y82s1jxm.js +0 -61
@@ -48,7 +48,9 @@ function WorkspaceLoader({ id }: WorkspaceRouteProps) {
48
48
  useWorkspaceEvent(event => {
49
49
  if (event.type === 'theme:updated' || event.type === 'workspace:updated') {
50
50
  queryClient.invalidateQueries({ queryKey: workspaceKeys.layout(id) })
51
- } else if (event.type === 'widget-layout:updated') {
51
+ } else if (event.type === 'widget-layout:updated' || event.type === 'widget:updated') {
52
+ // widget:updated too: a rebundle bumps the widget's content `tag`, and
53
+ // the thumbnail invalidation hook reads it off this query.
52
54
  queryClient.invalidateQueries({ queryKey: workspaceKeys.widgets(id) })
53
55
  } else if (event.type === 'view-layout:updated') {
54
56
  queryClient.invalidateQueries({ queryKey: workspaceKeys.views(id) })
@@ -0,0 +1,61 @@
1
+ import type { ComponentProps, RefObject } from 'react'
2
+
3
+ import { cn } from '@/client/lib/cn'
4
+
5
+ type ComposerProps = Omit<ComponentProps<'form'>, 'ref'> & {
6
+ composerRef: RefObject<HTMLTextAreaElement | null>
7
+ }
8
+
9
+ export function Composer({
10
+ composerRef,
11
+ className,
12
+ onMouseDown,
13
+ children,
14
+ ...props
15
+ }: ComposerProps) {
16
+ return (
17
+ <form
18
+ {...props}
19
+ onMouseDown={event => {
20
+ onMouseDown?.(event)
21
+ if (event.defaultPrevented) return
22
+ if (event.target instanceof HTMLElement && event.target.closest('button')) return
23
+ event.preventDefault()
24
+ composerRef.current?.focus()
25
+ }}
26
+ className={cn(
27
+ 'flex w-full max-w-(--chat-max-container) 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',
28
+ className
29
+ )}
30
+ >
31
+ {children}
32
+ </form>
33
+ )
34
+ }
35
+
36
+ type ComposerTextareaProps = Omit<ComponentProps<'textarea'>, 'ref'> & {
37
+ textareaRef: RefObject<HTMLTextAreaElement | null>
38
+ }
39
+
40
+ export function ComposerTextarea({ textareaRef, className, ...props }: ComposerTextareaProps) {
41
+ return (
42
+ <textarea
43
+ {...props}
44
+ ref={textareaRef}
45
+ className={cn(
46
+ 'field-sizing-content max-h-40 w-full resize-none bg-transparent px-2 py-1 text-sm leading-relaxed outline-none placeholder:text-muted-foreground disabled:opacity-50',
47
+ className
48
+ )}
49
+ />
50
+ )
51
+ }
52
+
53
+ type ComposerFooterProps = ComponentProps<'div'>
54
+
55
+ export function ComposerFooter({ className, children, ...props }: ComposerFooterProps) {
56
+ return (
57
+ <div {...props} className={cn('flex items-center justify-end gap-1.5', className)}>
58
+ {children}
59
+ </div>
60
+ )
61
+ }
@@ -64,7 +64,7 @@ function DropdownMenuLabel({
64
64
  data-slot="dropdown-menu-label"
65
65
  data-inset={inset}
66
66
  className={cn(
67
- 'px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7',
67
+ 'px-2 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7',
68
68
  className
69
69
  )}
70
70
  {...props}
@@ -87,7 +87,7 @@ function DropdownMenuItem({
87
87
  data-inset={inset}
88
88
  data-variant={variant}
89
89
  className={cn(
90
- "group/dropdown-menu-item relative flex cursor-default items-center gap-2 rounded-xs px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
90
+ "group/dropdown-menu-item relative flex cursor-default items-center gap-2 rounded-xs px-2 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
91
91
  className
92
92
  )}
93
93
  {...props}
@@ -112,7 +112,7 @@ function DropdownMenuSubTrigger({
112
112
  data-slot="dropdown-menu-sub-trigger"
113
113
  data-inset={inset}
114
114
  className={cn(
115
- "flex cursor-default items-center gap-2 rounded-xs px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
115
+ "flex cursor-default items-center gap-2 rounded-xs px-2 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
116
116
  className
117
117
  )}
118
118
  {...props}
@@ -2,15 +2,22 @@ import { Component, type ErrorInfo, type ReactNode } from 'react'
2
2
 
3
3
  import { IconAlertTriangle } from '@tabler/icons-react'
4
4
 
5
- type Props = {
5
+ import { reportAppletError } from '@/client/features/applets/applet-log'
6
+ import type { AppletKind } from '@/lib/types'
7
+
8
+ type WidgetErrorBoundaryProps = {
6
9
  name: string
10
+ // Applet attribution for the error journal (docs/self-correction.md). The
11
+ // boundary wraps both widgets (WidgetShell) and views (WorkspaceScreen).
12
+ kind: AppletKind
13
+ workspaceId: string
7
14
  resetKey: number
8
15
  children: ReactNode
9
16
  }
10
17
 
11
18
  type State = { error: Error | null }
12
19
 
13
- export class WidgetErrorBoundary extends Component<Props, State> {
20
+ export class WidgetErrorBoundary extends Component<WidgetErrorBoundaryProps, State> {
14
21
  state: State = { error: null }
15
22
 
16
23
  static getDerivedStateFromError(error: Error): State {
@@ -19,9 +26,18 @@ export class WidgetErrorBoundary extends Component<Props, State> {
19
26
 
20
27
  componentDidCatch(error: Error, info: ErrorInfo) {
21
28
  console.error(`[widget:${this.props.name}]`, error, info.componentStack)
29
+ // Journal the crash so `moi debug logs` can surface it to the agent — the
30
+ // console line above dies in a console nobody reads.
31
+ reportAppletError(this.props.workspaceId, {
32
+ source: 'render',
33
+ kind: this.props.kind,
34
+ name: this.props.name,
35
+ message: error.message || String(error),
36
+ stack: [error.stack, info.componentStack].filter(Boolean).join('\n')
37
+ })
22
38
  }
23
39
 
24
- componentDidUpdate(prev: Props) {
40
+ componentDidUpdate(prev: WidgetErrorBoundaryProps) {
25
41
  if (prev.resetKey !== this.props.resetKey && this.state.error) {
26
42
  this.setState({ error: null })
27
43
  }
@@ -2,6 +2,7 @@ import { AnimatePresence, motion } from 'motion/react'
2
2
 
3
3
  import { AppletMount } from '@/client/features/applets/AppletMount'
4
4
  import { useWidget } from '@/client/features/applets/useApplet'
5
+ import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
5
6
 
6
7
  import { WidgetErrorBoundary } from './WidgetErrorBoundary'
7
8
 
@@ -10,6 +11,7 @@ type WidgetShellProps = {
10
11
  }
11
12
 
12
13
  export function WidgetShell({ name }: WidgetShellProps) {
14
+ const workspaceId = useWorkspaceId()
13
15
  const widget = useWidget(name)
14
16
 
15
17
  return (
@@ -23,7 +25,12 @@ export function WidgetShell({ name }: WidgetShellProps) {
23
25
  exit={{ opacity: 0, filter: 'blur(4px)' }}
24
26
  transition={{ duration: 0.45, ease: 'easeInOut' }}
25
27
  >
26
- <WidgetErrorBoundary name={name} resetKey={widget.version}>
28
+ <WidgetErrorBoundary
29
+ name={name}
30
+ kind="widget"
31
+ workspaceId={workspaceId}
32
+ resetKey={widget.version}
33
+ >
27
34
  <AppletMount segment="widgets" name={name} version={widget.version}>
28
35
  <widget.Component />
29
36
  </AppletMount>
@@ -0,0 +1,100 @@
1
+ import type { AppletClientError, AppletKind } from '@/lib/types'
2
+
3
+ // Fire-and-forget reporter for browser-side applet errors — the client half of
4
+ // the applet error journal (docs/self-correction.md). Failures only the user's
5
+ // tab sees (module load failures, render crashes, window errors attributed to
6
+ // a bundle) are POSTed into the workspace journal so `moi debug logs` can show
7
+ // them to the agent. Always on: when the user says "it's broken", the crash
8
+ // their tab saw five minutes ago is already on record.
9
+ //
10
+ // Reporting must never hurt the app: fetch errors are swallowed, and two
11
+ // throttles bound the network chatter. The per-error cooldown collapses a
12
+ // crash loop of the SAME error into one POST per window; the global cap
13
+ // bounds the total regardless of message — an error whose text varies every
14
+ // occurrence (timestamps, ids) would defeat key-based cooldown and server
15
+ // dedup alike, and a tight throw loop must not become a POST-per-frame storm.
16
+ // Drops are silent: the journal is best-effort diagnostics, not telemetry.
17
+ const COOLDOWN_MS = 5_000
18
+ const lastSent = new Map<string, number>()
19
+
20
+ const RATE_WINDOW_MS = 60_000
21
+ const RATE_MAX_PER_WINDOW = 30
22
+ let rateWindowStart = 0
23
+ let rateCount = 0
24
+
25
+ export function reportAppletError(workspaceId: string, event: AppletClientError): void {
26
+ const now = Date.now()
27
+
28
+ const key = [workspaceId, event.source, event.kind, event.name, event.message].join('\0')
29
+ const last = lastSent.get(key)
30
+ if (last !== undefined && now - last < COOLDOWN_MS) return
31
+
32
+ if (now - rateWindowStart >= RATE_WINDOW_MS) {
33
+ rateWindowStart = now
34
+ rateCount = 0
35
+ }
36
+ if (rateCount >= RATE_MAX_PER_WINDOW) return
37
+ rateCount++
38
+
39
+ lastSent.set(key, now)
40
+ // Bound the cooldown map: drop the oldest half if it ever balloons.
41
+ if (lastSent.size > 256) {
42
+ for (const k of [...lastSent.keys()].slice(0, 128)) lastSent.delete(k)
43
+ }
44
+ void fetch(`/api/workspaces/${workspaceId}/applet-log`, {
45
+ method: 'POST',
46
+ headers: { 'Content-Type': 'application/json' },
47
+ body: JSON.stringify({ events: [event] })
48
+ }).catch(() => {})
49
+ }
50
+
51
+ // Attribute a window-level error to an applet by a bundle URL: applet bundles
52
+ // load from `/api/workspaces/<id>/(widgets|views)/<name>/…`, so any reference
53
+ // to one pins the error to that applet — and carries the workspace id along.
54
+ // Host-app URLs never match; their errors are not the journal's business.
55
+ // Matched against ErrorEvent.filename (a bare URL) and stack-trace text, where
56
+ // segments stop at `/`, whitespace, or `)` because stack frame formats differ
57
+ // per browser (Chrome parenthesizes URLs, Firefox uses `fn@url`).
58
+ const BUNDLE_URL_RE = /\/api\/workspaces\/([^/\s)]+)\/(widgets|views)\/([^/\s)]+)\//
59
+
60
+ type BundleRef = { workspaceId: string; kind: AppletKind; name: string }
61
+
62
+ // Exported for tests.
63
+ export function matchBundleUrl(text: string | undefined): BundleRef | null {
64
+ if (!text) return null
65
+ const m = BUNDLE_URL_RE.exec(text)
66
+ if (!m) return null
67
+ return { workspaceId: m[1], kind: m[2] === 'widgets' ? 'widget' : 'view', name: m[3] }
68
+ }
69
+
70
+ let installed = false
71
+
72
+ // Catch errors that escape React entirely — event handlers, async effects,
73
+ // unawaited promises — which no error boundary sees. Installed once at startup.
74
+ export function installAppletErrorHook(): void {
75
+ if (installed) return
76
+ installed = true
77
+
78
+ const report = (ref: BundleRef | null, raw: unknown, fallbackMessage?: string) => {
79
+ const err = raw instanceof Error ? raw : null
80
+ const stack = err?.stack ?? ''
81
+ const hit = ref ?? matchBundleUrl(stack)
82
+ if (!hit) return
83
+ reportAppletError(hit.workspaceId, {
84
+ source: 'window',
85
+ kind: hit.kind,
86
+ name: hit.name,
87
+ message: err?.message || fallbackMessage || String(raw),
88
+ ...(stack ? { stack } : {})
89
+ })
90
+ }
91
+
92
+ // Fast path for 'error' events: ErrorEvent.filename is the structured URL of
93
+ // the script whose top frame threw — no stack-text parsing, no per-browser
94
+ // format quirks, and it works even for throws with no usable stack
95
+ // (`throw 'string'`). The stack scan remains the fallback (e.g. an applet
96
+ // handler that threw inside vendor code, where filename names the vendor
97
+ // chunk) and the only path for promise rejections, which carry no filename.
98
+ window.addEventListener('error', e => report(matchBundleUrl(e.filename), e.error, e.message))
99
+ window.addEventListener('unhandledrejection', e => report(null, e.reason))
100
+ }
@@ -9,8 +9,10 @@ import {
9
9
  invalidateApplet,
10
10
  setCachedApplet
11
11
  } from '@/client/features/applets/applet-cache'
12
+ import { reportAppletError } from '@/client/features/applets/applet-log'
12
13
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
13
14
  import { type WorkspaceEvent, useWorkspaceEvent } from '@/client/runtime/useWorkspaceEvents'
15
+ import type { AppletKind } from '@/lib/types'
14
16
 
15
17
  type AppletState =
16
18
  | { status: 'loading'; version: number }
@@ -21,19 +23,22 @@ type AppletState =
21
23
  // MEI events tell it to reload. Everything else — dynamic import, caching,
22
24
  // cache-busting — is shared. An applet is an agent-authored UI unit loaded as an
23
25
  // ESM module and mounted into the workspace.
24
- type AppletKind = {
26
+ type AppletKindSpec = {
27
+ kind: AppletKind
25
28
  segment: AppletSegment
26
29
  // True when this MEI event means the named applet should cache-bust + reload.
27
30
  shouldReload: (event: WorkspaceEvent, name: string) => boolean
28
31
  }
29
32
 
30
- const WIDGET_KIND: AppletKind = {
33
+ const WIDGET_KIND: AppletKindSpec = {
34
+ kind: 'widget',
31
35
  segment: 'widgets',
32
36
  shouldReload: (e, name) =>
33
37
  (e.type === 'widget:updated' && e.name === name) || e.type === 'widgets:refresh'
34
38
  }
35
39
 
36
- const VIEW_KIND: AppletKind = {
40
+ const VIEW_KIND: AppletKindSpec = {
41
+ kind: 'view',
37
42
  segment: 'views',
38
43
  shouldReload: (e, name) => e.type === 'view:updated' && e.name === name
39
44
  }
@@ -59,7 +64,7 @@ function loadApplet(
59
64
  return promise
60
65
  }
61
66
 
62
- function useApplet(kind: AppletKind, name: string): AppletState {
67
+ function useApplet(kind: AppletKindSpec, name: string): AppletState {
63
68
  const workspaceId = useWorkspaceId()
64
69
  const [state, setState] = useState<AppletState>({ status: 'loading', version: 0 })
65
70
 
@@ -69,10 +74,19 @@ function useApplet(kind: AppletKind, name: string): AppletState {
69
74
  .then(Component =>
70
75
  setState(prev => ({ status: 'ready', Component, version: prev.version + 1 }))
71
76
  )
72
- .catch(err =>
77
+ .catch(err => {
78
+ // Journal the load failure so `moi debug logs` can surface it to the
79
+ // agent — otherwise only this tab ever sees it (docs/self-correction.md).
80
+ reportAppletError(workspaceId, {
81
+ source: 'load',
82
+ kind: kind.kind,
83
+ name,
84
+ message: String(err),
85
+ ...(err instanceof Error && err.stack ? { stack: err.stack } : {})
86
+ })
73
87
  setState(prev => ({ status: 'error', error: String(err), version: prev.version + 1 }))
74
- )
75
- }, [kind.segment, workspaceId, name])
88
+ })
89
+ }, [kind, workspaceId, name])
76
90
 
77
91
  useEffect(() => {
78
92
  load()
@@ -9,6 +9,7 @@ import {
9
9
  IconX
10
10
  } from '@tabler/icons-react'
11
11
 
12
+ import { Composer, ComposerFooter, ComposerTextarea } from '@/client/components/shared/Composer'
12
13
  import { cn } from '@/client/lib/cn'
13
14
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
14
15
  import { uploadFiles } from '@/client/features/chat/uploads'
@@ -89,16 +90,12 @@ export function ChatComposer({ composerRef, onSend, onStop, processing }: ChatCo
89
90
  }
90
91
 
91
92
  return (
92
- <form
93
+ <Composer
94
+ composerRef={composerRef}
93
95
  onSubmit={e => {
94
96
  e.preventDefault()
95
97
  send()
96
98
  }}
97
- onMouseDown={e => {
98
- if (e.target instanceof HTMLElement && e.target.closest('button')) return
99
- e.preventDefault()
100
- composerRef.current?.focus()
101
- }}
102
99
  onDragOver={e => {
103
100
  if (!e.dataTransfer.types.includes('Files')) return
104
101
  e.preventDefault()
@@ -115,10 +112,7 @@ export function ChatComposer({ composerRef, onSend, onStop, processing }: ChatCo
115
112
  setDragOver(false)
116
113
  addFiles(Array.from(e.dataTransfer.files))
117
114
  }}
118
- className={cn(
119
- 'flex w-full max-w-(--chat-max-container) 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',
120
- dragOver && 'ring-2 ring-ring/60'
121
- )}
115
+ className={cn(dragOver && 'ring-2 ring-ring/60')}
122
116
  >
123
117
  {attachments.length > 0 && (
124
118
  <div className="flex flex-wrap gap-2 px-1 pt-1 pb-0.5">
@@ -134,8 +128,8 @@ export function ChatComposer({ composerRef, onSend, onStop, processing }: ChatCo
134
128
  </div>
135
129
  )}
136
130
 
137
- <textarea
138
- ref={composerRef}
131
+ <ComposerTextarea
132
+ textareaRef={composerRef}
139
133
  id="chat-input"
140
134
  name="message"
141
135
  value={value}
@@ -154,9 +148,8 @@ export function ChatComposer({ composerRef, onSend, onStop, processing }: ChatCo
154
148
  }}
155
149
  placeholder={processing ? 'Queue a follow-up' : 'Do anything'}
156
150
  rows={1}
157
- className="field-sizing-content max-h-40 w-full resize-none bg-transparent px-2 py-1 text-sm leading-relaxed outline-none placeholder:text-muted-foreground disabled:opacity-50"
158
151
  />
159
- <div className="flex items-center justify-end gap-1.5">
152
+ <ComposerFooter>
160
153
  <input
161
154
  ref={fileRef}
162
155
  type="file"
@@ -187,8 +180,8 @@ export function ChatComposer({ composerRef, onSend, onStop, processing }: ChatCo
187
180
  <IconArrowUp stroke={1.5} />
188
181
  </Button>
189
182
  )}
190
- </div>
191
- </form>
183
+ </ComposerFooter>
184
+ </Composer>
192
185
  )
193
186
  }
194
187
 
@@ -3,9 +3,13 @@ import { memo, useState } from 'react'
3
3
  import { IconChevronDown } from '@tabler/icons-react'
4
4
 
5
5
  import { useSaveThreadConfig, useThreadConfig, useWorkspaceModels } from './api'
6
+ import {
7
+ resolveDisplayedEffort,
8
+ reverseEffortLevels,
9
+ sortModelsByProviderOrder
10
+ } from './model-order'
6
11
  import { useWorkspaceLayoutCtx } from '@/client/features/workspace/WorkspaceLayoutContext'
7
12
  import { useLive } from '@/client/features/chat/chat-store'
8
- import type { Model } from '@/lib/types'
9
13
 
10
14
  import { Button } from '@/client/components/ui/button'
11
15
  import {
@@ -39,31 +43,8 @@ function effortLabel(level: string): string {
39
43
  return level === 'xhigh' ? 'Extra' : capitalize(level)
40
44
  }
41
45
 
42
- // Output price ($/Mtok) parsed from a model's "$in/$out per Mtok" blurb.
43
- function outputPrice(description?: string): number {
44
- const m = description?.match(/\$\d+(?:\.\d+)?\s*\/\s*\$(\d+(?:\.\d+)?)\s*per Mtok/)
45
- return m ? Number(m[1]) : -1
46
- }
47
-
48
- // Canonical wire id without a context-variant suffix, e.g.
49
- // 'claude-opus-4-8[1m]' → 'claude-opus-4-8'. Groups a model with its variants.
50
- function familyOf(m: Model): string | undefined {
51
- return m.resolvedModel?.replace(/\[[^\]]*\]$/, '')
52
- }
53
-
54
- // Sort key ordering models most-capable-first (Fable → Opus → Sonnet → Haiku)
55
- // from price alone, no hardcoded names. A bare alias that omits its price (e.g.
56
- // plain 'opus') borrows a same-family variant's price ('opus[1m]'s $/Mtok) so
57
- // the two group together. Unpriced models (OpenClaw) return -1 → sort last,
58
- // keeping their original order since they're all equal.
59
- function sortPrice(m: Model, all: Model[]): number {
60
- const own = outputPrice(m.description)
61
- if (own >= 0) return own
62
- const family = familyOf(m)
63
- const sibling = all.find(
64
- x => x !== m && familyOf(x) === family && outputPrice(x.description) >= 0
65
- )
66
- return sibling ? outputPrice(sibling.description) : -1
46
+ type ModelPickerProps = {
47
+ scope?: 'active-chat' | 'workspace'
67
48
  }
68
49
 
69
50
  // Model selector for the chat composer. Renders the workspace's available
@@ -73,10 +54,11 @@ function sortPrice(m: Model, all: Model[]): number {
73
54
  // edits the workspace defaults, which seed the new thread. Both are sent with
74
55
  // each chat frame (see useChat); leaving them untouched runs on the SDK default.
75
56
  // Fast mode remains local-only for now.
76
- // Memoized (no props): it lives inside ChatInput, which re-renders on every
77
- // keystroke, so memo keeps the picker from re-rendering with it — it updates
78
- // only on its own store/query changes (active thread, models, layout).
79
- export const ModelPicker = memo(function ModelPicker() {
57
+ // The workspace scope gives new-chat surfaces such as the view builder the same
58
+ // defaults that their submit path reads. The active-chat scope persists per
59
+ // thread once one exists.
60
+ // Memoized because composer text changes should not re-render the picker.
61
+ export const ModelPicker = memo(function ModelPicker({ scope = 'active-chat' }: ModelPickerProps) {
80
62
  const { workspaceId, layout, setLayout } = useWorkspaceLayoutCtx()
81
63
  const { data } = useWorkspaceModels(workspaceId)
82
64
  // The SDK prepends a synthetic "default" entry ("Use the default model
@@ -85,15 +67,18 @@ export const ModelPicker = memo(function ModelPicker() {
85
67
  // "use default" row.
86
68
  const allModels = data?.models ?? []
87
69
  const defaultEntry = allModels.find(m => m.value === 'default')
88
- // Drop the "default" entry, then order by price descending. Array.sort is
89
- // stable, so same-price variants (Opus 1M vs standard) keep the SDK's order.
90
- const models = allModels
91
- .filter(m => m.value !== 'default')
92
- .sort((a, b) => sortPrice(b, allModels) - sortPrice(a, allModels))
70
+ const models = data
71
+ ? sortModelsByProviderOrder(
72
+ allModels.filter(model => model.value !== 'default'),
73
+ data.provider
74
+ )
75
+ : []
93
76
 
94
77
  // The active thread, if any. Its stored config is the source of truth; a new
95
78
  // chat (no active thread) falls back to — and edits — the workspace defaults.
96
- const activeSessionId = useLive(s => s.activeByWorkspace[workspaceId] ?? null)
79
+ const activeSessionId = useLive(s =>
80
+ scope === 'active-chat' ? (s.activeByWorkspace[workspaceId] ?? null) : null
81
+ )
97
82
  const threadCfg = useThreadConfig(workspaceId, activeSessionId).data
98
83
  const saveThreadCfg = useSaveThreadConfig(workspaceId)
99
84
  const [fastMode, setFastMode] = useState(false)
@@ -124,9 +109,10 @@ export const ModelPicker = memo(function ModelPicker() {
124
109
  ) ?? models[0]
125
110
  const current = persisted ?? defaultModel.value
126
111
  const model = models.find(m => m.value === current) ?? models[0]
127
- const effortLevels = model.supportsEffort ? (model.supportedEffortLevels ?? []) : []
128
- const currentEffort =
129
- selectedEffort && effortLevels.includes(selectedEffort) ? selectedEffort : effortLevels[0]
112
+ const effortLevels = reverseEffortLevels(
113
+ model.supportsEffort ? (model.supportedEffortLevels ?? []) : []
114
+ )
115
+ const currentEffort = resolveDisplayedEffort(effortLevels, selectedEffort)
130
116
  const showReasoning = effortLevels.length > 0
131
117
  // Fast mode is Claude-only (Opus); OpenClaw models never report supportsFastMode.
132
118
  const showFastMode = !!model.supportsFastMode
@@ -136,7 +122,7 @@ export const ModelPicker = memo(function ModelPicker() {
136
122
  <DropdownMenuTrigger
137
123
  render={
138
124
  <Button variant="ghost">
139
- <span className="font-normal text-foreground">
125
+ <span className="text-foreground">
140
126
  {headline(model.description) || model.displayName}
141
127
  </span>
142
128
  {currentEffort && (
@@ -72,6 +72,7 @@ export function reduceChatFrame(data: Record<string, unknown>, context: ChatFram
72
72
  queryClient?.removeQueries({ queryKey: workspaceKeys.threadConfig(workspaceId, from) })
73
73
  }
74
74
  queryClient?.invalidateQueries({ queryKey: workspaceKeys.sessions(workspaceId) })
75
+ queryClient?.invalidateQueries({ queryKey: workspaceKeys.preview(workspaceId) })
75
76
  return
76
77
  }
77
78
  if (data.type === 'workspace:switch') {
@@ -0,0 +1,47 @@
1
+ import type { Model, WorkspaceType } from '@/lib/types'
2
+
3
+ export const DEFAULT_EFFORT = 'high'
4
+
5
+ export const MODEL_ORDER = {
6
+ 'claude-code': [
7
+ 'claude-fable-5',
8
+ 'claude-opus-4-8',
9
+ 'claude-opus-4-8[1m]',
10
+ 'claude-sonnet-5',
11
+ 'claude-haiku-4-5-20251001'
12
+ ],
13
+ codex: [],
14
+ openclaw: []
15
+ } as const satisfies Record<WorkspaceType, readonly string[]>
16
+
17
+ function modelOrderKey(model: Model): string {
18
+ return model.resolvedModel ?? model.value
19
+ }
20
+
21
+ export function reverseEffortLevels(levels: readonly string[]): string[] {
22
+ return [...levels].reverse()
23
+ }
24
+
25
+ export function resolveDisplayedEffort(
26
+ levels: readonly string[],
27
+ selectedEffort: string | undefined
28
+ ): string | undefined {
29
+ if (selectedEffort && levels.includes(selectedEffort)) return selectedEffort
30
+ if (levels.includes(DEFAULT_EFFORT)) return DEFAULT_EFFORT
31
+ return levels[0]
32
+ }
33
+
34
+ export function sortModelsByProviderOrder(models: Model[], provider: WorkspaceType): Model[] {
35
+ const configuredOrder: readonly string[] = MODEL_ORDER[provider]
36
+ const rank = new Map<string, number>(configuredOrder.map((model, index) => [model, index]))
37
+
38
+ return models
39
+ .map((model, index) => ({ model, index, rank: rank.get(modelOrderKey(model)) }))
40
+ .sort((a, b) => {
41
+ if (a.rank === undefined && b.rank === undefined) return a.index - b.index
42
+ if (a.rank === undefined) return -1
43
+ if (b.rank === undefined) return 1
44
+ return a.rank - b.rank || a.index - b.index
45
+ })
46
+ .map(({ model }) => model)
47
+ }
@@ -2,6 +2,7 @@ import { useCallback, useMemo } from 'react'
2
2
 
3
3
  import { useQueryClient } from '@tanstack/react-query'
4
4
 
5
+ import { workspaceKeys } from '@/client/api/workspace-keys'
5
6
  import { useSessionView, useThreadConfig, useWorkspaceModels } from '@/client/features/chat/api'
6
7
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
7
8
  import { useWorkspaceLayoutCtx } from '@/client/features/workspace/WorkspaceLayoutContext'
@@ -112,6 +113,9 @@ export function useChat() {
112
113
  stream,
113
114
  ...(ready.length > 0 ? { attachments: ready.map(a => a.upload!.id) } : {})
114
115
  })
116
+ if (isNew) {
117
+ qc.invalidateQueries({ queryKey: workspaceKeys.preview(workspaceId) })
118
+ }
115
119
  // Drop the thread's attachments now that they've been sent (revokes the
116
120
  // preview object URLs). Keyed by the pre-mint id, matching where they were
117
121
  // stored by the composer.