moi-computer 0.11.1-next.5 → 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 (141) 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/attachments/draft-attachments.ts +21 -4
  15. package/client/features/chat/composer/useWorkspaceComposerState.tsx +3 -3
  16. package/client/features/chat/connection/chat-frames.ts +14 -7
  17. package/client/features/chat/messages/ChatEmptyState.tsx +33 -19
  18. package/client/features/chat/messages/MarkdownContent.tsx +3 -3
  19. package/client/features/chat/messages/fork-history.ts +14 -0
  20. package/client/features/chat/sessions/ChatSelector.tsx +138 -79
  21. package/client/features/chat/sessions/api.ts +109 -19
  22. package/client/features/chat/sessions/browser-tab-state.ts +30 -7
  23. package/client/features/chat/sessions/useSelectedSession.ts +217 -51
  24. package/client/features/chat/useChat.ts +43 -45
  25. package/client/features/collab/client.ts +10 -11
  26. package/client/features/collab/hooks.tsx +6 -11
  27. package/client/features/collab/host-state.ts +57 -128
  28. package/client/features/collab/provider.tsx +3 -3
  29. package/client/features/collab/testing/fake-engine.ts +6 -27
  30. package/client/features/collab/workspace-users-menu.tsx +3 -7
  31. package/client/features/drawings/{useViewBuilderSketch.ts → useViewSketch.ts} +7 -7
  32. package/client/features/home/HomePage.tsx +2 -2
  33. package/client/features/overview/Overview.tsx +3 -6
  34. package/client/features/overview/default/ViewsWidget.tsx +5 -12
  35. package/client/features/overview/default/registry.tsx +2 -4
  36. package/client/features/views/PendingViewScreen.tsx +279 -0
  37. package/client/features/views/ViewManager.tsx +10 -10
  38. package/client/features/views/api.ts +63 -130
  39. package/client/features/views/useViewActions.ts +151 -0
  40. package/client/features/views/useViewDrafts.ts +79 -0
  41. package/client/features/views/view-presentation.ts +4 -5
  42. package/client/features/views/view-submission.ts +88 -0
  43. package/client/features/workspace/WorkspaceMenu.tsx +63 -0
  44. package/client/features/workspace/WorkspaceScreen.tsx +180 -375
  45. package/client/features/workspace/browser-tab-state.ts +16 -9
  46. package/client/features/workspace/moi-context.ts +13 -15
  47. package/client/features/workspace/tab-resolution.ts +16 -29
  48. package/client/features/workspace/useWorkspaceNavigation.ts +146 -104
  49. package/client/index.tsx +5 -1
  50. package/client/runtime/useWorkspaceEvents.ts +7 -6
  51. package/client/store/ui.ts +25 -29
  52. package/dist/chunk-1zhnhy00.js +1 -0
  53. package/dist/chunk-27501vke.js +1 -0
  54. package/dist/{chunk-jf6czgrz.js → chunk-9xtv6djt.js} +2 -2
  55. package/dist/chunk-am1x230f.js +2 -0
  56. package/dist/{chunk-nez8sdta.js → chunk-darpsw65.js} +1 -1
  57. package/dist/{chunk-97eg9mjn.js → chunk-gps4qc38.js} +1 -1
  58. package/dist/{chunk-3a48fyf7.js → chunk-hzwr8dp8.js} +4 -4
  59. package/dist/{chunk-efdyz6xp.js → chunk-j905va8r.js} +1 -1
  60. package/dist/chunk-n33w9y38.js +10 -0
  61. package/dist/chunk-r63ks44z.js +68 -0
  62. package/dist/{chunk-vfpsc75k.js → chunk-vqpkqtdr.js} +1 -1
  63. package/dist/chunk-wd46nk26.css +1 -0
  64. package/dist/chunk-xgt7vxt9.js +1 -0
  65. package/dist/{chunk-z3byfve5.js → chunk-yvzhwtfa.js} +2 -2
  66. package/dist/index.html +1 -1
  67. package/lib/ids.ts +2 -5
  68. package/lib/moi-context.ts +100 -73
  69. package/lib/navigation.ts +48 -87
  70. package/lib/session-drafts.ts +10 -0
  71. package/lib/types.ts +64 -31
  72. package/lib/view-build-directives.ts +12 -0
  73. package/lib/workspace-layout.ts +1 -1
  74. package/lib/workspace-tabs.ts +12 -7
  75. package/package.json +3 -1
  76. package/server/agent-launcher.ts +27 -0
  77. package/server/api.ts +119 -209
  78. package/server/app-config.ts +21 -2
  79. package/server/applets/build-worker.ts +2 -1
  80. package/server/applets/view-source.ts +7 -1
  81. package/server/cli-env.ts +72 -50
  82. package/server/cli.ts +127 -70
  83. package/server/control.ts +82 -63
  84. package/server/data-dir.ts +13 -0
  85. package/server/functions.ts +2 -1
  86. package/server/harness/README.md +8 -0
  87. package/server/harness/acp/adapter.ts +2 -2
  88. package/server/harness/acp/client.ts +2 -1
  89. package/server/harness/acp/discovery.ts +3 -3
  90. package/server/harness/acp/session.ts +6 -9
  91. package/server/harness/claude-code/adapter.ts +13 -8
  92. package/server/harness/claude-code/auth.ts +3 -2
  93. package/server/harness/claude-code/cli.ts +3 -1
  94. package/server/harness/claude-code/git-worktree.ts +5 -2
  95. package/server/harness/claude-code/index.ts +5 -0
  96. package/server/harness/claude-code/mcp.ts +2 -0
  97. package/server/harness/claude-code/models.ts +2 -0
  98. package/server/harness/claude-code/session.ts +5 -34
  99. package/server/harness/claude-code/sessions.ts +8 -12
  100. package/server/harness/codex/NOTES.md +23 -4
  101. package/server/harness/codex/adapter.ts +5 -3
  102. package/server/harness/codex/client.ts +13 -21
  103. package/server/harness/codex/index.ts +18 -0
  104. package/server/harness/codex/session.ts +6 -14
  105. package/server/harness/codex/thread-list.ts +74 -0
  106. package/server/harness/fork.ts +12 -0
  107. package/server/harness/openclaw/adapter.ts +3 -3
  108. package/server/harness/openclaw/session.ts +2 -30
  109. package/server/harness/session-title.ts +12 -3
  110. package/server/harness/types.ts +8 -3
  111. package/server/moi-scaffold.ts +53 -20
  112. package/server/pending-views.ts +164 -0
  113. package/server/registry.ts +14 -4
  114. package/server/selected-session.ts +91 -44
  115. package/server/service.ts +16 -2
  116. package/server/session-archive.ts +32 -0
  117. package/server/session-config.ts +16 -111
  118. package/server/session-lifecycle.ts +17 -0
  119. package/server/session-store.ts +127 -0
  120. package/server/status.ts +3 -1
  121. package/server/tabs.ts +7 -10
  122. package/server/view-sessions.ts +267 -0
  123. package/server/views.ts +30 -41
  124. package/server/web.ts +47 -45
  125. package/server/workspace-env.ts +27 -0
  126. package/server/workspace-init.ts +12 -5
  127. package/workspace/.claude/skills/moi-workspace/SKILL.md +49 -20
  128. package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +2 -5
  129. package/client/features/views/ViewBuilder.tsx +0 -239
  130. package/client/features/views/useViewBuilderActions.ts +0 -103
  131. package/client/features/views/useViewBuilderDrafts.ts +0 -68
  132. package/dist/chunk-2jncyq65.js +0 -1
  133. package/dist/chunk-9zpvdws4.js +0 -68
  134. package/dist/chunk-h2kj1ysj.js +0 -1
  135. package/dist/chunk-hvj7tp3y.js +0 -1
  136. package/dist/chunk-nzwgm8vc.css +0 -1
  137. package/dist/chunk-ryg9z3kn.js +0 -10
  138. package/dist/chunk-tpn177bt.js +0 -2
  139. package/lib/view-builder-directives.ts +0 -16
  140. package/server/chat-selection.ts +0 -22
  141. package/server/view-builders.ts +0 -453
@@ -1,136 +1,41 @@
1
- import { mkdir, rename } from 'node:fs/promises'
2
- import { join } from 'path'
3
-
4
1
  import type { SessionConfig } from '@/lib/types'
2
+ import { getSessionRecords, updateSessionRecords } from './session-store'
5
3
 
6
- import { DATA_DIR } from './data-dir'
7
-
8
- // Per-session model/effort/Fast-mode overrides. Stored OUTSIDE
9
- // the user's workspace (no repo churn) in ONE global JSON file in moi's data
10
- // dir, alongside the workspace registry. Keyed by workspace path then sessionId:
11
- // { "<workspacePath>": { "<sessionId>": { model?, effort?, fastMode? } } }
12
- // Path (not registry id) is the key so config survives re-registration and lines
13
- // up with the SDK's path-based session storage.
14
-
15
- // A patch may clear a field with `null` (vs `undefined`, which leaves it alone).
4
+ // null clears a setting; undefined leaves it unchanged.
16
5
  export type SessionConfigPatch = {
17
6
  model?: string | null
18
7
  effort?: string | null
19
8
  fastMode?: boolean | null
20
9
  }
21
10
 
22
- type Store = Record<string, Record<string, SessionConfig>>
23
-
24
- export const DEFAULT_SESSION_CONFIG_PATH = join(DATA_DIR, 'session-config.json')
25
-
26
- let storePath = DEFAULT_SESSION_CONFIG_PATH
27
-
28
- // Test seam: point the store at a scratch file (mirrors registry.setRegistryPath).
29
- export function setSessionConfigPath(path: string): void {
30
- storePath = path
31
- }
32
-
33
- function clean(cfg: SessionConfig | undefined): SessionConfig {
34
- const out: SessionConfig = {}
35
- if (typeof cfg?.model === 'string') out.model = cfg.model
36
- if (typeof cfg?.effort === 'string') out.effort = cfg.effort
37
- if (typeof cfg?.fastMode === 'boolean') out.fastMode = cfg.fastMode
38
- return out
39
- }
40
-
41
- function isEmpty(cfg: SessionConfig): boolean {
42
- return cfg.model === undefined && cfg.effort === undefined && cfg.fastMode === undefined
43
- }
44
-
45
- async function readStoreFile(path: string): Promise<Store | null> {
46
- try {
47
- const parsed = JSON.parse(await Bun.file(path).text())
48
- return parsed && typeof parsed === 'object' ? (parsed as Store) : {}
49
- } catch {
50
- return null
51
- }
52
- }
53
-
54
- async function writeStore(store: Store): Promise<void> {
55
- await mkdir(join(storePath, '..'), { recursive: true })
56
- const tmp = `${storePath}.${process.pid}.tmp`
57
- await Bun.write(tmp, JSON.stringify(store, null, 2))
58
- await rename(tmp, storePath)
59
- }
60
-
61
- async function readStore(): Promise<Store> {
62
- return (await readStoreFile(storePath)) ?? {}
63
- }
64
-
65
- // Serialize read-modify-write so concurrent save/rename calls can't clobber the
66
- // single shared file (last writer would otherwise drop the other's update).
67
- let writeChain: Promise<unknown> = Promise.resolve()
68
- function locked<T>(fn: () => Promise<T>): Promise<T> {
69
- const run = writeChain.then(fn, fn)
70
- writeChain = run.catch(() => {})
71
- return run
72
- }
73
-
74
11
  export async function getSessionConfig(
75
12
  workspacePath: string,
76
13
  sessionId: string
77
14
  ): Promise<SessionConfig> {
78
- return locked(async () => {
79
- const store = await readStore()
80
- return clean(store[workspacePath]?.[sessionId])
81
- })
15
+ return (await getSessionRecords(workspacePath))[sessionId]?.config ?? {}
82
16
  }
83
17
 
84
18
  export async function hasSessionConfig(workspacePath: string, sessionId: string): Promise<boolean> {
85
- return !isEmpty(await getSessionConfig(workspacePath, sessionId))
19
+ return Object.keys(await getSessionConfig(workspacePath, sessionId)).length > 0
86
20
  }
87
21
 
88
- // Merge a patch over the stored config and write it back. `null` clears a field,
89
- // `undefined` leaves it untouched, and a typed value sets it. An emptied entry
90
- // is dropped to keep the file tidy. Returns the merged config.
91
22
  export async function saveSessionConfig(
92
23
  workspacePath: string,
93
24
  sessionId: string,
94
25
  patch: SessionConfigPatch
95
26
  ): Promise<SessionConfig> {
96
- return locked(async () => {
97
- const store = await readStore()
98
- const sessions = store[workspacePath] ?? {}
99
- const next = clean(sessions[sessionId])
100
- for (const key of ['model', 'effort'] as const) {
101
- const value = patch[key]
102
- if (value === undefined) continue
103
- if (value === null) delete next[key]
104
- else next[key] = value
27
+ let config: SessionConfig = {}
28
+ await updateSessionRecords(workspacePath, sessions => {
29
+ const record = (sessions[sessionId] ??= {})
30
+ config = { ...record.config }
31
+ for (const key of ['model', 'effort', 'fastMode'] as const) {
32
+ if (patch[key] === null) delete config[key]
105
33
  }
106
- if (patch.fastMode === null) delete next.fastMode
107
- else if (patch.fastMode !== undefined) next.fastMode = patch.fastMode
108
- if (isEmpty(next)) delete sessions[sessionId]
109
- else sessions[sessionId] = next
110
- if (Object.keys(sessions).length === 0) delete store[workspacePath]
111
- else store[workspacePath] = sessions
112
- await writeStore(store)
113
- return next
114
- })
115
- }
116
-
117
- // Move a session's config from one id to another (temp id → SDK real id on
118
- // rename). Merges onto whatever the destination already holds (destination wins,
119
- // so a concurrent write under the real id isn't lost) and removes the source.
120
- export async function renameSessionConfig(
121
- workspacePath: string,
122
- from: string,
123
- to: string
124
- ): Promise<void> {
125
- if (from === to) return
126
- await locked(async () => {
127
- const store = await readStore()
128
- const sessions = store[workspacePath]
129
- const src = clean(sessions?.[from])
130
- if (isEmpty(src)) return
131
- sessions![to] = { ...src, ...clean(sessions![to]) }
132
- delete sessions![from]
133
- store[workspacePath] = sessions!
134
- await writeStore(store)
34
+ if (typeof patch.model === 'string') config.model = patch.model
35
+ if (typeof patch.effort === 'string') config.effort = patch.effort
36
+ if (typeof patch.fastMode === 'boolean') config.fastMode = patch.fastMode
37
+ if (Object.keys(config).length) record.config = config
38
+ else delete record.config
135
39
  })
40
+ return config
136
41
  }
@@ -0,0 +1,17 @@
1
+ import { renameSessionRecord } from './session-store'
2
+ import { renameSelectedSession } from './selected-session'
3
+ import { renameViewExecutionSession } from './pending-views'
4
+ import { broadcast } from './state'
5
+
6
+ export async function renameSessionReferences(
7
+ workspaceId: string,
8
+ workspacePath: string,
9
+ from: string,
10
+ to: string
11
+ ) {
12
+ if (from === to) return
13
+ await renameSessionRecord(workspacePath, from, to)
14
+ await renameSelectedSession(workspacePath, from, to)
15
+ await renameViewExecutionSession(workspaceId, workspacePath, from, to)
16
+ broadcast(workspaceId, { type: 'session_renamed', from, to })
17
+ }
@@ -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
+ }