moi-computer 0.12.0 → 0.12.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 (140) hide show
  1. package/README.md +1 -1
  2. package/client/AGENTS.md +2 -2
  3. package/client/api/app-ui-keys.ts +1 -1
  4. package/client/api/workspace-keys.ts +1 -3
  5. package/client/app/routes/WorkspaceRoute.tsx +2 -8
  6. package/client/features/applets/applet-runtime.ts +11 -13
  7. package/client/features/chat/ChatPanel.tsx +70 -49
  8. package/client/features/chat/ChatPopup.tsx +81 -8
  9. package/client/features/chat/applet-chat-intents.ts +31 -12
  10. package/client/features/chat/chat-send.ts +33 -1
  11. package/client/features/chat/chat-store.ts +10 -0
  12. package/client/features/chat/composer/ChatComposer.tsx +24 -27
  13. package/client/features/chat/composer/ModelPicker.tsx +3 -3
  14. package/client/features/chat/composer/useWorkspaceComposerState.tsx +3 -3
  15. package/client/features/chat/connection/chat-frames.ts +14 -7
  16. package/client/features/chat/messages/ChatEmptyState.tsx +33 -19
  17. package/client/features/chat/messages/MarkdownContent.tsx +3 -3
  18. package/client/features/chat/messages/fork-history.ts +14 -0
  19. package/client/features/chat/sessions/ChatSelector.tsx +138 -79
  20. package/client/features/chat/sessions/api.ts +109 -19
  21. package/client/features/chat/sessions/browser-tab-state.ts +30 -7
  22. package/client/features/chat/sessions/useSelectedSession.ts +217 -51
  23. package/client/features/chat/useChat.ts +43 -45
  24. package/client/features/collab/client.ts +10 -11
  25. package/client/features/collab/hooks.tsx +6 -11
  26. package/client/features/collab/host-state.ts +57 -128
  27. package/client/features/collab/provider.tsx +3 -3
  28. package/client/features/collab/testing/fake-engine.ts +6 -27
  29. package/client/features/collab/workspace-users-menu.tsx +3 -7
  30. package/client/features/drawings/{useViewBuilderSketch.ts → useViewSketch.ts} +7 -7
  31. package/client/features/home/HomePage.tsx +2 -2
  32. package/client/features/overview/Overview.tsx +3 -6
  33. package/client/features/overview/default/ViewsWidget.tsx +5 -12
  34. package/client/features/overview/default/registry.tsx +2 -4
  35. package/client/features/views/PendingViewScreen.tsx +279 -0
  36. package/client/features/views/ViewManager.tsx +10 -10
  37. package/client/features/views/api.ts +63 -130
  38. package/client/features/views/useViewActions.ts +151 -0
  39. package/client/features/views/useViewDrafts.ts +79 -0
  40. package/client/features/views/view-presentation.ts +4 -5
  41. package/client/features/views/view-submission.ts +88 -0
  42. package/client/features/workspace/WorkspaceMenu.tsx +63 -0
  43. package/client/features/workspace/WorkspaceScreen.tsx +180 -375
  44. package/client/features/workspace/browser-tab-state.ts +16 -9
  45. package/client/features/workspace/moi-context.ts +13 -15
  46. package/client/features/workspace/tab-resolution.ts +16 -29
  47. package/client/features/workspace/useWorkspaceNavigation.ts +146 -104
  48. package/client/index.tsx +5 -1
  49. package/client/runtime/useWorkspaceEvents.ts +7 -6
  50. package/client/store/ui.ts +25 -29
  51. package/dist/chunk-1zhnhy00.js +1 -0
  52. package/dist/chunk-27501vke.js +1 -0
  53. package/dist/{chunk-jf6czgrz.js → chunk-9xtv6djt.js} +2 -2
  54. package/dist/chunk-am1x230f.js +2 -0
  55. package/dist/{chunk-nez8sdta.js → chunk-darpsw65.js} +1 -1
  56. package/dist/{chunk-97eg9mjn.js → chunk-gps4qc38.js} +1 -1
  57. package/dist/{chunk-3a48fyf7.js → chunk-hzwr8dp8.js} +4 -4
  58. package/dist/{chunk-efdyz6xp.js → chunk-j905va8r.js} +1 -1
  59. package/dist/chunk-n33w9y38.js +10 -0
  60. package/dist/chunk-r63ks44z.js +68 -0
  61. package/dist/{chunk-vfpsc75k.js → chunk-vqpkqtdr.js} +1 -1
  62. package/dist/chunk-wd46nk26.css +1 -0
  63. package/dist/chunk-xgt7vxt9.js +1 -0
  64. package/dist/{chunk-z3byfve5.js → chunk-yvzhwtfa.js} +2 -2
  65. package/dist/index.html +1 -1
  66. package/lib/ids.ts +2 -5
  67. package/lib/moi-context.ts +100 -73
  68. package/lib/navigation.ts +48 -87
  69. package/lib/session-drafts.ts +10 -0
  70. package/lib/types.ts +64 -31
  71. package/lib/view-build-directives.ts +12 -0
  72. package/lib/workspace-layout.ts +1 -1
  73. package/lib/workspace-tabs.ts +12 -7
  74. package/package.json +3 -1
  75. package/server/agent-launcher.ts +27 -0
  76. package/server/api.ts +119 -209
  77. package/server/app-config.ts +21 -2
  78. package/server/applets/build-worker.ts +2 -1
  79. package/server/applets/view-source.ts +7 -1
  80. package/server/cli-env.ts +72 -50
  81. package/server/cli.ts +101 -64
  82. package/server/control.ts +82 -63
  83. package/server/data-dir.ts +13 -0
  84. package/server/functions.ts +2 -1
  85. package/server/harness/README.md +8 -0
  86. package/server/harness/acp/adapter.ts +2 -2
  87. package/server/harness/acp/client.ts +2 -1
  88. package/server/harness/acp/discovery.ts +3 -3
  89. package/server/harness/acp/session.ts +6 -9
  90. package/server/harness/claude-code/adapter.ts +13 -8
  91. package/server/harness/claude-code/auth.ts +3 -2
  92. package/server/harness/claude-code/cli.ts +3 -1
  93. package/server/harness/claude-code/git-worktree.ts +5 -2
  94. package/server/harness/claude-code/index.ts +5 -0
  95. package/server/harness/claude-code/mcp.ts +2 -0
  96. package/server/harness/claude-code/models.ts +2 -0
  97. package/server/harness/claude-code/session.ts +5 -34
  98. package/server/harness/claude-code/sessions.ts +8 -12
  99. package/server/harness/codex/NOTES.md +23 -4
  100. package/server/harness/codex/adapter.ts +5 -3
  101. package/server/harness/codex/client.ts +13 -21
  102. package/server/harness/codex/index.ts +18 -0
  103. package/server/harness/codex/session.ts +6 -14
  104. package/server/harness/codex/thread-list.ts +74 -0
  105. package/server/harness/fork.ts +12 -0
  106. package/server/harness/openclaw/adapter.ts +3 -3
  107. package/server/harness/openclaw/session.ts +2 -30
  108. package/server/harness/session-title.ts +12 -3
  109. package/server/harness/types.ts +8 -3
  110. package/server/moi-scaffold.ts +2 -1
  111. package/server/pending-views.ts +164 -0
  112. package/server/registry.ts +14 -4
  113. package/server/selected-session.ts +91 -44
  114. package/server/service.ts +16 -2
  115. package/server/session-archive.ts +32 -0
  116. package/server/session-config.ts +16 -111
  117. package/server/session-lifecycle.ts +17 -0
  118. package/server/session-store.ts +127 -0
  119. package/server/status.ts +3 -1
  120. package/server/tabs.ts +7 -10
  121. package/server/view-sessions.ts +267 -0
  122. package/server/views.ts +30 -41
  123. package/server/web.ts +47 -45
  124. package/server/workspace-env.ts +27 -0
  125. package/server/workspace-init.ts +6 -2
  126. package/workspace/.claude/skills/moi-workspace/SKILL.md +49 -20
  127. package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +2 -5
  128. package/client/features/views/ViewBuilder.tsx +0 -239
  129. package/client/features/views/useViewBuilderActions.ts +0 -103
  130. package/client/features/views/useViewBuilderDrafts.ts +0 -68
  131. package/dist/chunk-2jncyq65.js +0 -1
  132. package/dist/chunk-e2q5ken7.js +0 -68
  133. package/dist/chunk-h2kj1ysj.js +0 -1
  134. package/dist/chunk-nzwgm8vc.css +0 -1
  135. package/dist/chunk-ph0h6h86.js +0 -1
  136. package/dist/chunk-ryg9z3kn.js +0 -10
  137. package/dist/chunk-tpn177bt.js +0 -2
  138. package/lib/view-builder-directives.ts +0 -16
  139. package/server/chat-selection.ts +0 -22
  140. package/server/view-builders.ts +0 -453
@@ -0,0 +1,127 @@
1
+ import { mkdir, rename } from 'node:fs/promises'
2
+ import { dirname, join } from 'node:path'
3
+ import type {
4
+ SessionConfig,
5
+ SessionRecord,
6
+ SessionRecordPatch,
7
+ SessionInfo,
8
+ SessionSummary
9
+ } from '@/lib/types'
10
+ import { DATA_DIR } from './data-dir'
11
+
12
+ type Store = Record<string, Record<string, SessionRecord>>
13
+ export const DEFAULT_SESSION_STORE_PATH = join(DATA_DIR, 'sessions.json')
14
+ let storePath = DEFAULT_SESSION_STORE_PATH
15
+ let writes: Promise<unknown> = Promise.resolve()
16
+
17
+ export function setSessionStorePath(path: string) {
18
+ storePath = path
19
+ }
20
+
21
+ async function readFile<T>(path: string): Promise<T | undefined> {
22
+ const file = Bun.file(path)
23
+ return (await file.exists()) ? file.json() : undefined
24
+ }
25
+
26
+ async function read(): Promise<Store> {
27
+ const stored = await readFile<Store>(storePath)
28
+ if (stored) return stored
29
+ // Import old files until the first unified write; leave the originals intact.
30
+ const directory = dirname(storePath)
31
+ const configs = await readFile<Record<string, Record<string, SessionConfig>>>(
32
+ join(directory, 'session-config.json')
33
+ )
34
+ const store: Store = {}
35
+ for (const [workspace, sessions] of Object.entries(configs ?? {})) {
36
+ const records = (store[workspace] ??= {})
37
+ for (const [id, config] of Object.entries(sessions)) records[id] = { ...records[id], config }
38
+ }
39
+ return store
40
+ }
41
+
42
+ export async function getSessionRecords(workspacePath: string) {
43
+ await writes
44
+ return (await read())[workspacePath] ?? {}
45
+ }
46
+
47
+ export async function getSessionRecord(
48
+ workspacePath: string,
49
+ sessionId: string
50
+ ): Promise<SessionRecord> {
51
+ return (await getSessionRecords(workspacePath))[sessionId] ?? {}
52
+ }
53
+
54
+ export async function updateSessionRecords<T>(
55
+ workspacePath: string,
56
+ change: (sessions: Record<string, SessionRecord>) => T
57
+ ) {
58
+ const run = writes.then(async () => {
59
+ const store = await read()
60
+ const sessions = (store[workspacePath] ??= {})
61
+ const result = change(sessions)
62
+ if (result === false) return result
63
+ for (const [id, record] of Object.entries(sessions)) {
64
+ if (Object.keys(record).length === 0) delete sessions[id]
65
+ }
66
+ if (Object.keys(sessions).length === 0) delete store[workspacePath]
67
+ await mkdir(dirname(storePath), { recursive: true })
68
+ const temp = `${storePath}.${process.pid}.tmp`
69
+ await Bun.write(temp, JSON.stringify(store, null, 2))
70
+ await rename(temp, storePath)
71
+ return result
72
+ })
73
+ writes = run.catch(() => {})
74
+ return run
75
+ }
76
+
77
+ export async function renameSessionRecord(workspacePath: string, from: string, to: string) {
78
+ if (from === to) return
79
+ await updateSessionRecords(workspacePath, sessions => {
80
+ if (sessions[from]) {
81
+ const source = sessions[from]
82
+ const target = sessions[to]
83
+ sessions[to] = {
84
+ ...source,
85
+ ...target,
86
+ ...(source.config || target?.config
87
+ ? { config: { ...source.config, ...target?.config } }
88
+ : {})
89
+ }
90
+ delete sessions[from]
91
+ }
92
+ for (const record of Object.values(sessions)) {
93
+ if (record.forkedFromSessionId === from) record.forkedFromSessionId = to
94
+ }
95
+ })
96
+ }
97
+
98
+ export async function withSessionRecords(
99
+ workspacePath: string,
100
+ sessions: SessionSummary[]
101
+ ): Promise<SessionInfo[]> {
102
+ const records = await getSessionRecords(workspacePath)
103
+ return sessions.map(session => {
104
+ const { config: _, ...metadata } = records[session.sessionId] ?? {}
105
+ return { ...session, ...metadata }
106
+ })
107
+ }
108
+
109
+ export async function patchSessionRecord(
110
+ workspacePath: string,
111
+ sessionId: string,
112
+ metadata: SessionRecordPatch
113
+ ) {
114
+ await updateSessionRecords(workspacePath, sessions => {
115
+ const next = { ...sessions[sessionId], ...metadata }
116
+ assertSessionRecord(next)
117
+ sessions[sessionId] = next
118
+ })
119
+ }
120
+
121
+ function assertSessionRecord(record: Partial<SessionRecord>): asserts record is SessionRecord {
122
+ if (
123
+ record.forkedFromSessionId === undefined &&
124
+ (record.forkedThroughMessageId !== undefined || record.forkedNoticeIds !== undefined)
125
+ )
126
+ throw new Error('Fork history requires a source session')
127
+ }
package/server/status.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  // chat appears stuck (loader spinning) and you want to know whether the server
6
6
  // still holds a live session for that thread, or when a widget's server call
7
7
  // hangs and you want to see whether its worker is alive and what it has loaded.
8
+ import { getAppConfig } from './app-config'
8
9
  import { CONTROL_PORT, PORT } from './constants'
9
10
  import { debugEnabled } from './debug'
10
11
  import { WORKER_LIMITS, type WorkerDebugInfo, getWorkersDebugSnapshot } from './functions'
@@ -73,7 +74,8 @@ export function renderStatus(): string {
73
74
  lines.push('')
74
75
  lines.push(`version ${VERSION}${process.env.MOI_SERVICE ? ' (service-managed)' : ''}`)
75
76
  lines.push(`uptime ${fmtDuration(now - STARTED_AT)}`)
76
- lines.push(`http port ${PORT}`)
77
+ const { unixSocket } = getAppConfig()
78
+ lines.push(unixSocket ? `web socket ${unixSocket}` : `http port ${PORT}`)
77
79
  lines.push(`control port ${CONTROL_PORT}`)
78
80
  lines.push(`debug logging ${debugEnabled ? 'on (--debug)' : 'off'}`)
79
81
  lines.push(`connected tabs ${getClientCount()}`)
package/server/tabs.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  // Tab discovery with portable navigation addresses.
2
2
  import type { ViewInfo, WorkspaceTabId } from '@/lib/types'
3
- import { moiHref } from '@/lib/navigation'
4
3
  import { viewTabId } from '@/lib/workspace-tabs'
5
4
 
6
5
  // One row of `moi tabs`. `isDefault` marks the workspace's saved default tab
@@ -9,27 +8,25 @@ export type TabRow = {
9
8
  id: WorkspaceTabId
10
9
  title: string
11
10
  isDefault: boolean
12
- href?: string
11
+ href: string
13
12
  }
14
13
 
15
14
  // The always-present tabs, titled like the tab bar renders them.
16
15
  const STATIC_TABS: { id: WorkspaceTabId; title: string }[] = [
17
16
  { id: 'overview', title: 'Overview' },
18
- { id: 'agent', title: 'Agent' },
19
17
  { id: 'scratchpad', title: 'Scratchpad' }
20
18
  ]
21
19
 
22
- // The `moi tabs` listing: static tabs plus each built view, the saved default
23
- // marked. View builders are transient build-state, not addressable tabs, so
24
- // they don't list (and a builder default simply marks no row).
20
+ // The `moi tabs` listing: static tabs plus every compiled or pending view, with
21
+ // the saved default marked.
25
22
  export function assembleTabRows(views: ViewInfo[], defaultTab: WorkspaceTabId): TabRow[] {
26
23
  return [
27
24
  ...STATIC_TABS,
28
- ...views.map(view => ({ id: viewTabId(view.id), title: view.config.title || view.id }))
25
+ ...views.map(view => ({ id: viewTabId(view.id), title: view.title || view.id }))
29
26
  ].map(row => ({
30
27
  ...row,
31
28
  isDefault: row.id === defaultTab,
32
- ...(row.id === 'agent' ? {} : { href: moiHref(row.id) })
29
+ href: `moi:/${row.id}`
33
30
  }))
34
31
  }
35
32
 
@@ -37,9 +34,9 @@ export function assembleTabRows(views: ViewInfo[], defaultTab: WorkspaceTabId):
37
34
  // browser to move. The browser repeats the availability check in case its view
38
35
  // list is stale in either direction.
39
36
  export function assertNavigableTab(tab: WorkspaceTabId, views: ViewInfo[]): void {
40
- const rows = assembleTabRows(views, 'agent').filter(row => row.href)
37
+ const rows = assembleTabRows(views, 'overview')
41
38
  if (rows.some(row => row.id === tab)) return
42
39
  throw new Error(
43
- `Unknown destination "${moiHref(tab)}". Valid addresses: ${rows.map(row => row.href).join(', ')}`
40
+ `Unknown destination "moi:/${tab}". Valid addresses: ${rows.map(row => row.href).join(', ')}`
44
41
  )
45
42
  }
@@ -0,0 +1,267 @@
1
+ import { APP_ICON_IDS } from '@/lib/app-icons'
2
+ import { viewBuildDirectives } from '@/lib/view-build-directives'
3
+ import { viewIdFromTab, viewTabId } from '@/lib/workspace-tabs'
4
+ import type { PendingView, SelectedSessionScope, WorkspaceEntry, WorkspaceTabId } from '@/lib/types'
5
+ import { getCollabReferencePath } from './collab/config'
6
+ import { harnessFor } from './harness/registry'
7
+ import type { SendMessageInput } from './harness/types'
8
+ import { ForkUnsupportedError, inheritedHistoryBoundary } from './harness/fork'
9
+ import { publishEvent } from './events'
10
+ import { broadcast } from './state'
11
+ import { getPinnedSession, saveSelectedSession, resolveRenamedSession } from './selected-session'
12
+ import { getSessionRecord, patchSessionRecord } from './session-store'
13
+ import { getSessionConfig, saveSessionConfig } from './session-config'
14
+ import {
15
+ beginViewBuild,
16
+ createPendingView,
17
+ getPendingView,
18
+ listPendingViews,
19
+ patchPendingView,
20
+ PendingViewError
21
+ } from './pending-views'
22
+
23
+ export class ViewStartupError extends Error {
24
+ constructor(
25
+ error: unknown,
26
+ public sessionId?: string,
27
+ public viewId?: string
28
+ ) {
29
+ super(error instanceof Error ? error.message : 'Couldn’t start view chat')
30
+ }
31
+ }
32
+ type BuildSendOptions = Pick<
33
+ SendMessageInput,
34
+ 'attachments' | 'optimisticId' | 'model' | 'effort' | 'fastMode' | 'stream'
35
+ > & { selectedSessionScope?: SelectedSessionScope }
36
+ export type SubmitViewInput = BuildSendOptions & { requirements: string; sessionId?: string }
37
+
38
+ // Both ordinary chat and initial build requests use this boundary.
39
+ export async function sendWorkspaceMessage(
40
+ ws: WorkspaceEntry,
41
+ input: SendMessageInput & { selectedSessionScope?: SelectedSessionScope; viewBuildId?: string }
42
+ ) {
43
+ const { selectedSessionScope, viewBuildId, ...message } = input
44
+ const sessionId = resolveRenamedSession(ws.path, input.sessionId)
45
+ const record = await getSessionRecord(ws.path, sessionId)
46
+ const tabId = input.context?.activeTab?.id ?? record.tabId ?? 'overview'
47
+ const targetViewId = viewBuildId ?? (input.isNew ? viewIdFromTab(tabId) : undefined)
48
+ const ownedViews = targetViewId
49
+ ? []
50
+ : (await listPendingViews(ws.path)).filter(view => view.executionSessionId === sessionId)
51
+ const pending = targetViewId
52
+ ? await getPendingView(ws.path, targetViewId)
53
+ : (ownedViews.find(view => view.id === viewIdFromTab(tabId)) ?? ownedViews[0])
54
+ const isBuildRequest = pending && (viewBuildId === pending.id || input.isNew)
55
+ if (
56
+ isBuildRequest &&
57
+ pending.executionSessionId &&
58
+ pending.executionSessionId !== sessionId &&
59
+ (pending.status === 'starting' ||
60
+ harnessFor(ws)
61
+ .activeSessions()
62
+ .some(
63
+ session =>
64
+ session.workspaceId === ws.id && session.sessionId === pending.executionSessionId
65
+ ))
66
+ )
67
+ throw new PendingViewError('This view is already being built in another chat', 409)
68
+ if (input.isNew && record.tabId !== tabId) {
69
+ record.tabId = tabId === 'overview' ? undefined : tabId
70
+ await attachSession(ws, tabId, sessionId, null, selectedSessionScope)
71
+ }
72
+ if (isBuildRequest)
73
+ await patchPendingView(ws.id, ws.path, pending.id, {
74
+ executionSessionId: sessionId
75
+ })
76
+ const collabReference = await getCollabReferencePath(ws.path, ws.type)
77
+ const pinnedSessionId = await getPinnedSession(ws.path)
78
+ await harnessFor(ws).sendMessage({
79
+ ...message,
80
+ sessionId,
81
+ context: {
82
+ ...input.context,
83
+ session: {
84
+ id: sessionId,
85
+ tabId: record.tabId,
86
+ pinned: pinnedSessionId === sessionId
87
+ },
88
+ ...(collabReference ? { collabReference } : {}),
89
+ directives: [
90
+ ...(input.context?.directives ?? []),
91
+ ...(isBuildRequest ? viewBuildDirectives(pending.id, APP_ICON_IDS) : []),
92
+ ...(isBuildRequest && record.forkedFromSessionId
93
+ ? [
94
+ 'Inherited conversation is background. Work on the current request; do not resume unrelated earlier tasks.'
95
+ ]
96
+ : []),
97
+ ...(pending && input.isNew && pending.requirements !== input.content
98
+ ? [`Original view requirements:\n${pending.requirements}`]
99
+ : []),
100
+ ...(pending && input.attachments?.length
101
+ ? ['Use the attachments as reference material for the intended view.']
102
+ : [])
103
+ ]
104
+ }
105
+ })
106
+ if (pending && pending.status !== 'starting')
107
+ await patchPendingView(ws.id, ws.path, pending.id, { status: 'submitted', error: undefined })
108
+ }
109
+ async function attachSession(
110
+ ws: WorkspaceEntry,
111
+ tabId: WorkspaceTabId,
112
+ sessionId: string,
113
+ previousSessionId?: string | null,
114
+ selectedSessionScope: SelectedSessionScope = 'shared'
115
+ ) {
116
+ await patchSessionRecord(ws.path, sessionId, { tabId: tabId === 'overview' ? undefined : tabId })
117
+ broadcast(ws.id, { type: 'sessions_changed', sessionId })
118
+ if (selectedSessionScope === 'shared') {
119
+ await saveSelectedSession(ws.path, sessionId, previousSessionId, tabId)
120
+ publishEvent({ type: 'selected-session:updated', workspaceId: ws.id, sessionId })
121
+ }
122
+ }
123
+ async function sendBuild(
124
+ ws: WorkspaceEntry,
125
+ view: PendingView,
126
+ sessionId: string,
127
+ isNew: boolean,
128
+ options: BuildSendOptions
129
+ ) {
130
+ await sendWorkspaceMessage(ws, {
131
+ ...options,
132
+ workspaceId: ws.id,
133
+ workspacePath: ws.path,
134
+ agentId: ws.agentId,
135
+ sessionId,
136
+ isNew,
137
+ viewBuildId: view.id,
138
+ content: view.requirements
139
+ })
140
+ await patchPendingView(ws.id, ws.path, view.id, { status: 'submitted' }, 'starting')
141
+ }
142
+ async function failStartup(
143
+ ws: WorkspaceEntry,
144
+ error: unknown,
145
+ sessionId?: string,
146
+ view?: PendingView
147
+ ): Promise<never> {
148
+ if (view)
149
+ await patchPendingView(
150
+ ws.id,
151
+ ws.path,
152
+ view.id,
153
+ {
154
+ status: 'failed',
155
+ error: error instanceof Error ? error.message : 'Couldn’t start view chat'
156
+ },
157
+ 'starting'
158
+ )
159
+ throw new ViewStartupError(
160
+ error,
161
+ sessionId ? resolveRenamedSession(ws.path, sessionId) : undefined,
162
+ view?.id
163
+ )
164
+ }
165
+
166
+ export async function submitView(ws: WorkspaceEntry, viewId: string, input: SubmitViewInput) {
167
+ const pinned = await getPinnedSession(ws.path)
168
+ const sessionId = pinned ?? input.sessionId ?? crypto.randomUUID()
169
+ const view = await beginViewBuild(
170
+ ws.id,
171
+ ws.path,
172
+ viewId,
173
+ input.requirements,
174
+ sessionId,
175
+ !!input.attachments?.length
176
+ )
177
+ try {
178
+ if (!pinned)
179
+ await attachSession(ws, viewTabId(view.id), sessionId, undefined, input.selectedSessionScope)
180
+ await sendBuild(ws, view, sessionId, !pinned, input)
181
+ } catch (error) {
182
+ return failStartup(ws, error, sessionId, view)
183
+ }
184
+ return { viewId, sessionId: resolveRenamedSession(ws.path, sessionId) }
185
+ }
186
+ export async function createViewFromSession(
187
+ ws: WorkspaceEntry,
188
+ fromSessionId: string | undefined,
189
+ requirements: string
190
+ ) {
191
+ if (!requirements.trim()) throw new Error('View requirements are required')
192
+ if (fromSessionId === undefined) {
193
+ const view = await createPendingView(ws.id, ws.path, {
194
+ requirements: requirements.trim(),
195
+ status: 'submitted'
196
+ })
197
+ return {
198
+ viewId: view.id,
199
+ mode: 'in-place' as const,
200
+ buildInstructions: viewBuildDirectives(view.id, APP_ICON_IDS)
201
+ }
202
+ }
203
+ if (!fromSessionId) throw new Error('Session id cannot be empty')
204
+ fromSessionId = resolveRenamedSession(ws.path, fromSessionId)
205
+ const harness = harnessFor(ws)
206
+ if (
207
+ !(await harness.listSessions(ws)).some(session => session.sessionId === fromSessionId) &&
208
+ !harness
209
+ .activeSessions()
210
+ .some(session => session.workspaceId === ws.id && session.sessionId === fromSessionId)
211
+ )
212
+ throw new Error('Source chat not found')
213
+ let sessionId: string | undefined
214
+ let view: PendingView | undefined
215
+ try {
216
+ const sourceConfig = await getSessionConfig(ws.path, fromSessionId)
217
+ try {
218
+ sessionId = await harness.forkSession?.(ws, fromSessionId, sourceConfig)
219
+ } catch (error) {
220
+ if (!(error instanceof ForkUnsupportedError)) throw error
221
+ }
222
+ const isNew = !sessionId
223
+ sessionId ??= crypto.randomUUID()
224
+ if (!isNew) {
225
+ await patchSessionRecord(ws.path, sessionId, { forkedFromSessionId: fromSessionId })
226
+ // The fork API returns only a child ID. A failed history read leaves the
227
+ // child usable and its full transcript visible.
228
+ const history = await harness.sessionEvents(ws, sessionId).catch(() => undefined)
229
+ if (history)
230
+ await patchSessionRecord(ws.path, sessionId, {
231
+ forkedFromSessionId: fromSessionId,
232
+ ...inheritedHistoryBoundary(history)
233
+ })
234
+ }
235
+ const config = await saveSessionConfig(ws.path, sessionId, sourceConfig)
236
+ view = await createPendingView(ws.id, ws.path, {
237
+ status: 'starting',
238
+ requirements: requirements.trim(),
239
+ executionSessionId: sessionId
240
+ })
241
+ await attachSession(ws, viewTabId(view.id), sessionId)
242
+ await sendBuild(ws, view, sessionId, isNew, config)
243
+ return {
244
+ viewId: view.id,
245
+ mode: 'handoff' as const,
246
+ sessionId: resolveRenamedSession(ws.path, sessionId)
247
+ }
248
+ } catch (error) {
249
+ return failStartup(ws, error, sessionId, view)
250
+ }
251
+ }
252
+ export async function failInterruptedViewStarts(ws: WorkspaceEntry) {
253
+ for (const view of await listPendingViews(ws.path)) {
254
+ if (view.status === 'starting')
255
+ await patchPendingView(
256
+ ws.id,
257
+ ws.path,
258
+ view.id,
259
+ {
260
+ status: 'failed',
261
+ error:
262
+ 'View chat startup was interrupted. Check the chat before continuing; it has not been retried.'
263
+ },
264
+ 'starting'
265
+ )
266
+ }
267
+ }
package/server/views.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from 'node:fs'
2
2
 
3
3
  import { viewTabId } from '@/lib/workspace-tabs'
4
- import type { ViewConfig, ViewInfo } from '@/lib/types'
4
+ import type { CompiledView, ViewConfig, ViewInfo, WorkspaceEntry } from '@/lib/types'
5
5
 
6
6
  import { syncAppletLogAfterBuild } from './applet-log'
7
7
  import {
@@ -15,7 +15,8 @@ import {
15
15
  import { serializeWorkspaceBundle } from './bundle-queue'
16
16
  import { reloadModules } from './functions'
17
17
  import { loadLayout, saveLayout } from './layout'
18
- import { deleteViewBuilderForView, markViewBuilderReady } from './view-builders'
18
+ import { completeViewBuild, listPendingViews } from './pending-views'
19
+ import { archiveViewSessions } from './session-archive'
19
20
  import { setViewSourceTitle } from './applets/config'
20
21
  import { deleteViewSourceFiles, readViewSource, ViewSourceInUseError } from './applets/view-source'
21
22
 
@@ -118,7 +119,7 @@ function listBuiltViews(workspacePath: string): Promise<string[]> {
118
119
  }
119
120
 
120
121
  // Built views in manifest order, with `title` resolved (falls back to the id).
121
- export async function getViewList(workspacePath: string): Promise<ViewInfo[]> {
122
+ export async function listCompiledViews(workspacePath: string): Promise<CompiledView[]> {
122
123
  const [built, manifest] = await Promise.all([
123
124
  listBuiltViews(workspacePath),
124
125
  readManifest(workspacePath)
@@ -137,12 +138,11 @@ export async function getViewList(workspacePath: string): Promise<ViewInfo[]> {
137
138
  const revision = getAppletRevision(workspacePath, 'view', id)
138
139
  return {
139
140
  id,
141
+ status: 'compiled',
140
142
  ...(revision ? { revision } : {}),
141
- config: {
142
- title: raw.title || id,
143
- ...(icon ? { icon } : {}),
144
- ...(requiredEnv ? { requiredEnv } : {})
145
- }
143
+ title: raw.title || id,
144
+ ...(icon ? { icon } : {}),
145
+ ...(requiredEnv ? { requiredEnv } : {})
146
146
  }
147
147
  })
148
148
  }
@@ -172,8 +172,15 @@ export async function collectViewRequiredEnv(
172
172
  return out
173
173
  }
174
174
 
175
+ export async function getWorkspaceViews(workspacePath: string): Promise<ViewInfo[]> {
176
+ const compiled = await listCompiledViews(workspacePath)
177
+ const ids = new Set(compiled.map(view => view.id))
178
+ const pending = (await listPendingViews(workspacePath)).filter(view => !ids.has(view.id))
179
+ return [...compiled, ...pending]
180
+ }
181
+
175
182
  export async function listViews(workspacePath: string): Promise<Response> {
176
- return Response.json({ views: await getViewList(workspacePath) })
183
+ return Response.json({ views: await getWorkspaceViews(workspacePath) })
177
184
  }
178
185
 
179
186
  export async function handleBundleViews(
@@ -181,9 +188,6 @@ export async function handleBundleViews(
181
188
  workspaceId: string,
182
189
  workspacePath: string,
183
190
  force = false,
184
- // When set, compile without advancing any view builder to `ready` (the
185
- // `moi bundle --no-status` opt-out). The build still publishes `view:updated`.
186
- skipStatus = false,
187
191
  target?: string
188
192
  ) {
189
193
  const before = await readManifest(workspacePath)
@@ -212,15 +216,7 @@ export async function handleBundleViews(
212
216
  for (const r of results) {
213
217
  if (r.status === 'built') {
214
218
  publish({ type: 'view:updated', name: r.name, config: r.config ?? null })
215
- if (!skipStatus) {
216
- await markViewBuilderReady(
217
- workspaceId,
218
- workspacePath,
219
- r.name,
220
- r.config?.title || r.name,
221
- r.config?.icon
222
- )
223
- }
219
+ await completeViewBuild(workspaceId, workspacePath, r.name)
224
220
  for (const m of r.serverModules ?? []) changedServerModules.add(m)
225
221
  }
226
222
  }
@@ -229,7 +225,7 @@ export async function handleBundleViews(
229
225
  reloadModules([...changedServerModules], workspacePath)
230
226
  }
231
227
 
232
- const views = await getViewList(workspacePath)
228
+ const views = await listCompiledViews(workspacePath)
233
229
  if (identityChanged || orderChanged || membershipChanged) {
234
230
  publish({ type: 'view-layout:updated', views })
235
231
  }
@@ -243,11 +239,11 @@ export async function updateViewTitle(
243
239
  workspacePath: string,
244
240
  viewId: string,
245
241
  title: string
246
- ): Promise<ViewInfo> {
242
+ ): Promise<CompiledView> {
247
243
  return serializeWorkspaceBundle(workspacePath, async () => {
248
- const current = (await getViewList(workspacePath)).find(view => view.id === viewId)
244
+ const current = (await listCompiledViews(workspacePath)).find(view => view.id === viewId)
249
245
  if (!current) throw new ViewMutationError('View not found', 404)
250
- if (current.config.title === title) return current
246
+ if (current.title === title) return current
251
247
 
252
248
  const source = await readViewSource(workspacePath, viewId)
253
249
  if (!source) throw new ViewMutationError('View source not found', 409)
@@ -265,21 +261,14 @@ export async function updateViewTitle(
265
261
 
266
262
  await Bun.write(source.path, updated)
267
263
  try {
268
- // A rename changed this entry; rebuild only it and preserve builder status.
269
- const results = await handleBundleViews(
270
- publish,
271
- workspaceId,
272
- workspacePath,
273
- true,
274
- true,
275
- viewId
276
- )
264
+ // A rename changed this entry; rebuild only it and leave pending views alone.
265
+ const results = await handleBundleViews(publish, workspaceId, workspacePath, true, viewId)
277
266
  const result = results.find(candidate => candidate.name === viewId)
278
267
  if (result?.status !== 'built') {
279
268
  throw new ViewMutationError(result?.error ?? 'Could not rebuild the renamed view', 422)
280
269
  }
281
270
 
282
- const renamed = (await getViewList(workspacePath)).find(view => view.id === viewId)
271
+ const renamed = (await listCompiledViews(workspacePath)).find(view => view.id === viewId)
283
272
  if (!renamed) {
284
273
  throw new ViewMutationError('Renamed view was not found after rebuilding', 422)
285
274
  }
@@ -300,22 +289,22 @@ export async function updateViewTitle(
300
289
 
301
290
  export async function deleteView(
302
291
  publish: (msg: unknown) => void,
303
- workspaceId: string,
304
- workspacePath: string,
292
+ ws: WorkspaceEntry,
305
293
  viewId: string
306
294
  ): Promise<void> {
295
+ const { id: workspaceId, path: workspacePath } = ws
307
296
  await serializeWorkspaceBundle(workspacePath, async () => {
308
- const current = (await getViewList(workspacePath)).some(view => view.id === viewId)
297
+ const current = (await listCompiledViews(workspacePath)).some(view => view.id === viewId)
309
298
  if (!current) throw new ViewMutationError('View not found', 404)
310
299
 
311
300
  try {
312
- await deleteViewSourceFiles(workspacePath, viewId)
301
+ await deleteViewSourceFiles(workspacePath, viewId, () => archiveViewSessions(ws, viewId))
313
302
  } catch (error) {
314
303
  if (error instanceof ViewSourceInUseError) throw new ViewMutationError(error.message, 409)
315
304
  throw error
316
305
  }
317
306
  reloadModules([`views/${viewId}`], workspacePath)
318
- await deleteViewBuilderForView(workspaceId, workspacePath, viewId)
307
+ await completeViewBuild(workspaceId, workspacePath, viewId)
319
308
  const layout = await loadLayout(workspacePath)
320
309
  const tab = viewTabId(viewId)
321
310
  await saveLayout(
@@ -331,7 +320,7 @@ export async function deleteView(
331
320
 
332
321
  publish({ type: 'view:deleted', workspaceId, name: viewId })
333
322
  publish({ type: 'workspace:updated' })
334
- await handleBundleViews(publish, workspaceId, workspacePath, false, false, viewId)
323
+ await handleBundleViews(publish, workspaceId, workspacePath, false, viewId)
335
324
  })
336
325
  }
337
326