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
@@ -27,13 +27,9 @@ import { moiContextSystemReminder, renderMoiContext } from '@/lib/moi-context'
27
27
  import { debug } from '../../debug'
28
28
  import { tapWire } from '../debug'
29
29
  import { broadcast } from '../../state'
30
- import { renameSelectedSession } from '../../selected-session'
31
- import { hasSessionConfig, renameSessionConfig, saveSessionConfig } from '../../session-config'
32
- import {
33
- markViewBuilderBuildingBySession,
34
- markViewBuilderWaitingBySession,
35
- renameViewBuilderSession
36
- } from '../../view-builders'
30
+ import { hasSessionConfig, saveSessionConfig } from '../../session-config'
31
+ import { renameSessionReferences } from '../../session-lifecycle'
32
+ import { claudeCodeSpawn } from '../../agent-launcher'
37
33
  import { resolveWorkspaceEnv } from '../../workspace-env'
38
34
  import { requireHarnessExecutable } from '../executable'
39
35
  import type { SendMessageInput } from '../types'
@@ -139,8 +135,6 @@ type LiveSession = {
139
135
  staleCli: boolean
140
136
  idleTimer: ReturnType<typeof setTimeout> | null
141
137
  closed: boolean
142
- // Passed to the view builder when the session becomes idle.
143
- lastBuilderError: string | undefined
144
138
  // Introspection only (surfaced by /status) — not load-bearing.
145
139
  createdAt: number
146
140
  lastActivityAt: number
@@ -405,12 +399,6 @@ function renameSession(s: LiveSession, realId: string): string {
405
399
  async function onSessionIdle(s: LiveSession) {
406
400
  const active = s.messages.active
407
401
  if (s.messages.dispatching || (active && !s.turnEnded)) return
408
- await markViewBuilderWaitingBySession(
409
- s.workspaceId,
410
- s.workspacePath,
411
- s.sessionId,
412
- s.lastBuilderError
413
- )
414
402
  if (s.closed || s.messages.dispatching || s.messages.active !== active) return
415
403
  active?.complete()
416
404
  s.messages.active = null
@@ -429,15 +417,7 @@ async function consume(s: LiveSession) {
429
417
  const realId = msg.session_id
430
418
  if (realId && realId !== s.sessionId) {
431
419
  const from = renameSession(s, realId)
432
- // Carry any config the picker wrote under the temp id to the real id.
433
- await renameSessionConfig(s.workspacePath, from, s.sessionId)
434
- await renameSelectedSession(s.workspacePath, from, s.sessionId)
435
- await renameViewBuilderSession(s.workspaceId, s.workspacePath, from, s.sessionId)
436
- broadcast(s.workspaceId, {
437
- type: 'session_renamed',
438
- from,
439
- to: s.sessionId
440
- })
420
+ await renameSessionReferences(s.workspaceId, s.workspacePath, from, s.sessionId)
441
421
  }
442
422
  startClaudeSessionTitleJob(s)
443
423
  // Seed explicit startup settings only when no saved picker choice exists.
@@ -531,12 +511,6 @@ async function consume(s: LiveSession) {
531
511
  !active || (!msg.queued_turn_count && (!consumed || consumed.includes(active.wireId)))
532
512
  if (turnFinished) s.turnEnded = true
533
513
  s.lastActivityAt = Date.now()
534
- // Remembered for the idle transition — the view builder shows the last
535
- // turn's error once the queue drains.
536
- s.lastBuilderError =
537
- msg.subtype === 'success'
538
- ? undefined
539
- : msg.errors.join('\n') || msg.subtype.replaceAll('_', ' ')
540
514
  debug(`cc result ws=${s.workspaceId} session=${s.sessionId} subtype=${msg.subtype}`)
541
515
  if (s.refreshSessionsOnResult) {
542
516
  s.refreshSessionsOnResult = false
@@ -560,7 +534,6 @@ async function consume(s: LiveSession) {
560
534
  sessionId: s.sessionId,
561
535
  content: message
562
536
  })
563
- await markViewBuilderWaitingBySession(s.workspaceId, s.workspacePath, s.sessionId, message)
564
537
  }
565
538
  } finally {
566
539
  // An expected restart only replaces the subprocess. An unexpected exit
@@ -624,6 +597,7 @@ function createLiveSession(input: {
624
597
  const options: Options = {
625
598
  abortController: abort,
626
599
  pathToClaudeCodeExecutable: requireHarnessExecutable('claude-code'),
600
+ spawnClaudeCodeProcess: claudeCodeSpawn(),
627
601
  // One query spans many user messages.
628
602
  maxTurns: 1000,
629
603
  cwd: input.workspacePath,
@@ -672,7 +646,6 @@ function createLiveSession(input: {
672
646
  staleCli: false,
673
647
  idleTimer: null,
674
648
  closed: false,
675
- lastBuilderError: undefined,
676
649
  createdAt: Date.now(),
677
650
  lastActivityAt: Date.now(),
678
651
  lastUserText: undefined,
@@ -830,7 +803,6 @@ async function dispatchNextMessage(messages: SessionMessages): Promise<void> {
830
803
  if (s.closed) throw new Error('Agent session closed before the message was sent')
831
804
  }
832
805
  }
833
- await markViewBuilderBuildingBySession(s.workspaceId, s.workspacePath, s.sessionId)
834
806
  if (cancelled()) return
835
807
  if (s.closed) throw new Error('Agent session closed before the message was sent')
836
808
  // A catalog refresh can arrive during any of the awaits above. Retry
@@ -926,7 +898,6 @@ export async function interruptCCSession(workspaceId: string, sessionId: string)
926
898
  }
927
899
  broadcast(s.workspaceId, { kind: 'stopped', sessionId: s.sessionId })
928
900
  if (!messages.active) setActivity(s, 'idle')
929
- await markViewBuilderWaitingBySession(s.workspaceId, s.workspacePath, s.sessionId)
930
901
  if (!s.closed && !messages.active) armIdle(s)
931
902
  void dispatchNextMessage(messages)
932
903
  }
@@ -14,7 +14,7 @@ import {
14
14
  isAttachmentOnlyPlaceholder,
15
15
  splitAttachmentNote
16
16
  } from '@/lib/attachment-note'
17
- import type { SessionInfo, StreamEvent } from '@/lib/types'
17
+ import type { SessionSummary, StreamEvent } from '@/lib/types'
18
18
 
19
19
  import { ClaudeAdapter } from './adapter'
20
20
 
@@ -52,7 +52,7 @@ export function visibleClaudeSessions<T extends Pick<SDKSessionInfo, 'tag'>>(ses
52
52
  return sessions.filter(session => session.tag !== MOI_ARCHIVED_SESSION_TAG)
53
53
  }
54
54
 
55
- export async function getSessions(workspacePath: string): Promise<SessionInfo[]> {
55
+ export async function getSessions(workspacePath: string): Promise<SessionSummary[]> {
56
56
  const sessions = visibleClaudeSessions(await listSessions({ dir: workspacePath }))
57
57
  return sessions.map(s => ({
58
58
  sessionId: s.sessionId,
@@ -142,16 +142,12 @@ export async function getSessionEvents(
142
142
  ): Promise<StreamEvent[]> {
143
143
  const adapter = new ClaudeAdapter()
144
144
  const events: StreamEvent[] = []
145
- try {
146
- const raw = await getSessionMessages(sessionId, { dir: workspacePath })
147
- for (const msg of raw) {
148
- // Disk replay carries no `stream_event` messages, so the adapter never
149
- // produces previews here — filter defensively to keep this the pure,
150
- // persisted StreamEvent path that reconnect-healing trusts.
151
- for (const ev of adapter.ingest(msg)) if (ev.kind !== 'preview') events.push(ev)
152
- }
153
- } catch {
154
- // session file missing or unreadable — return whatever we have (often [])
145
+ const raw = await getSessionMessages(sessionId, { dir: workspacePath })
146
+ for (const msg of raw) {
147
+ // Disk replay carries no `stream_event` messages, so the adapter never
148
+ // produces previews here — filter defensively to keep this the pure,
149
+ // persisted StreamEvent path that reconnect-healing trusts.
150
+ for (const ev of adapter.ingest(msg)) if (ev.kind !== 'preview') events.push(ev)
155
151
  }
156
152
  return events
157
153
  }
@@ -20,6 +20,7 @@ defines the protocol; generated types from the installed CLI define its exact wi
20
20
  | `permissions.ts` | Defines sandbox access and the default approval policy; rejects unsupported requests. |
21
21
  | `auth.ts`, `discovery.ts`, `status.ts` | Check login readiness, discover workspace paths from rollout heads, and report running processes. |
22
22
  | `session-title.ts` | Generates a title with a separate ephemeral `codex exec` call and applies it if the session is still unnamed. |
23
+ | `thread-list.ts` | Lists workspace threads from the state DB and hides agent-created tasks. |
23
24
  | `probe.ts` | Runs standalone protocol diagnostics without moi's session or workspace policy. |
24
25
 
25
26
  The shared contract and event layers are in [../README.md](../README.md).
@@ -54,7 +55,10 @@ reach the harness's 30-second RPC timeout before Bun closes the connection.
54
55
  ## Session lifecycle
55
56
 
56
57
  - A new chat starts under a temporary moi id. `thread/start` supplies the real
57
- id; `session_renamed` rekeys the chat, saved settings, and builder references.
58
+ id; `session_renamed` rekeys the chat, saved settings, and pending-build references.
59
+ - View handoffs pass the source chat's saved model to `thread/fork`. Codex 0.160.0
60
+ otherwise starts the fork with the configured default; switching an active-source
61
+ fork to `gpt-6.1-sol` on its first turn can fail with a `rustponsesapi` model error.
58
62
  - Concurrent resumes share one promise. Subscribe before `thread/resume`,
59
63
  buffer notifications while loading history, then apply them after the
60
64
  snapshot. Otherwise a live update can be overwritten by replay.
@@ -77,9 +81,24 @@ reach the harness's 30-second RPC timeout before Bun closes the connection.
77
81
  `thread/read` provides a static fallback when live resume fails.
78
82
 
79
83
  `thread/list` uses cwd filtering, `updated_at` ordering, and every cursor page.
80
- Repeated cursors fail instead of looping. Child-history loading is limited to
81
- four concurrent reads. Home-card previews reuse an existing app-server and read
82
- up to 50 recent sessions; rendering the home page does not spawn one per card.
84
+ Repeated cursors fail instead of looping. Listings pass `useStateDbOnly`: the
85
+ default mode decodes rollout heads from every workspace under
86
+ `$CODEX_HOME/sessions` (up to 10,000 files), which can exceed the RPC deadline
87
+ on large histories. Only the known state-database listing error falls back to
88
+ that scan; older CLIs ignore the field. CLI 0.162 reports code `-32603` with a
89
+ message ending in `failed to list threads from state database` (wrapped by the
90
+ thread store and app-server). Timeouts, disconnects, other RPC errors, and
91
+ app-server startup failures propagate so a failed refresh preserves cached chats.
92
+
93
+ The state DB also returns Codex Desktop tasks that an agent started through
94
+ `create_thread` (`threadSource: agent_created_thread`); the rollout scan drops
95
+ them only because their first input is a tool output, not a user message. moi
96
+ hides them. `thread/list` returns `threadSource` as null (CLI 0.162), so each
97
+ thread is read once with `thread/read` and its source is cached by id.
98
+
99
+ Child-history loading is limited to four concurrent reads. Home-card previews
100
+ reuse an existing app-server and read the same listing; rendering the home page
101
+ does not spawn one per card.
83
102
  Workspace import discovery separately reads up to 400 recent rollout heads
84
103
  under the server's `$CODEX_HOME/sessions`, without requiring a CLI executable.
85
104
 
@@ -13,7 +13,7 @@ import type {
13
13
  Turn
14
14
  } from '@/lib/format'
15
15
  import { stripMoiContextLoose } from '@/lib/moi-context'
16
- import type { McpServer, Model, SessionInfo } from '@/lib/types'
16
+ import type { McpServer, Model, SessionSummary } from '@/lib/types'
17
17
 
18
18
  import type { WorkspaceActivityPreview } from '../types'
19
19
 
@@ -97,6 +97,8 @@ export type CodexThread = {
97
97
  createdAt?: number
98
98
  updatedAt?: number
99
99
  name?: string | null
100
+ // Scalar label such as `user` or `agent_created_thread`; null in thread/list.
101
+ threadSource?: string | null
100
102
  status?: { type?: string; activeFlags?: string[] }
101
103
  turns?: CodexTurn[]
102
104
  }
@@ -143,11 +145,11 @@ function cleanPreview(preview: string | undefined): string {
143
145
  return preview ? formatChatTitle(stripMoiContextLoose(preview)) : ''
144
146
  }
145
147
 
146
- export function codexThreadToSessionInfo(t: CodexThread): SessionInfo {
148
+ export function codexThreadToSessionInfo(t: CodexThread): SessionSummary {
147
149
  return {
148
150
  sessionId: t.id,
149
151
  summary: t.name?.trim() || cleanPreview(t.preview),
150
- // Codex timestamps are unix seconds; SessionInfo wants millis.
152
+ // Codex timestamps are unix seconds; moi uses milliseconds.
151
153
  lastModified: (t.updatedAt ?? t.createdAt ?? 0) * 1000,
152
154
  cwd: t.cwd
153
155
  }
@@ -1,7 +1,7 @@
1
1
  // One app-server per workspace: environment is fixed at process spawn, while
2
2
  // threads share the connection. Framing lives in transport.ts; see NOTES.md
3
3
  // for lifecycle, configuration, and wire-type maintenance.
4
- import type { McpServer, Model, SessionInfo, StreamEvent } from '@/lib/types'
4
+ import type { McpServer, Model, SessionSummary, StreamEvent } from '@/lib/types'
5
5
 
6
6
  import {
7
7
  type CodexModel,
@@ -20,6 +20,8 @@ import type { WorkspaceActivityPreview } from '../types'
20
20
  import { findHarnessExecutable, requireHarnessExecutable } from '../executable'
21
21
  import { createCodexTransport, type Json, type NotificationListener } from './transport'
22
22
  import { readCodexPages } from './pagination'
23
+ import { listCodexThreads } from './thread-list'
24
+ import { agentCommand } from '../../agent-launcher'
23
25
  import { debug } from '../../debug'
24
26
  import { tapWire } from '../debug'
25
27
  import { resolveWorkspaceEnv } from '../../workspace-env'
@@ -123,7 +125,7 @@ async function startClient(workspacePath: string): Promise<ClientRecord> {
123
125
 
124
126
  const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
125
127
  const startedAt = Date.now()
126
- const proc = Bun.spawn([bin, 'app-server'], {
128
+ const proc = Bun.spawn(agentCommand([bin, 'app-server']), {
127
129
  cwd: workspacePath,
128
130
  stdin: 'pipe',
129
131
  stdout: 'pipe',
@@ -261,19 +263,11 @@ export function killAllCodexClients(): void {
261
263
  // ---- discovery (sessions list / models / cold history) -----------------------
262
264
 
263
265
  // Threads whose recorded cwd is exactly the workspace path, newest first.
264
- export async function getCodexSessions(workspacePath: string): Promise<SessionInfo[]> {
265
- try {
266
- const client = await getCodexClient(workspacePath)
267
- const threads = await readCodexPages<CodexThread>(client, 'thread/list', {
268
- cwd: workspacePath,
269
- limit: 100,
270
- sortKey: 'updated_at'
271
- })
272
- return threads.map(codexThreadToSessionInfo)
273
- } catch (err) {
274
- console.error('[codex] thread/list failed', err)
275
- return []
276
- }
266
+ export async function getCodexSessions(workspacePath: string): Promise<SessionSummary[]> {
267
+ // Startup and listing failures must both preserve the client's cached history.
268
+ const client = await getCodexClient(workspacePath)
269
+ const threads = await listCodexThreads(client, workspacePath)
270
+ return threads.map(codexThreadToSessionInfo)
277
271
  }
278
272
 
279
273
  export async function archiveCodexThread(
@@ -304,12 +298,10 @@ export async function getCodexWorkspacePreview(
304
298
  const client = await peekCodexClient(workspacePath)
305
299
  if (!client) return {}
306
300
  try {
307
- const res = await client.rpc<{ data?: CodexThread[] }>('thread/list', {
308
- cwd: workspacePath,
309
- limit: 50,
310
- sortKey: 'updated_at'
311
- })
312
- return selectCodexWorkspacePreview(res.data ?? [], includeFirstUserMessage)
301
+ // Every page: agent-created tasks are filtered after listing and could
302
+ // fill a single page.
303
+ const threads = await listCodexThreads(client, workspacePath)
304
+ return selectCodexWorkspacePreview(threads, includeFirstUserMessage)
313
305
  } catch {
314
306
  return {}
315
307
  }
@@ -1,6 +1,9 @@
1
1
  // Codex as a Harness. Thin wiring over this folder's modules — see
2
2
  // ../types.ts for the contract and ../README.md for the architecture.
3
3
  import type { Harness } from '../types'
4
+ import { ForkUnsupportedError } from '../fork'
5
+ import { CodexRpcError } from './transport'
6
+ import { getCodexClient } from './client'
4
7
  import { findHarnessExecutable, pathHarnessAvailability } from '../executable'
5
8
  import { getCodexAuthReadiness, startCodexLogin } from './auth'
6
9
  import {
@@ -39,6 +42,21 @@ export const codexHarness: Harness = {
39
42
  sendMessage: input => sendCodexMessage(input),
40
43
  interrupt: (workspaceId, sessionId) => interruptCodexRun({ workspaceId, sessionId }),
41
44
  archiveSession: (ws, sessionId) => archiveCodexSession(ws.path, sessionId),
45
+ forkSession: async (ws, sourceId, { model }) => {
46
+ const client = await getCodexClient(ws.path)
47
+ const { thread } = await client
48
+ .rpc<{ thread: { id: string } }>('thread/fork', {
49
+ threadId: sourceId,
50
+ // A live fork must start with its selected model, before its first turn.
51
+ ...(model ? { model } : {})
52
+ })
53
+ .catch(error => {
54
+ if (error instanceof CodexRpcError && error.code === -32601)
55
+ throw new ForkUnsupportedError('This Codex runtime does not support chat forks')
56
+ throw error
57
+ })
58
+ return thread.id
59
+ },
42
60
  activeSessions: () => getCodexActiveSessions(),
43
61
 
44
62
  listSessions: ws => getCodexSessions(ws.path),
@@ -44,9 +44,8 @@ import { generateCodexSessionTitle, renameCodexSessionIfUnchanged } from './sess
44
44
  import { agentStore } from '../../agent'
45
45
  import { debug } from '../../debug'
46
46
  import { broadcast } from '../../state'
47
- import { renameSelectedSession } from '../../selected-session'
48
- import { hasSessionConfig, renameSessionConfig, saveSessionConfig } from '../../session-config'
49
- import { renameViewBuilderSession } from '../../view-builders'
47
+ import { hasSessionConfig, saveSessionConfig } from '../../session-config'
48
+ import { renameSessionReferences } from '../../session-lifecycle'
50
49
 
51
50
  type CodexUserInputItem = { type: 'text'; text: string } | { type: 'image'; url: string }
52
51
 
@@ -952,20 +951,12 @@ async function sendMessage(
952
951
  if (realId !== input.sessionId) {
953
952
  aliases.set(recKey(input.workspaceId, input.sessionId), realId)
954
953
  sendLanes.set(recKey(input.workspaceId, realId), lane)
955
- await renameSessionConfig(input.workspacePath, input.sessionId, realId)
956
- await renameSelectedSession(input.workspacePath, input.sessionId, realId)
957
- // Builder tabs follow the same temporary-to-real session rename.
958
- await renameViewBuilderSession(
954
+ await renameSessionReferences(
959
955
  input.workspaceId,
960
956
  input.workspacePath,
961
957
  input.sessionId,
962
958
  realId
963
959
  )
964
- broadcast(input.workspaceId, {
965
- type: 'session_renamed',
966
- from: input.sessionId,
967
- to: realId
968
- })
969
960
  }
970
961
  rec = createRecord({
971
962
  workspaceId: input.workspaceId,
@@ -1002,7 +993,7 @@ async function sendMessage(
1002
993
  content: err instanceof Error ? err.message : 'failed to start codex session'
1003
994
  })
1004
995
  refreshAvailability(input.workspaceId, input.workspacePath)
1005
- return
996
+ throw err
1006
997
  }
1007
998
 
1008
999
  if (lane.generation !== generation) return
@@ -1029,7 +1020,7 @@ async function sendMessage(
1029
1020
  terminal: !rec.activeTurnId
1030
1021
  })
1031
1022
  if (!rec.activeTurnId) setProcessing(rec, false, null)
1032
- return
1023
+ throw error
1033
1024
  }
1034
1025
  if (lane.generation !== generation) return
1035
1026
  }
@@ -1129,6 +1120,7 @@ async function sendMessage(
1129
1120
  terminal: !rec.activeTurnId
1130
1121
  })
1131
1122
  refreshAvailability(rec.workspaceId, rec.workspacePath)
1123
+ throw err
1132
1124
  }
1133
1125
  }
1134
1126
 
@@ -0,0 +1,74 @@
1
+ import type { CodexThread } from './adapter'
2
+ import type { CodexClient } from './client'
3
+ import { readCodexPages } from './pagination'
4
+ import { CodexRpcError } from './transport'
5
+
6
+ type RpcClient = Pick<CodexClient, 'rpc'>
7
+
8
+ // Codex Desktop labels tasks its agent starts through `create_thread`. moi
9
+ // lists only chats a person started.
10
+ const AGENT_CREATED_THREAD_SOURCE = 'agent_created_thread'
11
+
12
+ // Fixed at thread/start, so entries never go stale. thread/list leaves the
13
+ // field null (CLI 0.162), so each thread is read once per server process.
14
+ const threadSources = new Map<string, string | undefined>()
15
+
16
+ // The default listing scans every rollout under $CODEX_HOME/sessions, so its
17
+ // cost grows with history from all workspaces and can exceed the RPC deadline.
18
+ // Only Codex's known database-listing error falls back to the scan. Older CLIs
19
+ // ignore useStateDbOnly; transport failures must not trigger another slow lookup.
20
+ export async function listCodexThreads(
21
+ client: RpcClient,
22
+ workspacePath: string
23
+ ): Promise<CodexThread[]> {
24
+ const list = (useStateDbOnly: boolean) =>
25
+ readCodexPages<CodexThread>(client, 'thread/list', {
26
+ cwd: workspacePath,
27
+ limit: 100,
28
+ sortKey: 'updated_at',
29
+ useStateDbOnly
30
+ })
31
+ let threads: CodexThread[]
32
+ try {
33
+ threads = await list(true)
34
+ } catch (err) {
35
+ // CLI 0.162 wraps the rollout error with thread-store context, but supplies
36
+ // no distinct error code for an unavailable DB. Match its specific suffix.
37
+ if (
38
+ !(err instanceof CodexRpcError) ||
39
+ err.code !== -32603 ||
40
+ !err.message.endsWith('failed to list threads from state database')
41
+ )
42
+ throw err
43
+ console.error('[codex] state DB thread/list failed; scanning rollouts', err)
44
+ threads = await list(false)
45
+ }
46
+ return withoutAgentCreatedThreads(client, threads)
47
+ }
48
+
49
+ async function withoutAgentCreatedThreads(
50
+ client: RpcClient,
51
+ threads: CodexThread[]
52
+ ): Promise<CodexThread[]> {
53
+ for (const thread of threads)
54
+ if (thread.threadSource) threadSources.set(thread.id, thread.threadSource)
55
+ const unknown = threads.filter(thread => !threadSources.has(thread.id))
56
+ let index = 0
57
+ await Promise.all(
58
+ Array.from({ length: Math.min(4, unknown.length) }, async () => {
59
+ while (index < unknown.length) {
60
+ const { id } = unknown[index++]
61
+ try {
62
+ const res = await client.rpc<{ thread?: CodexThread }>('thread/read', {
63
+ threadId: id,
64
+ includeTurns: false
65
+ })
66
+ threadSources.set(id, res.thread?.threadSource ?? undefined)
67
+ } catch {
68
+ // Unread threads stay listed and are retried on the next listing.
69
+ }
70
+ }
71
+ })
72
+ )
73
+ return threads.filter(thread => threadSources.get(thread.id) !== AGENT_CREATED_THREAD_SOURCE)
74
+ }
@@ -0,0 +1,12 @@
1
+ import type { StreamEvent } from '@/lib/types'
2
+ import { applyEvents } from '@/lib/format'
3
+
4
+ export class ForkUnsupportedError extends Error {}
5
+
6
+ export function inheritedHistoryBoundary(events: StreamEvent[]) {
7
+ const view = applyEvents(events)
8
+ return {
9
+ forkedThroughMessageId: view.turns.at(-1)?.id,
10
+ forkedNoticeIds: view.notices.map(notice => notice.id)
11
+ }
12
+ }
@@ -10,7 +10,7 @@
10
10
  // per-frame path the live session uses.
11
11
  import { replayAttachmentParts, stripAttachmentsLoose } from '@/lib/moi-attachments'
12
12
  import type { Part, StreamEvent, ToolCall, ToolState, Turn, TurnMeta } from '@/lib/format'
13
- import type { SessionInfo } from '@/lib/types'
13
+ import type { SessionSummary } from '@/lib/types'
14
14
 
15
15
  import type {
16
16
  OpenClawContentBlock,
@@ -34,7 +34,7 @@ function cleanTitle(text: string | undefined): string {
34
34
  ).trim()
35
35
  }
36
36
 
37
- export function toSessionInfo(row: OpenClawSessionRow, cwd: string): SessionInfo {
37
+ export function toSessionInfo(row: OpenClawSessionRow, cwd: string): SessionSummary {
38
38
  const summary =
39
39
  cleanTitle(row.label) ||
40
40
  cleanTitle(row.displayName) ||
@@ -51,7 +51,7 @@ export function toSessionInfo(row: OpenClawSessionRow, cwd: string): SessionInfo
51
51
  provider && provider !== 'webchat' ? { provider, ...(label ? { label } : {}) } : undefined
52
52
  // Flavor from the gateway key layout: cron buckets are `…:cron:<jobId>`,
53
53
  // spawned subagents carry `spawnedBy` (and live under `…:subagent:<uuid>`).
54
- const flavor: SessionInfo['flavor'] = row.key.includes(':cron:')
54
+ const flavor: SessionSummary['flavor'] = row.key.includes(':cron:')
55
55
  ? 'cron'
56
56
  : row.spawnedBy || row.key.includes(':subagent:')
57
57
  ? 'subagent'
@@ -31,7 +31,6 @@ import {
31
31
  type OpenClawSessionDetail,
32
32
  getOpenClawSessionMessages
33
33
  } from './discovery'
34
- import { renameSelectedSession } from '../../selected-session'
35
34
  import {
36
35
  type ToolResultInfo,
37
36
  findToolCallOwners,
@@ -47,11 +46,7 @@ import {
47
46
  } from './gateway'
48
47
  import { recordOpenClawThinkingProfile, recordOpenClawThinkingRejection } from './thinking'
49
48
  import { broadcast } from '../../state'
50
- import {
51
- markViewBuilderBuildingBySession,
52
- markViewBuilderWaitingBySession,
53
- renameViewBuilderSession
54
- } from '../../view-builders'
49
+ import { renameSessionReferences } from '../../session-lifecycle'
55
50
 
56
51
  type OpenClawSessionKey = string // the gateway-side composite key, e.g. `agent:main:main`
57
52
 
@@ -228,11 +223,6 @@ function setProcessing(rec: SessionRecord, processing: boolean, runId: string |
228
223
  sessionId: rec.sessionId,
229
224
  activity: processing ? 'running' : 'idle'
230
225
  })
231
- if (processing) {
232
- void markViewBuilderBuildingBySession(rec.workspaceId, rec.workspacePath, rec.sessionId)
233
- } else {
234
- void markViewBuilderWaitingBySession(rec.workspaceId, rec.workspacePath, rec.sessionId)
235
- }
236
226
  }
237
227
 
238
228
  function clearIdleTimer(rec: SessionRecord): void {
@@ -1344,18 +1334,12 @@ async function sendOpenClawMessageImpl(input: {
1344
1334
  })
1345
1335
  if (created?.sessionId && created.sessionId !== input.sessionId) {
1346
1336
  realSessionId = created.sessionId
1347
- await renameSelectedSession(input.workspacePath, input.sessionId, realSessionId)
1348
- await renameViewBuilderSession(
1337
+ await renameSessionReferences(
1349
1338
  input.workspaceId,
1350
1339
  input.workspacePath,
1351
1340
  input.sessionId,
1352
1341
  realSessionId
1353
1342
  )
1354
- broadcast(input.workspaceId, {
1355
- type: 'session_renamed',
1356
- from: input.sessionId,
1357
- to: realSessionId
1358
- })
1359
1343
  }
1360
1344
  }
1361
1345
  rec = await getOrCreateOpenClawSession({
@@ -1378,12 +1362,6 @@ async function sendOpenClawMessageImpl(input: {
1378
1362
  sessionId: realSessionId,
1379
1363
  content: message
1380
1364
  })
1381
- await markViewBuilderWaitingBySession(
1382
- input.workspaceId,
1383
- input.workspacePath,
1384
- realSessionId,
1385
- message
1386
- )
1387
1365
  throw err
1388
1366
  }
1389
1367
 
@@ -1429,12 +1407,6 @@ async function sendOpenClawMessageImpl(input: {
1429
1407
  sessionId: rec.sessionId,
1430
1408
  content: message
1431
1409
  })
1432
- await markViewBuilderWaitingBySession(
1433
- rec.workspaceId,
1434
- rec.workspacePath,
1435
- rec.sessionId,
1436
- message
1437
- )
1438
1410
  throw err
1439
1411
  }
1440
1412
  }
@@ -1,6 +1,8 @@
1
1
  import { join } from 'node:path'
2
2
  import { tmpdir } from 'node:os'
3
- import { mkdtemp, rm } from 'node:fs/promises'
3
+ import { chmod, mkdtemp, rm } from 'node:fs/promises'
4
+
5
+ import { agentCommand } from '../agent-launcher'
4
6
 
5
7
  const MAX_TITLE_SOURCE_LENGTH = 1_000
6
8
  const MAX_GENERATED_TITLE_LENGTH = 64
@@ -71,7 +73,7 @@ export async function runSessionTitleCommand(input: {
71
73
  }): Promise<string | null> {
72
74
  if (input.signal.aborted) return null
73
75
  try {
74
- const proc = Bun.spawn([...input.command], {
76
+ const proc = Bun.spawn(agentCommand(input.command), {
75
77
  cwd: input.cwd,
76
78
  stdin: new Blob([input.stdin ?? '']),
77
79
  stdout: 'pipe',
@@ -87,8 +89,15 @@ export async function runSessionTitleCommand(input: {
87
89
  }
88
90
  }
89
91
 
92
+ // On managed machines the title command runs as the agent's user, which is
93
+ // neither the folder's owner nor in its group, so the folder is open to
94
+ // everyone: the agent works in it and Codex writes its answer there. It holds
95
+ // only the schema and the title, for one run. moi stays the owner, which is
96
+ // what lets it remove the folder from /tmp afterwards.
90
97
  export async function createSessionTitleTempDir(): Promise<string> {
91
- return mkdtemp(join(tmpdir(), 'moi-session-title-'))
98
+ const path = await mkdtemp(join(tmpdir(), 'moi-session-title-'))
99
+ await chmod(path, 0o777)
100
+ return path
92
101
  }
93
102
 
94
103
  export async function removeSessionTitleTempDir(path: string): Promise<void> {
@@ -10,7 +10,8 @@ import type {
10
10
  McpServer,
11
11
  Model,
12
12
  SessionActivity,
13
- SessionInfo,
13
+ SessionConfig,
14
+ SessionSummary,
14
15
  StreamEvent,
15
16
  WorkspaceEntry,
16
17
  WorkspaceType
@@ -83,13 +84,17 @@ export type Harness = {
83
84
  interrupt(workspaceId: string, sessionId: string): Promise<void>
84
85
  // Optional because some providers do not expose an archive operation.
85
86
  archiveSession?(ws: WorkspaceEntry, sessionId: string): Promise<void>
87
+ // Silent native fork, returning its durable child id. Apply sourceConfig at
88
+ // creation if the backend needs it there. The caller copies the full config
89
+ // to the child and passes it on the first send, before any work starts.
90
+ forkSession?(ws: WorkspaceEntry, sessionId: string, sourceConfig: SessionConfig): Promise<string>
86
91
  // Every session whose activity is not `idle`, across all workspaces (drives
87
- // the status snapshot and view-builder reconciliation). Activity is mirrored
92
+ // the status snapshot and pending-view progress). Activity is mirrored
88
93
  // from the backend's native lifecycle signal, never derived by counting.
89
94
  activeSessions(): { workspaceId: string; sessionId: string; activity: SessionActivity }[]
90
95
 
91
96
  // -- discovery / metadata ---------------------------------------------------
92
- listSessions(ws: WorkspaceEntry): Promise<SessionInfo[]>
97
+ listSessions(ws: WorkspaceEntry): Promise<SessionSummary[]>
93
98
  // Home-page card preview. Called for every card on the home screen, so
94
99
  // implementations must stay cheap: no process spawns, no per-session
95
100
  // transcript reads unless cached. Failures resolve to {} — the card