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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/client/api/workspace-keys.ts +2 -2
  2. package/client/app/AppRouter.tsx +0 -2
  3. package/client/app/shell/SidebarLayout.tsx +3 -16
  4. package/client/assets/openai.svg +1 -3
  5. package/client/components/shared/Composer.tsx +53 -2
  6. package/client/components/ui/button.tsx +1 -1
  7. package/client/components/ui/tooltip.tsx +12 -15
  8. package/client/features/chat/ChatComposer.tsx +25 -15
  9. package/client/features/chat/ChatPanel.tsx +5 -2
  10. package/client/features/chat/MarkdownContent.tsx +20 -2
  11. package/client/features/chat/ModelPicker.tsx +5 -3
  12. package/client/features/chat/TurnView.tsx +2 -2
  13. package/client/features/chat/chat-frames.ts +13 -6
  14. package/client/features/chat/chat-send.ts +1 -1
  15. package/client/features/chat/chat-store.ts +22 -17
  16. package/client/features/chat/tool-group/ToolOutput.tsx +4 -12
  17. package/client/features/chat/tool-group/format.ts +0 -6
  18. package/client/features/chat/useChat.ts +11 -2
  19. package/client/features/connectors/McpServerCards.tsx +95 -0
  20. package/client/features/connectors/api.ts +0 -11
  21. package/client/features/home/HomePage.tsx +33 -28
  22. package/client/features/home/api.ts +24 -12
  23. package/client/features/home/workspace-presentation.tsx +17 -15
  24. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +243 -0
  25. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +95 -0
  26. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +230 -0
  27. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +35 -0
  28. package/client/features/home/workspace-setup/useWorkspaceImport.ts +61 -0
  29. package/client/features/settings/ConnectorsSettings.tsx +89 -0
  30. package/client/features/settings/SettingsLayout.tsx +2 -2
  31. package/client/features/settings/WorkspaceSettings.tsx +8 -4
  32. package/client/features/views/ViewBuilderTab.tsx +19 -15
  33. package/client/features/views/useViewBuilderActions.ts +1 -1
  34. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -4
  35. package/client/features/workspace/WorkspaceScreen.tsx +11 -3
  36. package/client/features/workspace/api.ts +19 -1
  37. package/client/features/workspace/moi-context.ts +85 -0
  38. package/client/main.tsx +7 -4
  39. package/dist/{chunk-cs8vbert.js → chunk-1dfbr7n2.js} +2 -2
  40. package/dist/chunk-339jds4x.js +15 -0
  41. package/dist/chunk-3xsvsnhr.css +1 -0
  42. package/dist/{chunk-zpxrb1ce.js → chunk-anqmsbjt.js} +2 -2
  43. package/dist/chunk-hbvfb6sk.js +63 -0
  44. package/dist/{chunk-kxmvv1ax.js → chunk-qwm5f6qk.js} +1 -1
  45. package/dist/{chunk-axszxe4c.js → chunk-sxbfh73c.js} +1 -1
  46. package/dist/chunk-yp4srgqt.js +10 -0
  47. package/dist/index.html +1 -1
  48. package/dist/openai-ep9ht2pq.svg +1 -0
  49. package/lib/ids.ts +15 -0
  50. package/lib/moi-context.ts +170 -0
  51. package/lib/types.ts +29 -11
  52. package/lib/view-builder-directives.ts +16 -0
  53. package/lib/workspace-types.ts +12 -0
  54. package/package.json +2 -1
  55. package/server/api.ts +92 -30
  56. package/server/harness/README.md +25 -9
  57. package/server/harness/claude-code/NOTES.md +20 -6
  58. package/server/harness/claude-code/adapter.ts +2 -2
  59. package/server/harness/claude-code/git-worktree.ts +32 -0
  60. package/server/harness/claude-code/index.ts +32 -12
  61. package/server/harness/claude-code/mcp.ts +16 -65
  62. package/server/harness/claude-code/models.ts +3 -0
  63. package/server/harness/claude-code/session.ts +196 -61
  64. package/server/harness/codex/NOTES.md +41 -11
  65. package/server/harness/codex/adapter.ts +21 -7
  66. package/server/harness/codex/client.ts +33 -17
  67. package/server/harness/codex/discovery.ts +114 -0
  68. package/server/harness/codex/index.ts +9 -5
  69. package/server/harness/codex/probe.ts +4 -2
  70. package/server/harness/codex/session.ts +57 -5
  71. package/server/harness/executable.ts +82 -0
  72. package/server/harness/openclaw/adapter.ts +8 -1
  73. package/server/harness/openclaw/index.ts +8 -14
  74. package/server/harness/openclaw/session.ts +50 -10
  75. package/server/harness/openclaw/strip.ts +2 -2
  76. package/server/harness/shell-path.ts +79 -0
  77. package/server/harness/types.ts +22 -5
  78. package/server/registry.ts +57 -12
  79. package/server/view-builders.ts +3 -2
  80. package/server/web.ts +24 -8
  81. package/server/workspace-import.ts +45 -0
  82. package/workspace/.claude/skills/moi-workspace/SKILL.md +3 -3
  83. package/client/features/connectors/ConnectorsPage.tsx +0 -92
  84. package/client/features/connectors/McpMenu.tsx +0 -145
  85. package/client/features/home/CreateWorkspaceDialog.tsx +0 -130
  86. package/client/features/home/CreateWorkspaceDialogSteps.tsx +0 -234
  87. package/dist/chunk-4vf1t6v1.js +0 -10
  88. package/dist/chunk-b3ynfk4g.js +0 -62
  89. package/dist/chunk-b4b276wx.js +0 -15
  90. package/dist/chunk-npwq6jmr.css +0 -1
  91. package/dist/openai-h13pza4b.svg +0 -3
  92. package/lib/view-builder-meta.ts +0 -35
@@ -21,7 +21,8 @@ import {
21
21
  import { ATTACHMENT_ONLY_PLACEHOLDER, appendAttachmentNote } from '@/lib/attachment-note'
22
22
  import { ClaudeAdapter } from './adapter'
23
23
  import type { Part } from '@/lib/format'
24
- import { stripViewBuilderMeta } from '@/lib/view-builder-meta'
24
+ import type { SessionActivity } from '@/lib/types'
25
+ import { type MoiContext, moiContextSystemReminder, renderMoiContext } from '@/lib/moi-context'
25
26
 
26
27
  import { debug } from '../../debug'
27
28
  import { tapWire } from '../debug'
@@ -34,6 +35,7 @@ import {
34
35
  renameViewBuilderSession
35
36
  } from '../../view-builders'
36
37
  import { resolveWorkspaceEnv } from '../../workspace-env'
38
+ import { requireHarnessExecutable } from '../executable'
37
39
 
38
40
  // Media types Claude vision accepts; uploads.ts guarantees every image upload is
39
41
  // normalized to one of these, so the cast on `media_type` below is sound.
@@ -92,6 +94,11 @@ export function buildUserMessage(
92
94
  const MAX_LIVE_SESSIONS = 8
93
95
  const IDLE_TTL_MS = 5 * 60_000
94
96
 
97
+ // SDK task types that keep running after the turn ends (background Bash,
98
+ // workflow runs). Subagent Tasks complete within their turn, so they are
99
+ // deliberately excluded — a leaked entry would keep the session alive forever.
100
+ const BG_TASK_TYPES = new Set(['local_bash', 'local_workflow'])
101
+
95
102
  const ALLOWED_TOOLS = [
96
103
  'Bash',
97
104
  'Read',
@@ -119,9 +126,19 @@ type LiveSession = {
119
126
  adapter: ClaudeAdapter
120
127
  input: InputQueue
121
128
  abort: AbortController
122
- // User messages enqueued but not yet completed. A turn ends on a `result`
123
- // message; processing = pendingTurns > 0.
124
- pendingTurns: number
129
+ // Session activity, mirrored from the SDK's `session_state_changed` events
130
+ // (authoritative — it fires `idle` only after the CLI's input queue drains,
131
+ // so queued messages merged into one model turn can't wedge it, unlike the
132
+ // old send/result counter). `sendCCMessage` flips it to 'running'
133
+ // optimistically so the loader doesn't wait a subprocess round-trip.
134
+ activity: SessionActivity
135
+ // Whether this query has emitted `session_state_changed` at all. When it
136
+ // never does (older CLI), the `result` handler falls back to declaring idle.
137
+ sawStateEvents: boolean
138
+ // Live background tasks (background Bash, workflows) keyed by task id, fed by
139
+ // the SDK's typed task events. Non-empty keeps the session alive past the
140
+ // idle TTL — tearing down the subprocess would kill its background children.
141
+ bgTasks: Set<string>
125
142
  model: string | undefined
126
143
  // Reasoning effort the query was created with. The SDK has no live setter for
127
144
  // it (unlike setModel), so a change tears the session down and resumes.
@@ -139,6 +156,9 @@ type LiveSession = {
139
156
  desiredStream: boolean
140
157
  idleTimer: ReturnType<typeof setTimeout> | null
141
158
  closed: boolean
159
+ // Last turn's error text (result subtype), consumed by the view-builder
160
+ // status update on the idle transition.
161
+ lastBuilderError: string | undefined
142
162
  // Introspection only (surfaced by /status) — not load-bearing.
143
163
  createdAt: number
144
164
  lastActivityAt: number
@@ -166,11 +186,17 @@ function liveKey(workspaceId: string, sessionId: string): string {
166
186
  return real ? recKey(workspaceId, real) : direct
167
187
  }
168
188
 
169
- // Running sessions across all workspaces, for the connect-time status snapshot.
170
- export function getCCRunningSessions(): { workspaceId: string; sessionId: string }[] {
171
- const out: { workspaceId: string; sessionId: string }[] = []
189
+ // Non-idle sessions across all workspaces, for the status snapshot.
190
+ export function getCCActiveSessions(): {
191
+ workspaceId: string
192
+ sessionId: string
193
+ activity: SessionActivity
194
+ }[] {
195
+ const out: { workspaceId: string; sessionId: string; activity: SessionActivity }[] = []
172
196
  for (const s of sessions.values()) {
173
- if (s.pendingTurns > 0) out.push({ workspaceId: s.workspaceId, sessionId: s.sessionId })
197
+ if (s.activity !== 'idle') {
198
+ out.push({ workspaceId: s.workspaceId, sessionId: s.sessionId, activity: s.activity })
199
+ }
174
200
  }
175
201
  return out
176
202
  }
@@ -186,8 +212,8 @@ export type CCDebugSession = {
186
212
  desiredEffort: string | undefined
187
213
  stream: boolean
188
214
  desiredStream: boolean
189
- pendingTurns: number
190
- busy: boolean
215
+ activity: SessionActivity
216
+ bgTasks: number
191
217
  closed: boolean
192
218
  hasIdleTimer: boolean
193
219
  createdAt: number
@@ -207,8 +233,8 @@ export function getCCDebugSnapshot(): { sessions: CCDebugSession[]; aliases: num
207
233
  desiredEffort: s.desiredEffort,
208
234
  stream: s.stream,
209
235
  desiredStream: s.desiredStream,
210
- pendingTurns: s.pendingTurns,
211
- busy: s.pendingTurns > 0,
236
+ activity: s.activity,
237
+ bgTasks: s.bgTasks.size,
212
238
  closed: s.closed,
213
239
  hasIdleTimer: s.idleTimer !== null,
214
240
  createdAt: s.createdAt,
@@ -262,8 +288,12 @@ function createInputQueue(): InputQueue {
262
288
  }
263
289
  }
264
290
 
265
- function broadcastProcessing(s: LiveSession, processing: boolean) {
266
- broadcast(s.workspaceId, { type: 'status', sessionId: s.sessionId, processing })
291
+ // Set the session's activity and broadcast the transition (deduped — repeated
292
+ // same-value events from the SDK don't re-broadcast).
293
+ function setActivity(s: LiveSession, activity: SessionActivity) {
294
+ if (s.activity === activity) return
295
+ s.activity = activity
296
+ broadcast(s.workspaceId, { type: 'status', sessionId: s.sessionId, activity })
267
297
  }
268
298
 
269
299
  function clearIdle(s: LiveSession) {
@@ -276,13 +306,26 @@ function clearIdle(s: LiveSession) {
276
306
  function armIdle(s: LiveSession) {
277
307
  clearIdle(s)
278
308
  s.idleTimer = setTimeout(() => {
279
- if (s.pendingTurns === 0) teardown(s)
309
+ if (s.activity === 'running') return
310
+ if (s.bgTasks.size > 0) {
311
+ // Tearing down would kill the subprocess and its background children
312
+ // (renders, watch loops). Keep the session alive until they finish.
313
+ debug(
314
+ `cc idle-keepalive ws=${s.workspaceId} session=${s.sessionId} bgTasks=${s.bgTasks.size}`
315
+ )
316
+ armIdle(s)
317
+ return
318
+ }
319
+ teardown(s)
280
320
  }, IDLE_TTL_MS)
281
321
  }
282
322
 
283
323
  function teardown(s: LiveSession) {
284
324
  if (s.closed) return
285
- debug(`cc teardown ws=${s.workspaceId} session=${s.sessionId} pendingTurns=${s.pendingTurns}`)
325
+ debug(`cc teardown ws=${s.workspaceId} session=${s.sessionId} activity=${s.activity}`)
326
+ // Terminal status first, while the session is still registered — the consume
327
+ // finally can't be relied on (a hung SDK iterator never reaches it).
328
+ setActivity(s, 'idle')
286
329
  s.closed = true
287
330
  clearIdle(s)
288
331
  s.input.close()
@@ -310,6 +353,20 @@ function renameSession(s: LiveSession, realId: string) {
310
353
  broadcast(s.workspaceId, { type: 'session_renamed', from, to: realId })
311
354
  }
312
355
 
356
+ // The session just went idle (state event, or `result` on a CLI without state
357
+ // events): settle the view builder, then either rebuild for a deferred
358
+ // effort/streaming change or arm the idle timer.
359
+ async function onSessionIdle(s: LiveSession) {
360
+ await markViewBuilderWaitingBySession(
361
+ s.workspaceId,
362
+ s.workspacePath,
363
+ s.sessionId,
364
+ s.lastBuilderError
365
+ )
366
+ if (s.desiredEffort !== s.effort || s.desiredStream !== s.stream) teardown(s)
367
+ else armIdle(s)
368
+ }
369
+
313
370
  async function consume(s: LiveSession) {
314
371
  try {
315
372
  for await (const msg of s.q) {
@@ -353,27 +410,68 @@ async function consume(s: LiveSession) {
353
410
  if (msg.type === 'system' && msg.subtype === 'init') {
354
411
  debug(`cc init ws=${s.workspaceId} session=${s.sessionId}`)
355
412
  }
356
- if (msg.type === 'result') {
413
+ // A turn is producing output while we think the session is idle: a
414
+ // queued message the CLI ran as its own turn after the previous result,
415
+ // or an SDK-initiated turn (e.g. a background-task notification waking
416
+ // the model). Re-assert running so the spinner tracks real activity.
417
+ if ((msg.type === 'assistant' || msg.type === 'stream_event') && s.activity === 'idle') {
418
+ setActivity(s, 'running')
419
+ }
420
+ // Authoritative activity mirror. The CLI emits `idle` only once its own
421
+ // input queue drains, so queued messages the model merged into one turn
422
+ // (one `result` for N sends) still end in a clean idle here. Observed
423
+ // empirically: current CLIs don't emit this in streaming-input mode, so
424
+ // the `result` fallback below is the everyday path.
425
+ if (msg.type === 'system' && msg.subtype === 'session_state_changed') {
426
+ s.sawStateEvents = true
357
427
  s.lastActivityAt = Date.now()
358
- s.pendingTurns = Math.max(0, s.pendingTurns - 1)
359
- debug(`cc result ws=${s.workspaceId} session=${s.sessionId} pendingTurns=${s.pendingTurns}`)
360
- if (s.pendingTurns === 0) {
361
- broadcastProcessing(s, false)
362
- const builderError =
363
- msg.subtype === 'success'
364
- ? undefined
365
- : msg.errors.join('\n') || msg.subtype.replaceAll('_', ' ')
366
- await markViewBuilderWaitingBySession(
367
- s.workspaceId,
368
- s.workspacePath,
369
- s.sessionId,
370
- builderError
428
+ debug(`cc state ws=${s.workspaceId} session=${s.sessionId} state=${msg.state}`)
429
+ if (msg.state === 'running') setActivity(s, 'running')
430
+ else if (msg.state === 'requires_action') setActivity(s, 'requires-action')
431
+ else if (msg.state === 'idle') {
432
+ setActivity(s, 'idle')
433
+ await onSessionIdle(s)
434
+ }
435
+ }
436
+ // Background-task lifecycle (typed SDK events): track live background
437
+ // work so idle eviction doesn't kill it (armIdle keep-alive). Only task
438
+ // types that outlive the turn count; subagent Tasks end within it.
439
+ if (msg.type === 'system' && msg.subtype === 'task_started') {
440
+ if (BG_TASK_TYPES.has(msg.task_type ?? '')) {
441
+ s.bgTasks.add(msg.task_id)
442
+ debug(
443
+ `cc bg-task start ws=${s.workspaceId} session=${s.sessionId} task=${msg.task_id} type=${msg.task_type} live=${s.bgTasks.size}`
444
+ )
445
+ }
446
+ }
447
+ if (msg.type === 'system' && msg.subtype === 'task_notification') {
448
+ if (s.bgTasks.delete(msg.task_id)) {
449
+ debug(
450
+ `cc bg-task end ws=${s.workspaceId} session=${s.sessionId} task=${msg.task_id} status=${msg.status} live=${s.bgTasks.size}`
371
451
  )
372
- // A mid-turn effort/streaming change couldn't be applied live; now
373
- // that the queue has drained, tear down so the next message resumes
374
- // with it.
375
- if (s.desiredEffort !== s.effort || s.desiredStream !== s.stream) teardown(s)
376
- else armIdle(s)
452
+ }
453
+ }
454
+ if (msg.type === 'system' && msg.subtype === 'task_updated') {
455
+ const status = msg.patch?.status
456
+ if (status === 'completed' || status === 'failed' || status === 'killed') {
457
+ s.bgTasks.delete(msg.task_id)
458
+ }
459
+ }
460
+ if (msg.type === 'result') {
461
+ s.lastActivityAt = Date.now()
462
+ // Remembered for the idle transition — the view builder shows the last
463
+ // turn's error once the queue drains.
464
+ s.lastBuilderError =
465
+ msg.subtype === 'success'
466
+ ? undefined
467
+ : msg.errors.join('\n') || msg.subtype.replaceAll('_', ' ')
468
+ debug(`cc result ws=${s.workspaceId} session=${s.sessionId} subtype=${msg.subtype}`)
469
+ // Fallback for CLIs that never emit `session_state_changed`: treat
470
+ // every result as turn-over. With state events, `idle` follows the
471
+ // result and drives the same path.
472
+ if (!s.sawStateEvents) {
473
+ setActivity(s, 'idle')
474
+ await onSessionIdle(s)
377
475
  }
378
476
  }
379
477
  }
@@ -391,20 +489,18 @@ async function consume(s: LiveSession) {
391
489
  await markViewBuilderWaitingBySession(s.workspaceId, s.workspacePath, s.sessionId, message)
392
490
  }
393
491
  } finally {
394
- if (s.pendingTurns > 0) {
395
- s.pendingTurns = 0
396
- broadcastProcessing(s, false)
397
- }
492
+ // teardown broadcasts the terminal idle status itself (deduped).
398
493
  teardown(s)
399
494
  }
400
495
  }
401
496
 
402
- // Close one idle session to stay under the cap. A busy session is never evicted;
403
- // if everything is busy we allow a temporary overflow rather than killing a run.
497
+ // Close one idle session to stay under the cap. A running session — or one
498
+ // with live background tasks — is never evicted; if everything is busy we allow
499
+ // a temporary overflow rather than killing a run.
404
500
  function evictIfNeeded() {
405
501
  if (sessions.size < MAX_LIVE_SESSIONS) return
406
502
  for (const s of sessions.values()) {
407
- if (s.pendingTurns === 0) {
503
+ if (s.activity === 'idle' && s.bgTasks.size === 0) {
408
504
  teardown(s)
409
505
  return
410
506
  }
@@ -431,6 +527,7 @@ function createLiveSession(input: {
431
527
  const abort = new AbortController()
432
528
  const options: Options = {
433
529
  abortController: abort,
530
+ pathToClaudeCodeExecutable: requireHarnessExecutable('claude-code'),
434
531
  // Generous: one query() spans the whole live session (many turns). On end
435
532
  // (limit hit / closed / error) the session is torn down and the next
436
533
  // message recreates it via resume.
@@ -467,7 +564,9 @@ function createLiveSession(input: {
467
564
  adapter: new ClaudeAdapter(),
468
565
  input: queue,
469
566
  abort,
470
- pendingTurns: 0,
567
+ activity: 'idle',
568
+ sawStateEvents: false,
569
+ bgTasks: new Set(),
471
570
  model: input.model,
472
571
  effort: input.effort,
473
572
  desiredEffort: input.effort,
@@ -475,6 +574,7 @@ function createLiveSession(input: {
475
574
  desiredStream: input.stream,
476
575
  idleTimer: null,
477
576
  closed: false,
577
+ lastBuilderError: undefined,
478
578
  createdAt: Date.now(),
479
579
  lastActivityAt: Date.now(),
480
580
  lastUserText: undefined
@@ -501,6 +601,9 @@ export async function sendCCMessage(input: {
501
601
  model?: string
502
602
  effort?: string
503
603
  stream?: boolean
604
+ // Structured moi context (lib/moi-context.ts), rendered here and injected
605
+ // as a leading system-reminder text block; the display parts never see it.
606
+ context?: MoiContext
504
607
  }): Promise<void> {
505
608
  // Resolve any attachments into agent content blocks + display parts. Unknown
506
609
  // or expired ids are silently dropped (resolveUploads filters them) — if that
@@ -509,8 +612,20 @@ export async function sendCCMessage(input: {
509
612
  ? resolveUploads(input.workspaceId, input.attachments)
510
613
  : []
511
614
  if (!input.content && uploads.length === 0) return
512
- const displayContent = stripViewBuilderMeta(input.content)
513
- const { content, parts } = buildUserMessage(input.content, uploads, displayContent)
615
+ const { content: userContent, parts } = buildUserMessage(input.content, uploads)
616
+ // The envelope goes in as its OWN leading text block, never merged into the
617
+ // user's string: the SDK's first-prompt extraction (session titles,
618
+ // home-card previews) skips tag-leading text, so a prefixed string would
619
+ // hide every moi message from it. On replay the adapter strips the block to
620
+ // empty and drops it.
621
+ const content: MessageContent = input.context
622
+ ? [
623
+ { type: 'text', text: moiContextSystemReminder(renderMoiContext(input.context)) },
624
+ ...(typeof userContent === 'string'
625
+ ? [{ type: 'text' as const, text: userContent }]
626
+ : userContent)
627
+ ]
628
+ : userContent
514
629
 
515
630
  const wantStream = input.stream === true
516
631
  let s = sessions.get(liveKey(input.workspaceId, input.sessionId))
@@ -518,7 +633,7 @@ export async function sendCCMessage(input: {
518
633
  // construct-time, no SDK setter), so when either differs we tear the idle
519
634
  // session down and recreate it via resume — the change lands on this very
520
635
  // turn. A busy session keeps its settings until the in-flight turn ends.
521
- if (s && (input.effort !== s.effort || wantStream !== s.stream) && s.pendingTurns === 0) {
636
+ if (s && (input.effort !== s.effort || wantStream !== s.stream) && s.activity === 'idle') {
522
637
  teardown(s)
523
638
  s = undefined
524
639
  }
@@ -582,44 +697,64 @@ export async function sendCCMessage(input: {
582
697
  // Safety net: if a future SDK does echo the user message, the adapter re-ids
583
698
  // that echo to the same optimisticId so it collapses onto the turn above
584
699
  // instead of duplicating.
585
- if (input.optimisticId) s.adapter.expectUserEcho(input.optimisticId, displayContent)
700
+ if (input.optimisticId) s.adapter.expectUserEcho(input.optimisticId, input.content)
586
701
 
587
702
  s.lastActivityAt = Date.now()
588
703
  // For an attachment-only message, fall back to the filenames so the thread
589
704
  // list / status view don't show a blank label.
590
- const label = displayContent || uploads.map(u => u.filename).join(', ')
705
+ const label = input.content || uploads.map(u => u.filename).join(', ')
591
706
  s.lastUserText = label.replace(/\s+/g, ' ').slice(0, 120)
592
707
 
593
- const wasIdle = s.pendingTurns === 0
594
- s.pendingTurns++
595
- if (wasIdle) {
708
+ // Optimistic flip — the authoritative `session_state_changed: running` from
709
+ // the subprocess confirms it moments later (setActivity dedupes).
710
+ if (s.activity !== 'running') {
596
711
  await markViewBuilderBuildingBySession(s.workspaceId, s.workspacePath, s.sessionId)
597
- broadcastProcessing(s, true)
712
+ setActivity(s, 'running')
598
713
  }
714
+ clearIdle(s)
599
715
  s.input.push(content)
600
716
  tapWire(s.workspaceId, 'send', { type: 'user', content })
601
717
  debug(
602
- `cc enqueue ws=${s.workspaceId} session=${s.sessionId} pendingTurns=${s.pendingTurns} text=${JSON.stringify(s.lastUserText)}`
718
+ `cc enqueue ws=${s.workspaceId} session=${s.sessionId} activity=${s.activity} text=${JSON.stringify(s.lastUserText)}`
603
719
  )
604
720
  }
605
721
 
606
- // Interrupt the current turn and drop any queued messages, but keep the session
607
- // alive for the next message.
722
+ // How long Stop waits for the SDK's interrupt round-trip before declaring the
723
+ // subprocess wedged and tearing it down. A hung subprocess never answers, and
724
+ // without this cap the whole interrupt path (and the user's only escape hatch
725
+ // from a stuck spinner) hangs with it.
726
+ const INTERRUPT_TIMEOUT_MS = 5_000
727
+
728
+ // Interrupt the current turn and drop any queued messages, keeping the session
729
+ // alive for the next message. If the subprocess doesn't acknowledge in time it
730
+ // is torn down instead — the next message respawns via resume.
608
731
  export async function interruptCCSession(workspaceId: string, sessionId: string): Promise<void> {
609
732
  const s = sessions.get(liveKey(workspaceId, sessionId))
610
733
  if (!s) return
611
- debug(`cc interrupt ws=${workspaceId} session=${sessionId} pendingTurns=${s.pendingTurns}`)
734
+ debug(`cc interrupt ws=${workspaceId} session=${sessionId} activity=${s.activity}`)
612
735
  s.input.clear()
736
+ let timer: ReturnType<typeof setTimeout> | undefined
737
+ const timedOut = Symbol('interrupt-timeout')
613
738
  try {
614
- await s.q.interrupt()
739
+ const outcome = await Promise.race([
740
+ s.q.interrupt(),
741
+ new Promise(resolve => {
742
+ timer = setTimeout(() => resolve(timedOut), INTERRUPT_TIMEOUT_MS)
743
+ })
744
+ ])
745
+ if (outcome === timedOut) {
746
+ debug(`cc interrupt timeout ws=${workspaceId} session=${sessionId} — tearing down`)
747
+ teardown(s)
748
+ }
615
749
  } catch (err) {
616
750
  console.error('[cc-session] interrupt failed', err)
751
+ } finally {
752
+ clearTimeout(timer)
617
753
  }
618
- s.pendingTurns = 0
619
754
  broadcast(s.workspaceId, { kind: 'stopped', sessionId: s.sessionId })
620
- broadcastProcessing(s, false)
755
+ setActivity(s, 'idle')
621
756
  await markViewBuilderWaitingBySession(s.workspaceId, s.workspacePath, s.sessionId)
622
- armIdle(s)
757
+ if (!s.closed) armIdle(s)
623
758
  }
624
759
 
625
760
  // Tear down a workspace's IDLE sessions so the next message respawns the agent
@@ -628,7 +763,7 @@ export async function interruptCCSession(workspaceId: string, sessionId: string)
628
763
  // turn ends (then idle-evict or get recreated on the next message via resume).
629
764
  export function restartWorkspaceSessions(workspacePath: string): void {
630
765
  for (const s of [...sessions.values()]) {
631
- if (s.workspacePath === workspacePath && s.pendingTurns === 0) teardown(s)
766
+ if (s.workspacePath === workspacePath && s.activity === 'idle') teardown(s)
632
767
  }
633
768
  }
634
769
 
@@ -97,6 +97,30 @@ Per-turn overrides (`model`, `effort`, `summary`, sandbox/approval policy)
97
97
  become the thread's defaults for later turns — no drain-then-rebuild dance at
98
98
  all. `thread/settings/update` queues setting changes without starting a turn.
99
99
 
100
+ ### additionalContext (native per-turn ambient context)
101
+
102
+ `turn/start` and `turn/steer` take an experimental
103
+ `additionalContext: { <key>: { value, kind: 'untrusted' | 'application' } }`
104
+ map (openai/codex#24154, shipped in 0.135.0, May 2026) — moi uses it for the
105
+ `<moi-context>` envelope (key `moi-context`, kind `application`, so the wire
106
+ tag matches the tag the moi-workspace skill triggers on):
107
+
108
+ - `application` injects a developer-role message `<key>value</key>`;
109
+ `untrusted` a user-role `<external_key>value</external_key>`. Values are
110
+ middle-truncated to a ~1,000-token budget.
111
+ - Send the map every turn; the server diffs per key and injects only when a
112
+ value CHANGED since the last turn — unchanged keys cost nothing.
113
+ - Injected fragments never appear as `userMessage` items (live or on
114
+ `thread/read` replay), so nothing to strip.
115
+ - Gated: requires `initialize.capabilities.experimentalApi: true`, else a
116
+ new-enough server rejects the request when the field is present.
117
+ - Servers < 0.135 have no `deny_unknown_fields` on TurnStartParams and
118
+ silently DROP the field — no error to detect. The only reliable support
119
+ signal is the version in the initialize response's `userAgent`
120
+ (`codex_cli_rs/<semver> …`) — see `codexSupportsAdditionalContext`
121
+ (client.ts). Below the cutoff the session path appends the envelope to the
122
+ text item instead (adapter strips it from echoes).
123
+
100
124
  ### Feature map vs the adapter checklist
101
125
 
102
126
  - **Models**: `model/list` — models with ordered `supportedReasoningEfforts`,
@@ -149,16 +173,17 @@ all. `thread/settings/update` queues setting changes without starting a turn.
149
173
  - Typed bindings are generated, version-matched to the installed binary:
150
174
  `codex app-server generate-ts --out DIR` (or `generate-json-schema`).
151
175
 
152
- ### Binary availability (Codex Desktop caveat)
176
+ ### Binary availability
153
177
 
154
- Don't assume Codex Desktop puts `codex` on PATH. The desktop app is a CLI
155
- _consumer_: it resolves an external codex binary (honoring `CODEX_CLI_PATH`,
156
- then PATH) and on first launch can install/update `@openai/codex` with a Node
157
- runtime bundled inside the app — app-managed, not necessarily a shell-visible
158
- `codex` command. Officially the CLI is a separate install (`npm i -g
159
- @openai/codex`, brew, or the standalone installer). The adapter should detect
160
- the binary: explicit config → `CODEX_CLI_PATH` → `codex` on PATH → error with
161
- install instructions.
178
+ The adapter resolves `codex` through `../executable.ts`: first a PATH lookup
179
+ over the server's PATH merged with the user's login-shell PATH
180
+ (`../shell-path.ts`), then the known macOS app-bundle locations —
181
+ `/Applications/ChatGPT.app/Contents/Resources/codex` and the legacy
182
+ `/Applications/Codex.app/Contents/Resources/codex` — since Codex Desktop
183
+ manages an app-internal binary that is not shell-visible. PATH wins over the
184
+ bundle probe, so a deliberately installed CLI is never shadowed. If nothing
185
+ resolves, install the CLI with
186
+ `curl -fsSL https://chatgpt.com/codex/install.sh | sh`.
162
187
 
163
188
  ## 3. Client libraries
164
189
 
@@ -212,8 +237,13 @@ state, steer/interrupt, previews, usage). Empirical findings beyond §2:
212
237
  - **`turn/completed` carries no items** (`itemsView: "notLoaded"`); items
213
238
  arrive only via `item/started`/`item/completed`.
214
239
  - **The npm `codex` bin is a Node shim** that spawns the platform binary;
215
- killing the shim tears down the server via stdin EOF, so no orphans — but
216
- binary detection must tolerate shim paths (`CODEX_CLI_PATH` → PATH).
240
+ killing the shim tears down the server via stdin EOF, so no orphans. The
241
+ absolute shim path returned by the PATH lookup is safe to spawn.
242
+ - **Rollout files double as a discovery index.** Each thread persists to
243
+ `~/.codex/sessions/YYYY/MM/DD/rollout-<timestamp>-<uuid>.jsonl` whose first
244
+ line is a `session_meta` record with the thread's `cwd` (older formats put
245
+ the meta fields at the top level). `discovery.ts` reads those heads directly
246
+ — workspace discovery works without the binary installed.
217
247
  - **User-level config bleeds in**: threads start MCP servers and hooks from
218
248
  `~/.codex/config.toml` / `hooks.json` per thread; their failures arrive as
219
249
  notifications (`mcpServer/startupStatus/updated`, `hook/completed`) we
@@ -9,6 +9,7 @@
9
9
  // Type shapes are hand-written against `codex app-server generate-ts`
10
10
  // (CLI 0.144.5) and read defensively — see ./NOTES.md.
11
11
  import type { Part, StreamEvent, SystemNotice, ToolCall, ToolState, Turn } from '@/lib/format'
12
+ import { stripMoiContext, stripMoiContextLoose } from '@/lib/moi-context'
12
13
  import type { Model, SessionInfo } from '@/lib/types'
13
14
 
14
15
  import type { WorkspaceActivityPreview } from '../types'
@@ -105,10 +106,18 @@ export type CodexModel = {
105
106
 
106
107
  // ---- discovery mappings ------------------------------------------------------
107
108
 
109
+ // `thread/list.preview` snippets come from the raw first user message — on
110
+ // the pre-0.135 fallback path that text carries the appended context envelope,
111
+ // so previews strip it like transcript turns do. Loose variant: previews are
112
+ // truncated snippets, so a mid-envelope cut must still strip.
113
+ function cleanPreview(preview: string | undefined): string {
114
+ return preview ? stripMoiContextLoose(preview).trim() : ''
115
+ }
116
+
108
117
  export function codexThreadToSessionInfo(t: CodexThread): SessionInfo {
109
118
  return {
110
119
  sessionId: t.id,
111
- summary: t.name?.trim() || t.preview?.trim() || '',
120
+ summary: t.name?.trim() || cleanPreview(t.preview),
112
121
  // Codex timestamps are unix seconds; SessionInfo wants millis.
113
122
  lastModified: (t.updatedAt ?? t.createdAt ?? 0) * 1000,
114
123
  cwd: t.cwd
@@ -136,7 +145,7 @@ export function selectCodexWorkspacePreview(
136
145
  (a.createdAt ?? a.updatedAt ?? 0) - (b.createdAt ?? b.updatedAt ?? 0) ||
137
146
  a.id.localeCompare(b.id)
138
147
  )[0]
139
- firstUserMessage = oldest?.preview?.trim() || undefined
148
+ firstUserMessage = cleanPreview(oldest?.preview) || undefined
140
149
  }
141
150
 
142
151
  return {
@@ -147,16 +156,17 @@ export function selectCodexWorkspacePreview(
147
156
 
148
157
  export function codexModelToModel(m: CodexModel): Model {
149
158
  const efforts = (m.supportedReasoningEfforts ?? []).map(e => e.reasoningEffort)
159
+ const displayName = m.displayName.replace(/^GPT-/, '').replaceAll('-', ' ')
150
160
  return {
151
161
  value: m.id,
152
162
  resolvedModel: m.model,
153
- displayName: m.displayName,
163
+ displayName,
154
164
  // Our Model.description is a " · "-joined "<headline> · <tagline>" blurb
155
165
  // (the picker renders the first segment as the row label), so lead with
156
166
  // the display name and let Codex's one-liner be the tagline.
157
167
  ...(m.description
158
- ? { description: `${m.displayName} · ${m.description}` }
159
- : { description: m.displayName }),
168
+ ? { description: `${displayName} · ${m.description}` }
169
+ : { description: displayName }),
160
170
  supportsEffort: efforts.length > 0,
161
171
  ...(efforts.length > 0 ? { supportedEffortLevels: efforts } : {})
162
172
  }
@@ -182,8 +192,12 @@ function statusToToolState(status: string | undefined): ToolState {
182
192
  function userInputToParts(content: CodexUserInput[] | undefined): Part[] {
183
193
  const parts: Part[] = []
184
194
  for (const c of content ?? []) {
185
- if (c.type === 'text' && c.text) parts.push({ type: 'text', text: c.text })
186
- else if (c.type === 'image' && c.url)
195
+ // The send path appends the `<moi-context>` envelope to the agent text;
196
+ // the native echo and thread replays carry it back, so peel it here.
197
+ if (c.type === 'text' && c.text) {
198
+ const text = stripMoiContext(c.text)
199
+ if (text) parts.push({ type: 'text', text })
200
+ } else if (c.type === 'image' && c.url)
187
201
  parts.push({ type: 'file', mediaType: 'image/*', url: c.url })
188
202
  else if (c.type === 'localImage' && c.path)
189
203
  parts.push({ type: 'text', text: `[image: ${c.path}]` })