moi-computer 0.3.1-next.0 → 0.3.1-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/client/api/workspace-keys.ts +2 -2
  2. package/client/app/AppRouter.tsx +0 -2
  3. package/client/app/shell/SidebarLayout.tsx +3 -16
  4. package/client/assets/openai.svg +1 -3
  5. package/client/components/shared/Composer.tsx +53 -2
  6. package/client/components/ui/button.tsx +1 -1
  7. package/client/components/ui/tooltip.tsx +12 -15
  8. package/client/features/chat/ChatComposer.tsx +25 -15
  9. package/client/features/chat/ChatPanel.tsx +5 -2
  10. package/client/features/chat/MarkdownContent.tsx +20 -2
  11. package/client/features/chat/ModelPicker.tsx +5 -3
  12. package/client/features/chat/TurnView.tsx +2 -2
  13. package/client/features/chat/chat-frames.ts +13 -6
  14. package/client/features/chat/chat-send.ts +1 -1
  15. package/client/features/chat/chat-store.ts +22 -17
  16. package/client/features/chat/tool-group/ToolOutput.tsx +4 -12
  17. package/client/features/chat/tool-group/format.ts +0 -6
  18. package/client/features/chat/useChat.ts +11 -2
  19. package/client/features/connectors/McpServerCards.tsx +95 -0
  20. package/client/features/connectors/api.ts +0 -11
  21. package/client/features/home/HomePage.tsx +33 -28
  22. package/client/features/home/api.ts +24 -12
  23. package/client/features/home/workspace-presentation.tsx +17 -15
  24. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +243 -0
  25. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +95 -0
  26. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +230 -0
  27. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +35 -0
  28. package/client/features/home/workspace-setup/useWorkspaceImport.ts +61 -0
  29. package/client/features/settings/ConnectorsSettings.tsx +89 -0
  30. package/client/features/settings/SettingsLayout.tsx +2 -2
  31. package/client/features/settings/WorkspaceSettings.tsx +8 -4
  32. package/client/features/views/ViewBuilderTab.tsx +19 -15
  33. package/client/features/views/useViewBuilderActions.ts +1 -1
  34. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -4
  35. package/client/features/workspace/WorkspaceScreen.tsx +11 -3
  36. package/client/features/workspace/api.ts +19 -1
  37. package/client/features/workspace/moi-context.ts +85 -0
  38. package/client/main.tsx +7 -4
  39. package/dist/{chunk-cs8vbert.js → chunk-1dfbr7n2.js} +2 -2
  40. package/dist/chunk-339jds4x.js +15 -0
  41. package/dist/chunk-3xsvsnhr.css +1 -0
  42. package/dist/{chunk-zpxrb1ce.js → chunk-anqmsbjt.js} +2 -2
  43. package/dist/chunk-hbvfb6sk.js +63 -0
  44. package/dist/{chunk-kxmvv1ax.js → chunk-qwm5f6qk.js} +1 -1
  45. package/dist/{chunk-axszxe4c.js → chunk-sxbfh73c.js} +1 -1
  46. package/dist/chunk-yp4srgqt.js +10 -0
  47. package/dist/index.html +1 -1
  48. package/dist/openai-ep9ht2pq.svg +1 -0
  49. package/lib/ids.ts +15 -0
  50. package/lib/moi-context.ts +170 -0
  51. package/lib/types.ts +29 -11
  52. package/lib/view-builder-directives.ts +16 -0
  53. package/lib/workspace-types.ts +12 -0
  54. package/package.json +2 -1
  55. package/server/api.ts +92 -30
  56. package/server/harness/README.md +25 -9
  57. package/server/harness/claude-code/NOTES.md +20 -6
  58. package/server/harness/claude-code/adapter.ts +2 -2
  59. package/server/harness/claude-code/git-worktree.ts +32 -0
  60. package/server/harness/claude-code/index.ts +32 -12
  61. package/server/harness/claude-code/mcp.ts +16 -65
  62. package/server/harness/claude-code/models.ts +3 -0
  63. package/server/harness/claude-code/session.ts +196 -61
  64. package/server/harness/codex/NOTES.md +41 -11
  65. package/server/harness/codex/adapter.ts +21 -7
  66. package/server/harness/codex/client.ts +33 -17
  67. package/server/harness/codex/discovery.ts +114 -0
  68. package/server/harness/codex/index.ts +9 -5
  69. package/server/harness/codex/probe.ts +4 -2
  70. package/server/harness/codex/session.ts +57 -5
  71. package/server/harness/executable.ts +82 -0
  72. package/server/harness/openclaw/adapter.ts +8 -1
  73. package/server/harness/openclaw/index.ts +8 -14
  74. package/server/harness/openclaw/session.ts +50 -10
  75. package/server/harness/openclaw/strip.ts +2 -2
  76. package/server/harness/shell-path.ts +79 -0
  77. package/server/harness/types.ts +22 -5
  78. package/server/registry.ts +57 -12
  79. package/server/view-builders.ts +3 -2
  80. package/server/web.ts +24 -8
  81. package/server/workspace-import.ts +45 -0
  82. package/workspace/.claude/skills/moi-workspace/SKILL.md +3 -3
  83. package/client/features/connectors/ConnectorsPage.tsx +0 -92
  84. package/client/features/connectors/McpMenu.tsx +0 -145
  85. package/client/features/home/CreateWorkspaceDialog.tsx +0 -130
  86. package/client/features/home/CreateWorkspaceDialogSteps.tsx +0 -234
  87. package/dist/chunk-4vf1t6v1.js +0 -10
  88. package/dist/chunk-b3ynfk4g.js +0 -62
  89. package/dist/chunk-b4b276wx.js +0 -15
  90. package/dist/chunk-npwq6jmr.css +0 -1
  91. package/dist/openai-h13pza4b.svg +0 -3
  92. package/lib/view-builder-meta.ts +0 -35
@@ -4,6 +4,7 @@ import { useQueryClient } from '@tanstack/react-query'
4
4
 
5
5
  import { workspaceKeys } from '@/client/api/workspace-keys'
6
6
  import { useSessionView, useThreadConfig, useWorkspaceModels } from '@/client/features/chat/api'
7
+ import { useMoiUserMessageContext } from '@/client/features/workspace/moi-context'
7
8
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
8
9
  import { useWorkspaceLayoutCtx } from '@/client/features/workspace/WorkspaceLayoutContext'
9
10
  import { sendMessage } from '@/client/features/chat/chat-connection'
@@ -23,11 +24,17 @@ export function useChat() {
23
24
  const qc = useQueryClient()
24
25
  const { layout } = useWorkspaceLayoutCtx()
25
26
  const modelsData = useWorkspaceModels(workspaceId).data
27
+ // Snapshot of the workspace's ambient UI state + queued one-shot
28
+ // directives, taken when the message actually goes out.
29
+ const buildMoiContext = useMoiUserMessageContext()
26
30
 
27
31
  const activeSessionId = useLive(s => s.activeByWorkspace[workspaceId] ?? null)
28
- const processing = useLive(s =>
29
- activeSessionId ? (s.processing[`${workspaceId}:${activeSessionId}`] ?? false) : false
32
+ const activity = useLive(s =>
33
+ activeSessionId ? (s.activity[`${workspaceId}:${activeSessionId}`] ?? 'idle') : 'idle'
30
34
  )
35
+ // Only `running` shows the loader/Stop. `requires-action` (agent blocked on
36
+ // user input) deliberately renders like idle until it gets its own UI.
37
+ const processing = activity === 'running'
31
38
  const error = useLive(s =>
32
39
  activeSessionId ? (s.errors[`${workspaceId}:${activeSessionId}`] ?? null) : null
33
40
  )
@@ -111,6 +118,7 @@ export function useChat() {
111
118
  model,
112
119
  effort,
113
120
  stream,
121
+ context: buildMoiContext(),
114
122
  ...(ready.length > 0 ? { attachments: ready.map(a => a.upload!.id) } : {})
115
123
  })
116
124
  if (isNew) {
@@ -127,6 +135,7 @@ export function useChat() {
127
135
  qc,
128
136
  layout.selectedModel,
129
137
  layout.selectedEffort,
138
+ buildMoiContext,
130
139
  threadCfg?.model,
131
140
  threadCfg?.effort,
132
141
  modelsData
@@ -0,0 +1,95 @@
1
+ import type { ReactNode } from 'react'
2
+
3
+ import { IconAlertCircleFilled } from '@tabler/icons-react'
4
+
5
+ import { Skeleton } from '@/client/components/ui/skeleton'
6
+ import { IconMcp } from '@/client/features/connectors/IconMcp'
7
+ import { formatMcpServerName, getMcpIcon } from '@/client/features/connectors/mcp-icons'
8
+ import type { McpServer } from '@/lib/types'
9
+
10
+ function statusLabel(status: McpServer['status']): string {
11
+ if (status === 'needs-auth') return 'Needs auth'
12
+ return status[0].toUpperCase() + status.slice(1)
13
+ }
14
+
15
+ type McpServerIconProps = {
16
+ name: string
17
+ status: McpServer['status']
18
+ }
19
+
20
+ function McpServerIcon({ name, status }: McpServerIconProps) {
21
+ const icon = getMcpIcon(name)
22
+ const className = 'size-full rounded-sm ring-2 ring-background'
23
+
24
+ return (
25
+ <span className="relative size-10 shrink-0">
26
+ {icon ? (
27
+ <img src={icon} alt="" className={className} />
28
+ ) : (
29
+ <span className="flex size-full items-center justify-center rounded-sm bg-muted text-muted-foreground ring-2 ring-background">
30
+ <IconMcp className="size-5" />
31
+ </span>
32
+ )}
33
+ {status !== 'connected' && (
34
+ <IconAlertCircleFilled
35
+ aria-hidden="true"
36
+ size={16}
37
+ stroke={1.75}
38
+ className="absolute -top-1 -right-1 rounded-full bg-card text-amber-400"
39
+ />
40
+ )}
41
+ </span>
42
+ )
43
+ }
44
+
45
+ export function sortMcpServers(servers: McpServer[]): McpServer[] {
46
+ return [...servers].sort(
47
+ (a, b) => Number(b.status === 'connected') - Number(a.status === 'connected')
48
+ )
49
+ }
50
+
51
+ type McpServerCardProps = {
52
+ server: McpServer
53
+ }
54
+
55
+ type McpServerCardLayoutProps = {
56
+ icon: ReactNode
57
+ children: ReactNode
58
+ }
59
+
60
+ function McpServerCardLayout({ icon, children }: McpServerCardLayoutProps) {
61
+ return (
62
+ <div className="flex items-center gap-3 text-card-foreground">
63
+ {icon}
64
+ <div className="flex min-w-0 flex-1 flex-col justify-center gap-0.5">{children}</div>
65
+ </div>
66
+ )
67
+ }
68
+
69
+ export function McpServerCard({ server }: McpServerCardProps) {
70
+ return (
71
+ <McpServerCardLayout icon={<McpServerIcon name={server.name} status={server.status} />}>
72
+ <div className="truncate text-sm font-medium text-foreground">
73
+ {formatMcpServerName(server.name)}
74
+ </div>
75
+ <span className="text-sm text-muted-foreground">{statusLabel(server.status)}</span>
76
+ </McpServerCardLayout>
77
+ )
78
+ }
79
+
80
+ export function McpServerCardSkeleton() {
81
+ return (
82
+ <McpServerCardLayout icon={<Skeleton className="size-10 shrink-0 rounded-sm" />}>
83
+ <Skeleton className="h-4 w-36 max-w-full" />
84
+ <Skeleton className="h-4 w-20" />
85
+ </McpServerCardLayout>
86
+ )
87
+ }
88
+
89
+ type McpServerGridProps = {
90
+ children: ReactNode
91
+ }
92
+
93
+ export function McpServerGrid({ children }: McpServerGridProps) {
94
+ return <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">{children}</div>
95
+ }
@@ -15,14 +15,3 @@ export function useWorkspaceMcp(workspaceId: string, enabled: boolean) {
15
15
  refetchOnWindowFocus: false
16
16
  })
17
17
  }
18
-
19
- export function useUserMcp() {
20
- return useQuery<McpServer[]>({
21
- queryKey: workspaceKeys.userMcp,
22
- queryFn: () => requestJson('/api/mcp'),
23
- staleTime: 30_000,
24
- gcTime: Infinity,
25
- refetchOnMount: true,
26
- refetchOnWindowFocus: true
27
- })
28
- }
@@ -1,7 +1,15 @@
1
1
  import { IconChevronRight, IconEggCracked, IconLoader2, IconPlus } from '@tabler/icons-react'
2
2
  import { Link, useLocation } from 'wouter'
3
3
 
4
- import { useAddWorkspace, useDiscoveredWorkspaces, useWorkspacePreview, useWorkspaces } from './api'
4
+ import {
5
+ useDiscoveredWorkspaces,
6
+ useWorkspacePreview,
7
+ useWorkspaces,
8
+ useWorkspaceSetupInfo
9
+ } from './api'
10
+ import { CreateWorkspaceDialog } from './workspace-setup/CreateWorkspaceDialog'
11
+ import { ImportWorkspaceDialog } from './workspace-setup/ImportWorkspaceDialog'
12
+ import { useWorkspaceImport } from './workspace-setup/useWorkspaceImport'
5
13
  import { HomeLogo } from './HomeLogo'
6
14
  import { Button } from '@/client/components/ui/button'
7
15
  import {
@@ -12,20 +20,22 @@ import {
12
20
  import { cn } from '@/client/lib/cn'
13
21
  import { useUiStore } from '@/client/store/ui'
14
22
  import {
15
- WorkspaceTypeIcon,
23
+ WorkspaceAgentIcons,
16
24
  workspaceDisplayName,
17
25
  workspaceProviderIcon
18
26
  } from '@/client/features/home/workspace-presentation'
19
27
  import type { DiscoveredWorkspace, WorkspaceEntry } from '@/lib/types'
20
28
 
21
- import { CreateWorkspaceDialog } from './CreateWorkspaceDialog'
22
29
  import { WorkspacePreview } from './WorkspacePreview'
23
30
 
24
31
  export function HomePage() {
25
32
  const [, navigate] = useLocation()
26
33
  const workspacesQuery = useWorkspaces()
27
34
  const discoveredQuery = useDiscoveredWorkspaces()
28
- const importMutation = useAddWorkspace()
35
+ const setupInfo = useWorkspaceSetupInfo()
36
+ const importFlow = useWorkspaceImport({
37
+ onSuccess: entry => navigate(`/workspace/${entry.id}`)
38
+ })
29
39
  const discoveredWorkspacesOpen = useUiStore(state => state.discoveredWorkspacesOpen)
30
40
  const setDiscoveredWorkspacesOpen = useUiStore(state => state.setDiscoveredWorkspacesOpen)
31
41
 
@@ -48,13 +58,9 @@ export function HomePage() {
48
58
  const workspaces = workspacesQuery.data
49
59
  const discovered = discoveredQuery.data
50
60
  const count = workspaces.length
51
- const importingPath =
52
- importMutation.isPending && importMutation.variables ? importMutation.variables.path : null
53
61
 
54
62
  function handleAdd(suggestion: DiscoveredWorkspace) {
55
- importMutation.mutate(suggestion, {
56
- onSuccess: entry => navigate(`/workspace/${entry.id}`)
57
- })
63
+ importFlow.startImport(suggestion)
58
64
  }
59
65
 
60
66
  return (
@@ -122,21 +128,25 @@ export function HomePage() {
122
128
  <CollapsibleContent>
123
129
  <ul className="border-t border-border">
124
130
  {discovered.map(item => (
125
- <SuggestedRow
126
- key={item.path}
127
- suggestion={item}
128
- onAdd={handleAdd}
129
- loading={importingPath === item.path}
130
- />
131
+ <SuggestedRow key={item.path} suggestion={item} onAdd={handleAdd} />
131
132
  ))}
132
133
  </ul>
133
- {importMutation.isError && (
134
- <p className="mt-3 text-xs text-destructive">{importMutation.error.message}</p>
135
- )}
136
134
  </CollapsibleContent>
137
135
  </Collapsible>
138
136
  </section>
139
137
  )}
138
+
139
+ {importFlow.choice && (
140
+ <ImportWorkspaceDialog
141
+ choice={importFlow.choice}
142
+ availability={setupInfo.data?.availability}
143
+ isPending={importFlow.isPending}
144
+ errorMessage={importFlow.error?.message}
145
+ onTypeChange={importFlow.selectType}
146
+ onSubmit={importFlow.submit}
147
+ onReset={importFlow.reset}
148
+ />
149
+ )}
140
150
  </div>
141
151
  )
142
152
  }
@@ -174,25 +184,20 @@ function WorkspaceCard({ workspace }: WorkspaceCardProps) {
174
184
  type SuggestedRowProps = {
175
185
  suggestion: DiscoveredWorkspace
176
186
  onAdd: (suggestion: DiscoveredWorkspace) => void
177
- loading: boolean
178
187
  }
179
188
 
180
- function SuggestedRow({ suggestion, onAdd, loading }: SuggestedRowProps) {
181
- const { path, type } = suggestion
189
+ function SuggestedRow({ suggestion, onAdd }: SuggestedRowProps) {
190
+ const { path, types } = suggestion
182
191
  const name = workspaceDisplayName(suggestion)
183
192
  return (
184
193
  <li className="flex items-center gap-2 border-b border-border px-1 py-3">
185
- <WorkspaceTypeIcon type={type} />
194
+ <WorkspaceAgentIcons types={types} />
186
195
  <span className="shrink-0 text-sm font-medium text-foreground">{name}</span>
187
196
  <span title={path} className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
188
197
  {suggestion.displayPath ?? path}
189
198
  </span>
190
- <Button variant="outline" size="sm" onClick={() => onAdd(suggestion)} disabled={loading}>
191
- {loading ? (
192
- <IconLoader2 stroke={1.75} className="animate-spin" />
193
- ) : (
194
- <IconPlus stroke={1.75} />
195
- )}
199
+ <Button variant="outline" size="sm" onClick={() => onAdd(suggestion)}>
200
+ <IconPlus stroke={1.75} />
196
201
  Add
197
202
  </Button>
198
203
  </li>
@@ -4,6 +4,7 @@ import { jsonRequest, requestJson, requestVoid } from '@/client/api/http'
4
4
  import { workspaceKeys } from '@/client/api/workspace-keys'
5
5
  import type {
6
6
  DiscoveredWorkspace,
7
+ HarnessAvailability,
7
8
  WorkspaceEntry,
8
9
  WorkspacePreview,
9
10
  WorkspaceType
@@ -43,37 +44,48 @@ export function useDiscoveredWorkspaces() {
43
44
  })
44
45
  }
45
46
 
46
- export function useAddWorkspace() {
47
+ export function useImportWorkspace() {
47
48
  const queryClient = useQueryClient()
48
- return useMutation<WorkspaceEntry, Error, DiscoveredWorkspace>({
49
- mutationFn: discovered =>
50
- requestJson('/api/workspaces', jsonRequest('POST', discovered), 'Failed to add workspace'),
51
- onSuccess: (entry, suggestion) => {
49
+ return useMutation<WorkspaceEntry, Error, ImportWorkspaceInput>({
50
+ mutationFn: input =>
51
+ requestJson('/api/workspaces', jsonRequest('POST', input), 'Failed to add workspace'),
52
+ onSuccess: (entry, input) => {
52
53
  queryClient.setQueryData<WorkspaceEntry[]>(workspaceKeys.all, previous =>
53
54
  upsertWorkspaceEntry(previous, entry)
54
55
  )
55
56
  queryClient.setQueryData<DiscoveredWorkspace[]>(workspaceKeys.discover, previous =>
56
- (previous ?? []).filter(item => item.path !== suggestion.path)
57
+ (previous ?? []).filter(item => item.path !== input.path)
57
58
  )
58
59
  }
59
60
  })
60
61
  }
61
62
 
62
- export type CreateWorkspaceInfo = {
63
+ export type ImportWorkspaceInput = {
64
+ path: string
65
+ type: WorkspaceType
66
+ }
67
+
68
+ export type WorkspaceSetupInfo = {
63
69
  root: string
64
70
  displayRoot: string
65
71
  canChooseFolder: boolean
72
+ // Per-backend runtime availability (are the Claude/Codex CLIs installed?),
73
+ // keyed by workspace type. Missing entries mean available.
74
+ availability?: Partial<Record<WorkspaceType, HarnessAvailability>>
66
75
  }
67
76
 
68
- export function useCreateWorkspaceInfo() {
69
- return useQuery<CreateWorkspaceInfo>({
70
- queryKey: workspaceKeys.createInfo,
77
+ export function useWorkspaceSetupInfo() {
78
+ return useQuery<WorkspaceSetupInfo>({
79
+ queryKey: workspaceKeys.setupInfo,
80
+ // Availability can change while the app is open (the user installs the
81
+ // agent CLI) — refetch on mount instead of caching forever.
71
82
  queryFn: () => requestJson('/api/workspaces/create'),
72
- staleTime: Infinity
83
+ staleTime: 30_000,
84
+ refetchOnMount: 'always'
73
85
  })
74
86
  }
75
87
 
76
- export type ChooseFolderResult = { path: string } | { canceled: true }
88
+ export type ChooseFolderResult = DiscoveredWorkspace | { canceled: true }
77
89
 
78
90
  export function useChooseFolder() {
79
91
  return useMutation<ChooseFolderResult, Error, void>({
@@ -1,7 +1,6 @@
1
1
  import claudeIcon from '@/client/assets/claude.svg'
2
2
  import openaiIcon from '@/client/assets/openai.svg'
3
3
  import openclawIcon from '@/client/assets/openclaw.svg'
4
- import { cn } from '@/client/lib/cn'
5
4
  import type { DiscoveredWorkspace, WorkspaceEntry, WorkspaceType } from '@/lib/types'
6
5
 
7
6
  export const workspaceProviderIcon: Record<WorkspaceType, string> = {
@@ -16,28 +15,31 @@ export const workspaceTypeLabel: Record<WorkspaceType, string> = {
16
15
  codex: 'Codex'
17
16
  }
18
17
 
19
- type WorkspaceTypeIconProps = {
20
- type: WorkspaceType
21
- className?: string
18
+ type WorkspaceAgentIconsProps = {
19
+ types: WorkspaceType[]
22
20
  }
23
21
 
24
- export function WorkspaceTypeIcon({ type, className }: WorkspaceTypeIconProps) {
22
+ export function WorkspaceAgentIcons({ types }: WorkspaceAgentIconsProps) {
23
+ const label = types.map(type => workspaceTypeLabel[type]).join(', ')
24
+
25
25
  return (
26
- <img
27
- src={workspaceProviderIcon[type]}
28
- alt=""
29
- aria-label={workspaceTypeLabel[type]}
30
- className={cn('size-4 shrink-0', className)}
31
- />
26
+ <span role="img" aria-label={label} className="inline-flex shrink-0 items-center -space-x-0.5">
27
+ {types.map(type => (
28
+ <img
29
+ key={type}
30
+ src={workspaceProviderIcon[type]}
31
+ alt=""
32
+ className="size-4 shrink-0 rounded-full bg-muted ring-2 ring-muted"
33
+ />
34
+ ))}
35
+ </span>
32
36
  )
33
37
  }
34
38
 
35
- type WorkspaceDisplaySource = Pick<
36
- WorkspaceEntry | DiscoveredWorkspace,
37
- 'name' | 'path' | 'type' | 'agentId'
38
- >
39
+ type WorkspaceDisplaySource = WorkspaceEntry | DiscoveredWorkspace
39
40
 
40
41
  export function workspaceDisplayName(workspace: WorkspaceDisplaySource): string {
42
+ if ('types' in workspace) return workspace.path.split('/').pop() || workspace.path
41
43
  if (workspace.name) return workspace.name
42
44
  if (workspace.type === 'openclaw') return workspace.agentId ?? 'OpenClaw agent'
43
45
  return workspace.path.split('/').pop() || workspace.path
@@ -0,0 +1,243 @@
1
+ import { type FormEvent, type ReactElement, useState } from 'react'
2
+
3
+ import { useLocation } from 'wouter'
4
+
5
+ import { useChooseFolder, useCreateWorkspace, useWorkspaceSetupInfo } from '../api'
6
+ import { Button } from '@/client/components/ui/button'
7
+ import {
8
+ Dialog,
9
+ DialogDescription,
10
+ DialogTitle,
11
+ DialogTrigger
12
+ } from '@/client/components/ui/dialog'
13
+ import { Input } from '@/client/components/ui/input'
14
+ import { Tooltip, TooltipContent, TooltipTrigger } from '@/client/components/ui/tooltip'
15
+ import { cn } from '@/client/lib/cn'
16
+ import { validateWorkspaceFolderName } from '@/lib/workspace-name'
17
+ import { WORKSPACE_TYPE_ORDER } from '@/lib/workspace-types'
18
+ import type { WorkspaceType } from '@/lib/types'
19
+
20
+ import { ImportWorkspaceStep } from './ImportWorkspaceDialog'
21
+ import { WorkspaceAgentStep } from './WorkspaceAgentStep'
22
+ import { WorkspaceDialogContent } from './WorkspaceDialogContent'
23
+ import { useWorkspaceImport } from './useWorkspaceImport'
24
+
25
+ type CreateWorkspaceDialogProps = {
26
+ trigger: ReactElement
27
+ }
28
+
29
+ type CreateWorkspaceStep = 'agent' | 'name'
30
+
31
+ const DEFAULT_WORKSPACE_TYPE = WORKSPACE_TYPE_ORDER[0]
32
+
33
+ export function CreateWorkspaceDialog({ trigger }: CreateWorkspaceDialogProps) {
34
+ const [, navigate] = useLocation()
35
+ const info = useWorkspaceSetupInfo()
36
+ const createMutation = useCreateWorkspace()
37
+ const chooseFolder = useChooseFolder()
38
+ const importFlow = useWorkspaceImport({ onSuccess: entry => finish(entry.id) })
39
+
40
+ const [open, setOpen] = useState(false)
41
+ const [step, setStep] = useState<CreateWorkspaceStep>('agent')
42
+ const [type, setType] = useState<WorkspaceType>(DEFAULT_WORKSPACE_TYPE)
43
+ const [name, setName] = useState('')
44
+
45
+ const trimmedName = name.trim()
46
+ const nameError = trimmedName ? validateWorkspaceFolderName(trimmedName) : null
47
+ const canChooseFolder = info.data?.canChooseFolder ?? true
48
+ const isImporting = chooseFolder.isPending || importFlow.isPending
49
+ const isCreating = createMutation.isPending
50
+
51
+ function finish(workspaceId: string) {
52
+ setOpen(false)
53
+ navigate(`/workspace/${workspaceId}`)
54
+ }
55
+
56
+ function resetDialog() {
57
+ setStep('agent')
58
+ setType(DEFAULT_WORKSPACE_TYPE)
59
+ setName('')
60
+ chooseFolder.reset()
61
+ importFlow.reset()
62
+ createMutation.reset()
63
+ }
64
+
65
+ async function chooseExistingFolder() {
66
+ if (isImporting) return
67
+ chooseFolder.reset()
68
+
69
+ try {
70
+ const result = await chooseFolder.mutateAsync()
71
+ if (!('canceled' in result)) importFlow.startImport(result)
72
+ } catch {
73
+ // The agent step renders the folder-picker error.
74
+ }
75
+ }
76
+
77
+ function continueToName() {
78
+ createMutation.reset()
79
+ setStep('name')
80
+ }
81
+
82
+ function createWorkspace() {
83
+ if (!trimmedName || nameError || isCreating) return
84
+ createMutation.reset()
85
+ createMutation.mutate({ name: trimmedName, type }, { onSuccess: entry => finish(entry.id) })
86
+ }
87
+
88
+ return (
89
+ <Dialog
90
+ open={open}
91
+ onOpenChange={setOpen}
92
+ onOpenChangeComplete={nextOpen => {
93
+ if (!nextOpen) resetDialog()
94
+ }}
95
+ >
96
+ <DialogTrigger render={trigger} />
97
+ <WorkspaceDialogContent>
98
+ {importFlow.choice ? (
99
+ <ImportWorkspaceStep
100
+ choice={importFlow.choice}
101
+ availability={info.data?.availability}
102
+ isPending={importFlow.isPending}
103
+ errorMessage={importFlow.error?.message}
104
+ onTypeChange={importFlow.selectType}
105
+ onCancel={importFlow.reset}
106
+ onSubmit={importFlow.submit}
107
+ />
108
+ ) : step === 'agent' ? (
109
+ <WorkspaceAgentStep
110
+ title="Create new workspace"
111
+ selectedType={type}
112
+ availability={info.data?.availability}
113
+ isPending={isImporting}
114
+ errorMessage={(chooseFolder.error ?? importFlow.error)?.message}
115
+ secondaryAction={
116
+ <ExistingFolderButton
117
+ available={canChooseFolder}
118
+ disabled={isImporting}
119
+ onClick={chooseExistingFolder}
120
+ />
121
+ }
122
+ primaryLabel="Next"
123
+ onTypeChange={setType}
124
+ onSubmit={continueToName}
125
+ />
126
+ ) : (
127
+ <WorkspaceNameStep
128
+ name={name}
129
+ validationError={nameError}
130
+ requestError={createMutation.error?.message}
131
+ isPending={isCreating}
132
+ onNameChange={setName}
133
+ onSubmit={createWorkspace}
134
+ />
135
+ )}
136
+ </WorkspaceDialogContent>
137
+ </Dialog>
138
+ )
139
+ }
140
+
141
+ type WorkspaceNameStepProps = {
142
+ name: string
143
+ validationError: string | null
144
+ requestError?: string
145
+ isPending: boolean
146
+ onNameChange: (name: string) => void
147
+ onSubmit: () => void
148
+ }
149
+
150
+ function WorkspaceNameStep({
151
+ name,
152
+ validationError,
153
+ requestError,
154
+ isPending,
155
+ onNameChange,
156
+ onSubmit
157
+ }: WorkspaceNameStepProps) {
158
+ function handleSubmit(event: FormEvent<HTMLFormElement>) {
159
+ event.preventDefault()
160
+ onSubmit()
161
+ }
162
+
163
+ return (
164
+ <form className="flex flex-col gap-5" onSubmit={handleSubmit}>
165
+ <div className="flex flex-col gap-0.5 pr-8">
166
+ <DialogTitle>Create new workspace</DialogTitle>
167
+ <DialogDescription>Give it a short and recognizable name</DialogDescription>
168
+ </div>
169
+
170
+ <div className="flex flex-col gap-2">
171
+ <label htmlFor="workspace-name" className="sr-only">
172
+ Workspace name
173
+ </label>
174
+ <Input
175
+ id="workspace-name"
176
+ value={name}
177
+ onChange={event => onNameChange(event.target.value)}
178
+ placeholder="my-workspace"
179
+ autoFocus
180
+ aria-invalid={Boolean(validationError)}
181
+ aria-describedby={validationError ? 'workspace-name-error' : undefined}
182
+ autoComplete="off"
183
+ spellCheck={false}
184
+ />
185
+ {validationError && (
186
+ <p id="workspace-name-error" role="alert" className="text-xs text-destructive">
187
+ {validationError}
188
+ </p>
189
+ )}
190
+ </div>
191
+
192
+ {requestError && (
193
+ <p role="alert" className="text-xs text-destructive">
194
+ {requestError}
195
+ </p>
196
+ )}
197
+
198
+ <div className="flex items-center justify-end gap-2">
199
+ <Button type="submit" disabled={!name.trim() || Boolean(validationError) || isPending}>
200
+ {isPending ? 'Creating…' : 'Create workspace'}
201
+ </Button>
202
+ </div>
203
+ </form>
204
+ )
205
+ }
206
+
207
+ type ExistingFolderButtonProps = {
208
+ available: boolean
209
+ disabled: boolean
210
+ onClick: () => void
211
+ }
212
+
213
+ function ExistingFolderButton({ available, disabled, onClick }: ExistingFolderButtonProps) {
214
+ const button = (
215
+ <Button
216
+ variant="secondary"
217
+ disabled={available && disabled}
218
+ aria-disabled={!available || undefined}
219
+ onClick={event => {
220
+ if (!available) {
221
+ event.preventDefault()
222
+ return
223
+ }
224
+ onClick()
225
+ }}
226
+ className={cn(!available && 'cursor-not-allowed opacity-50')}
227
+ >
228
+ Use existing folder
229
+ </Button>
230
+ )
231
+
232
+ if (available) return button
233
+
234
+ return (
235
+ <Tooltip>
236
+ <TooltipTrigger render={button} />
237
+ <TooltipContent>
238
+ Run <code className="rounded-[4px] bg-accent px-1 py-0.5 font-mono">moi init</code> in the
239
+ folder to add it manually
240
+ </TooltipContent>
241
+ </Tooltip>
242
+ )
243
+ }