moi-computer 0.11.0 → 0.11.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.
- package/client/AGENTS.md +2 -2
- package/client/components/ui/button.tsx +1 -53
- package/client/components/ui/collapsible.tsx +1 -15
- package/client/components/ui/dialog.tsx +1 -58
- package/client/components/ui/dropdown-menu.tsx +1 -254
- package/client/components/ui/hover-card.tsx +1 -44
- package/client/components/ui/input.tsx +1 -21
- package/client/components/ui/popover.tsx +1 -88
- package/client/components/ui/resizable.tsx +1 -40
- package/client/components/ui/skeleton.tsx +1 -13
- package/client/components/ui/slider.tsx +1 -70
- package/client/components/ui/spinner.tsx +1 -18
- package/client/components/ui/switch.tsx +1 -23
- package/client/components/ui/tabs.tsx +1 -0
- package/client/components/ui/textarea.tsx +1 -18
- package/client/components/ui/tooltip.tsx +1 -51
- package/client/features/chat/ChatPanel.tsx +6 -6
- package/client/features/chat/ChatPopup.tsx +3 -4
- package/client/features/chat/TurnView.tsx +5 -4
- package/client/features/chat/api.ts +5 -14
- package/client/features/chat/chat-frames.ts +5 -2
- package/client/features/chat/composer/ChatComposer.tsx +5 -1
- package/client/features/chat/composer/ModelPicker.tsx +4 -3
- package/client/features/chat/composer/banners/ErrorBanner.tsx +20 -12
- package/client/features/chat/composer/useWorkspaceComposerState.tsx +15 -7
- package/client/features/chat/group-turns.ts +11 -0
- package/client/features/chat/session-view.ts +53 -0
- package/client/features/chat/useChat.ts +5 -1
- package/client/features/dev/ChatStatesPage.tsx +3 -1
- package/client/features/dev/DevIndexPage.tsx +5 -0
- package/client/features/dev/DevRoutes.tsx +2 -0
- package/client/features/dev/HarnessDebugPage.tsx +1 -1
- package/client/features/dev/UiComponentPreviews.tsx +834 -0
- package/client/features/dev/UiComponentsPage.tsx +60 -0
- package/client/features/home/WorkspacePreview.tsx +1 -1
- package/client/features/home/workspace-setup/DemoDialog.tsx +3 -2
- package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +5 -8
- package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +7 -20
- package/client/features/settings/SettingsLayout.tsx +1 -1
- package/client/features/settings/WorkspaceSettings.tsx +4 -1
- package/client/features/views/ViewManager.tsx +14 -9
- package/client/features/widgets/WidgetFrame.tsx +1 -1
- package/client/features/widgets/Widgets.tsx +1 -3
- package/client/features/workspace/WorkspaceScreen.tsx +5 -1
- package/client/features/workspace/WorkspaceSplitLayout.tsx +6 -1
- package/client/features/workspace/api.ts +2 -4
- package/client/index.css +22 -29
- package/dist/{chunk-tny85yt2.js → chunk-4s15axjs.js} +2 -2
- package/dist/{chunk-c9pjqx9m.js → chunk-53a7pxcz.js} +1 -1
- package/dist/chunk-6664vxpk.css +1 -0
- package/dist/{chunk-104m57qw.js → chunk-87thzbtw.js} +2 -2
- package/dist/chunk-a6jad1a6.js +1 -0
- package/dist/chunk-dghwstd2.js +9 -0
- package/dist/chunk-eg120aca.js +1 -0
- package/dist/{chunk-v7wr1df4.js → chunk-j3wvxjr7.js} +1 -1
- package/dist/chunk-vwjeezeb.js +1 -0
- package/dist/chunk-w482ew2c.js +546 -0
- package/dist/chunk-yc471zah.js +70 -0
- package/dist/index.html +1 -1
- package/lib/format.ts +49 -1
- package/lib/themes.ts +6 -6
- package/lib/types.ts +5 -7
- package/package.json +17 -7
- package/registry.json +643 -0
- package/server/AGENTS.md +1 -0
- package/server/agent.ts +1 -1
- package/server/api.ts +25 -29
- package/server/applets.ts +30 -29
- package/server/bundler/applet-css.ts +6 -1
- package/server/bundler/build-applet.ts +5 -1
- package/server/bundler/build-worker.ts +178 -0
- package/server/cli-ui-components.ts +28 -33
- package/server/cli.ts +6 -11
- package/server/data-dir.ts +1 -1
- package/server/harness/README.md +13 -9
- package/server/harness/acp/NOTES.md +426 -0
- package/server/harness/acp/discovery.ts +27 -30
- package/server/harness/acp/model-state.ts +57 -0
- package/server/harness/acp/session.ts +18 -6
- package/server/harness/claude-code/NOTES.md +47 -12
- package/server/harness/claude-code/cli.ts +40 -0
- package/server/harness/claude-code/index.ts +11 -5
- package/server/harness/claude-code/models.ts +72 -19
- package/server/harness/claude-code/session.ts +408 -299
- package/server/harness/hermes/NOTES.md +18 -0
- package/server/harness/hermes/discovery.ts +20 -0
- package/server/harness/hermes/index.ts +9 -0
- package/server/harness/hermes/models.ts +28 -8
- package/server/harness/types.ts +4 -2
- package/server/moi-scaffold.ts +1 -1
- package/server/preview.ts +3 -1
- package/server/registry.ts +63 -41
- package/server/scratchpad-executor.ts +79 -56
- package/server/scratchpad-shape-defaults.ts +82 -0
- package/server/tldraw-package.d.ts +4 -0
- package/server/ui-components.ts +101 -434
- package/server/view-builders.ts +2 -1
- package/server/web.ts +9 -5
- package/server/workspace-env.ts +3 -2
- package/tsconfig.json +0 -1
- package/ui-components/accordion.tsx +71 -0
- package/ui-components/alert-dialog.tsx +165 -0
- package/ui-components/alert.tsx +68 -0
- package/ui-components/attachment.tsx +195 -0
- package/ui-components/avatar.tsx +90 -0
- package/ui-components/badge.tsx +49 -0
- package/ui-components/button-group.tsx +78 -0
- package/ui-components/button.tsx +55 -0
- package/ui-components/calendar.tsx +180 -0
- package/ui-components/card.tsx +84 -0
- package/ui-components/carousel.tsx +235 -0
- package/ui-components/chart.tsx +338 -0
- package/ui-components/checkbox.tsx +27 -0
- package/ui-components/collapsible.tsx +15 -0
- package/ui-components/combobox.tsx +265 -0
- package/ui-components/context-menu.tsx +244 -0
- package/ui-components/dialog.tsx +138 -0
- package/ui-components/docs/accordion.md +463 -0
- package/ui-components/docs/alert-dialog.md +481 -0
- package/ui-components/docs/alert.md +301 -0
- package/ui-components/docs/attachment.md +689 -0
- package/ui-components/docs/avatar.md +495 -0
- package/ui-components/docs/badge.md +258 -0
- package/ui-components/docs/button-group.md +879 -0
- package/ui-components/docs/button.md +26 -0
- package/ui-components/docs/calendar.md +862 -0
- package/ui-components/docs/card.md +265 -0
- package/ui-components/docs/carousel.md +627 -0
- package/ui-components/docs/chart.md +1256 -0
- package/ui-components/docs/checkbox.md +477 -0
- package/ui-components/docs/collapsible.md +446 -0
- package/ui-components/docs/combobox.md +1003 -0
- package/ui-components/docs/context-menu.md +860 -0
- package/ui-components/docs/data-table.md +1580 -0
- package/ui-components/docs/date-picker.md +614 -0
- package/ui-components/docs/dialog.md +414 -0
- package/ui-components/docs/drawer.md +51 -0
- package/ui-components/docs/dropdown-menu.md +1000 -0
- package/ui-components/docs/field.md +1192 -0
- package/ui-components/docs/hover-card.md +275 -0
- package/ui-components/docs/input-group.md +866 -0
- package/ui-components/docs/input.md +456 -0
- package/ui-components/docs/label.md +295 -0
- package/ui-components/docs/pagination.md +416 -0
- package/ui-components/docs/popover.md +348 -0
- package/ui-components/docs/progress.md +214 -0
- package/ui-components/docs/radio-group.md +389 -0
- package/ui-components/docs/resizable.md +265 -0
- package/ui-components/docs/select.md +616 -0
- package/ui-components/docs/separator.md +216 -0
- package/ui-components/docs/skeleton.md +205 -0
- package/ui-components/docs/slider.md +226 -0
- package/ui-components/docs/spinner.md +332 -0
- package/ui-components/docs/switch.md +236 -0
- package/ui-components/docs/table.md +551 -0
- package/ui-components/docs/tabs.md +379 -0
- package/ui-components/docs/textarea.md +187 -0
- package/ui-components/docs/toggle-group.md +370 -0
- package/ui-components/docs/toggle.md +91 -0
- package/ui-components/docs/tooltip.md +290 -0
- package/ui-components/drawer.tsx +213 -0
- package/ui-components/dropdown-menu.tsx +263 -0
- package/ui-components/field.tsx +224 -0
- package/ui-components/hover-card.tsx +46 -0
- package/ui-components/input-group.tsx +146 -0
- package/ui-components/input.tsx +20 -0
- package/ui-components/label.tsx +17 -0
- package/ui-components/pagination.tsx +124 -0
- package/ui-components/popover.tsx +81 -0
- package/ui-components/progress.tsx +63 -0
- package/ui-components/radio-group.tsx +37 -0
- package/ui-components/resizable.tsx +40 -0
- package/ui-components/scoped-portal.tsx +31 -0
- package/ui-components/select.tsx +195 -0
- package/ui-components/separator.tsx +18 -0
- package/ui-components/skeleton.tsx +15 -0
- package/ui-components/slider.tsx +75 -0
- package/ui-components/spinner.tsx +20 -0
- package/ui-components/switch.tsx +26 -0
- package/ui-components/table.tsx +86 -0
- package/ui-components/tabs.tsx +75 -0
- package/ui-components/textarea.tsx +17 -0
- package/ui-components/toggle-group.tsx +85 -0
- package/ui-components/toggle.tsx +42 -0
- package/ui-components/tooltip.tsx +61 -0
- package/ui-components/utils.ts +8 -0
- package/workspace/.claude/skills/moi-workspace/SKILL.md +11 -20
- package/workspace/.claude/skills/moi-workspace/references/DESIGN.md +4 -3
- package/workspace/.claude/skills/moi-workspace/references/UI-COMPONENTS.md +67 -203
- package/dist/chunk-59zf0m6n.js +0 -1
- package/dist/chunk-bj3akjs2.js +0 -1
- package/dist/chunk-j2w2vak4.js +0 -546
- package/dist/chunk-k2r9c95m.js +0 -10
- package/dist/chunk-kmbxhgwv.js +0 -1
- package/dist/chunk-p1yqa71k.js +0 -83
- package/dist/chunk-r5xrenjy.css +0 -1
|
@@ -1,16 +1,11 @@
|
|
|
1
|
-
//
|
|
1
|
+
// One long-lived SDK query per session, with follow-ups queued in moi.
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
// messages (and messages from multiple browser tabs) are pushed into the same
|
|
7
|
-
// queue — so they're *queued* instead of rejected, and there's no cold `resume`
|
|
8
|
-
// between turns.
|
|
3
|
+
// Dispatch waits for the preceding user turn to finish before applying the next
|
|
4
|
+
// message's settings. Pending messages survive subprocess replacement; running
|
|
5
|
+
// background tasks retain their process until they finish.
|
|
9
6
|
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
// live deltas. If a session is idle-evicted (or lost on a server restart), the
|
|
13
|
-
// next message recreates it with `resume` — transparently.
|
|
7
|
+
// The SDK persists history to disk. After eviction or a server restart, the
|
|
8
|
+
// next message resumes that history in a new process.
|
|
14
9
|
import {
|
|
15
10
|
type Options,
|
|
16
11
|
type Query,
|
|
@@ -26,7 +21,7 @@ import { claudeSessionExists } from './sessions'
|
|
|
26
21
|
import { generateClaudeSessionTitle, renameClaudeSessionIfUnchanged } from './session-title'
|
|
27
22
|
import type { Part } from '@/lib/format'
|
|
28
23
|
import type { SessionActivity } from '@/lib/types'
|
|
29
|
-
import {
|
|
24
|
+
import { moiContextSystemReminder, renderMoiContext } from '@/lib/moi-context'
|
|
30
25
|
|
|
31
26
|
import { debug } from '../../debug'
|
|
32
27
|
import { tapWire } from '../debug'
|
|
@@ -41,20 +36,16 @@ import {
|
|
|
41
36
|
} from '../../view-builders'
|
|
42
37
|
import { resolveWorkspaceEnv } from '../../workspace-env'
|
|
43
38
|
import { requireHarnessExecutable } from '../executable'
|
|
39
|
+
import type { SendMessageInput } from '../types'
|
|
44
40
|
|
|
45
41
|
// Media types Claude vision accepts; uploads.ts guarantees every image upload is
|
|
46
42
|
// normalized to one of these, so the cast on `media_type` below is sound.
|
|
47
43
|
type ImageMediaType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp'
|
|
48
44
|
|
|
49
|
-
// What the SDK's streaming-input prompt accepts for one message's content:
|
|
50
|
-
// a plain string or an array of Anthropic content blocks (text/image/…).
|
|
51
45
|
type MessageContent = SDKUserMessage['message']['content']
|
|
52
46
|
|
|
53
|
-
//
|
|
54
|
-
//
|
|
55
|
-
// base64 vision blocks; other files are referenced by their temp path so the
|
|
56
|
-
// agent can Read them. Display text stays the user's text (no path note).
|
|
57
|
-
// Exported for unit tests.
|
|
47
|
+
// Send images inline and other files by path. Keep those paths out of the
|
|
48
|
+
// user's display text.
|
|
58
49
|
export function buildUserMessage(
|
|
59
50
|
text: string,
|
|
60
51
|
uploads: StoredUpload[],
|
|
@@ -93,25 +84,51 @@ export function buildUserMessage(
|
|
|
93
84
|
return { content: blocks, parts }
|
|
94
85
|
}
|
|
95
86
|
|
|
96
|
-
//
|
|
97
|
-
// exceeded, the least-recently-active IDLE session is closed; a busy session is
|
|
98
|
-
// never evicted. Idle sessions are also closed after this TTL.
|
|
87
|
+
// Each live session owns a subprocess. Only idle sessions can be evicted.
|
|
99
88
|
const MAX_LIVE_SESSIONS = 8
|
|
100
89
|
const IDLE_TTL_MS = 5 * 60_000
|
|
101
90
|
|
|
102
|
-
//
|
|
103
|
-
//
|
|
104
|
-
|
|
105
|
-
const BG_TASK_TYPES = new Set(['local_bash', 'local_workflow'])
|
|
91
|
+
// Older CLIs lack background-task snapshots. These task types outlive the turn;
|
|
92
|
+
// other types count only when their event explicitly marks them backgrounded.
|
|
93
|
+
const LEGACY_BG_TASK_TYPES = new Set(['local_bash', 'local_workflow'])
|
|
106
94
|
|
|
107
95
|
type InputQueue = {
|
|
108
96
|
iterator: AsyncGenerator<SDKUserMessage>
|
|
109
|
-
push: (content: MessageContent) => void
|
|
97
|
+
push: (content: MessageContent, uuid: NonNullable<SDKUserMessage['uuid']>) => void
|
|
110
98
|
clear: () => void
|
|
111
99
|
close: () => void
|
|
112
100
|
}
|
|
113
101
|
|
|
102
|
+
type PendingMessage = {
|
|
103
|
+
input: SendMessageInput
|
|
104
|
+
content: MessageContent
|
|
105
|
+
titleSource: string
|
|
106
|
+
turnId: string
|
|
107
|
+
wireId: NonNullable<SDKUserMessage['uuid']>
|
|
108
|
+
label: string
|
|
109
|
+
resolve: () => void
|
|
110
|
+
reject: (error: Error) => void
|
|
111
|
+
completed: Promise<void>
|
|
112
|
+
complete: () => void
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// This queue outlives its subprocess. Register it before any async setup so
|
|
116
|
+
// concurrent first sends share one session, including across temp-id renames.
|
|
117
|
+
type SessionMessages = {
|
|
118
|
+
workspaceId: string
|
|
119
|
+
workspacePath: string
|
|
120
|
+
sessionId: string
|
|
121
|
+
isNew: boolean
|
|
122
|
+
pending: PendingMessage[]
|
|
123
|
+
active: PendingMessage | null
|
|
124
|
+
dispatching: boolean
|
|
125
|
+
stopping: boolean
|
|
126
|
+
publishedActivity: SessionActivity
|
|
127
|
+
live?: LiveSession
|
|
128
|
+
}
|
|
129
|
+
|
|
114
130
|
type LiveSession = {
|
|
131
|
+
messages: SessionMessages
|
|
115
132
|
workspaceId: string
|
|
116
133
|
workspacePath: string
|
|
117
134
|
workspaceEnv: Record<string, string>
|
|
@@ -120,41 +137,28 @@ type LiveSession = {
|
|
|
120
137
|
adapter: ClaudeAdapter
|
|
121
138
|
input: InputQueue
|
|
122
139
|
abort: AbortController
|
|
123
|
-
//
|
|
124
|
-
// (authoritative — it fires `idle` only after the CLI's input queue drains,
|
|
125
|
-
// so queued messages merged into one model turn can't wedge it, unlike the
|
|
126
|
-
// old send/result counter). `sendCCMessage` flips it to 'running'
|
|
127
|
-
// optimistically so the loader doesn't wait a subprocess round-trip.
|
|
140
|
+
// SDK activity, set optimistically to running when a prompt is dispatched.
|
|
128
141
|
activity: SessionActivity
|
|
129
|
-
//
|
|
130
|
-
// never does (older CLI), the `result` handler falls back to declaring idle.
|
|
142
|
+
// Without state events, the matching result is the turn-completion signal.
|
|
131
143
|
sawStateEvents: boolean
|
|
132
|
-
|
|
133
|
-
//
|
|
134
|
-
//
|
|
144
|
+
turnEnded: boolean
|
|
145
|
+
// The SDK's full set of background tasks, including subagents and ambient
|
|
146
|
+
// watchers. All retain their process; none alone makes the chat busy.
|
|
135
147
|
bgTasks: Set<string>
|
|
148
|
+
// Once this process emits a snapshot, task edges must never mutate its set:
|
|
149
|
+
// the SDK does not guarantee their ordering relative to snapshots.
|
|
150
|
+
sawBackgroundSnapshot: boolean
|
|
136
151
|
model: string | undefined
|
|
137
|
-
//
|
|
138
|
-
// inherits the provider configuration.
|
|
152
|
+
// Live flag settings; undefined inherits provider defaults.
|
|
139
153
|
fastMode: boolean | undefined
|
|
140
|
-
// Reasoning effort the query was created with. The SDK has no live setter for
|
|
141
|
-
// it (unlike setModel), so a change tears the session down and resumes.
|
|
142
154
|
effort: string | undefined
|
|
143
|
-
//
|
|
144
|
-
// turn is in flight (can't rebuild mid-turn), the session is torn down once it
|
|
145
|
-
// drains so the next message resumes with the requested effort.
|
|
146
|
-
desiredEffort: string | undefined
|
|
147
|
-
// Whether this query was built with `includePartialMessages` (live token
|
|
148
|
-
// streaming). Like effort, it's a construct-time option with no live setter,
|
|
149
|
-
// so a change tears the session down and resumes.
|
|
155
|
+
// `includePartialMessages` is fixed at creation, so changes require resume.
|
|
150
156
|
stream: boolean
|
|
151
|
-
//
|
|
152
|
-
|
|
153
|
-
desiredStream: boolean
|
|
157
|
+
// Rebuild before the next send, once this turn and background tasks finish.
|
|
158
|
+
staleCli: boolean
|
|
154
159
|
idleTimer: ReturnType<typeof setTimeout> | null
|
|
155
160
|
closed: boolean
|
|
156
|
-
//
|
|
157
|
-
// status update on the idle transition.
|
|
161
|
+
// Passed to the view builder when the session becomes idle.
|
|
158
162
|
lastBuilderError: string | undefined
|
|
159
163
|
// Introspection only (surfaced by /status) — not load-bearing.
|
|
160
164
|
createdAt: number
|
|
@@ -166,11 +170,9 @@ type LiveSession = {
|
|
|
166
170
|
}
|
|
167
171
|
|
|
168
172
|
const sessions = new Map<string, LiveSession>()
|
|
169
|
-
|
|
170
|
-
//
|
|
171
|
-
//
|
|
172
|
-
// carries the temp id; this alias re-routes it to the live session instead of
|
|
173
|
-
// spawning a duplicate. Temp ids are UUIDs, so stale entries never collide.
|
|
173
|
+
const messageQueues = new Map<string, SessionMessages>()
|
|
174
|
+
// `${workspaceId}:${tempId}` -> real session id. Follow-ups may still use the
|
|
175
|
+
// client's temporary id after the SDK has assigned the real one.
|
|
174
176
|
const aliases = new Map<string, string>()
|
|
175
177
|
|
|
176
178
|
function recKey(workspaceId: string, sessionId: string): string {
|
|
@@ -193,9 +195,10 @@ export function getCCActiveSessions(): {
|
|
|
193
195
|
activity: SessionActivity
|
|
194
196
|
}[] {
|
|
195
197
|
const out: { workspaceId: string; sessionId: string; activity: SessionActivity }[] = []
|
|
196
|
-
for (const
|
|
197
|
-
|
|
198
|
-
|
|
198
|
+
for (const messages of messageQueues.values()) {
|
|
199
|
+
const activity = messageActivity(messages)
|
|
200
|
+
if (activity !== 'idle') {
|
|
201
|
+
out.push({ workspaceId: messages.workspaceId, sessionId: messages.sessionId, activity })
|
|
199
202
|
}
|
|
200
203
|
}
|
|
201
204
|
return out
|
|
@@ -210,9 +213,9 @@ export type CCDebugSession = {
|
|
|
210
213
|
model: string | undefined
|
|
211
214
|
fastMode: boolean | undefined
|
|
212
215
|
effort: string | undefined
|
|
213
|
-
desiredEffort: string | undefined
|
|
214
216
|
stream: boolean
|
|
215
|
-
|
|
217
|
+
queuedMessages: number
|
|
218
|
+
staleCli: boolean
|
|
216
219
|
activity: SessionActivity
|
|
217
220
|
bgTasks: number
|
|
218
221
|
closed: boolean
|
|
@@ -222,8 +225,7 @@ export type CCDebugSession = {
|
|
|
222
225
|
lastUserText: string | undefined
|
|
223
226
|
}
|
|
224
227
|
|
|
225
|
-
//
|
|
226
|
-
// Read-only — never mutate the returned objects.
|
|
228
|
+
// Session diagnostics for /status.
|
|
227
229
|
export function getCCDebugSnapshot(): { sessions: CCDebugSession[]; aliases: number } {
|
|
228
230
|
return {
|
|
229
231
|
sessions: [...sessions.values()].map(s => ({
|
|
@@ -232,9 +234,9 @@ export function getCCDebugSnapshot(): { sessions: CCDebugSession[]; aliases: num
|
|
|
232
234
|
model: s.model,
|
|
233
235
|
fastMode: s.fastMode,
|
|
234
236
|
effort: s.effort,
|
|
235
|
-
desiredEffort: s.desiredEffort,
|
|
236
237
|
stream: s.stream,
|
|
237
|
-
|
|
238
|
+
queuedMessages: s.messages.pending.length,
|
|
239
|
+
staleCli: s.staleCli,
|
|
238
240
|
activity: s.activity,
|
|
239
241
|
bgTasks: s.bgTasks.size,
|
|
240
242
|
closed: s.closed,
|
|
@@ -247,9 +249,7 @@ export function getCCDebugSnapshot(): { sessions: CCDebugSession[]; aliases: num
|
|
|
247
249
|
}
|
|
248
250
|
}
|
|
249
251
|
|
|
250
|
-
//
|
|
251
|
-
// queued user messages and awaits when empty, so the session stays open between
|
|
252
|
-
// turns instead of ending when the current input is consumed.
|
|
252
|
+
// Waiting when empty keeps the SDK session open between prompts.
|
|
253
253
|
function createInputQueue(): InputQueue {
|
|
254
254
|
const buffer: SDKUserMessage[] = []
|
|
255
255
|
let wake: (() => void) | null = null
|
|
@@ -270,9 +270,10 @@ function createInputQueue(): InputQueue {
|
|
|
270
270
|
|
|
271
271
|
return {
|
|
272
272
|
iterator: gen(),
|
|
273
|
-
push(content: MessageContent) {
|
|
273
|
+
push(content: MessageContent, uuid: NonNullable<SDKUserMessage['uuid']>) {
|
|
274
274
|
buffer.push({
|
|
275
275
|
type: 'user',
|
|
276
|
+
uuid,
|
|
276
277
|
message: { role: 'user', content },
|
|
277
278
|
parent_tool_use_id: null
|
|
278
279
|
})
|
|
@@ -290,12 +291,22 @@ function createInputQueue(): InputQueue {
|
|
|
290
291
|
}
|
|
291
292
|
}
|
|
292
293
|
|
|
293
|
-
// Set the session's activity and broadcast the transition (deduped — repeated
|
|
294
|
-
// same-value events from the SDK don't re-broadcast).
|
|
295
294
|
function setActivity(s: LiveSession, activity: SessionActivity) {
|
|
296
|
-
if (s.activity === activity) return
|
|
297
295
|
s.activity = activity
|
|
298
|
-
|
|
296
|
+
publishMessageActivity(s.messages)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function messageActivity(messages: SessionMessages): SessionActivity {
|
|
300
|
+
const activity = messages.live?.activity ?? 'idle'
|
|
301
|
+
if (activity !== 'idle') return activity
|
|
302
|
+
return messages.active || messages.pending.length || messages.dispatching ? 'running' : 'idle'
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function publishMessageActivity(messages: SessionMessages) {
|
|
306
|
+
const activity = messageActivity(messages)
|
|
307
|
+
if (messages.publishedActivity === activity) return
|
|
308
|
+
messages.publishedActivity = activity
|
|
309
|
+
broadcast(messages.workspaceId, { type: 'status', sessionId: messages.sessionId, activity })
|
|
299
310
|
}
|
|
300
311
|
|
|
301
312
|
function clearIdle(s: LiveSession) {
|
|
@@ -308,10 +319,9 @@ function clearIdle(s: LiveSession) {
|
|
|
308
319
|
function armIdle(s: LiveSession) {
|
|
309
320
|
clearIdle(s)
|
|
310
321
|
s.idleTimer = setTimeout(() => {
|
|
311
|
-
if (s.activity
|
|
322
|
+
if (s.activity !== 'idle' || s.messages.active || s.messages.dispatching) return
|
|
312
323
|
if (s.bgTasks.size > 0) {
|
|
313
|
-
//
|
|
314
|
-
// (renders, watch loops). Keep the session alive until they finish.
|
|
324
|
+
// Eviction would kill the background tasks too.
|
|
315
325
|
debug(
|
|
316
326
|
`cc idle-keepalive ws=${s.workspaceId} session=${s.sessionId} bgTasks=${s.bgTasks.size}`
|
|
317
327
|
)
|
|
@@ -342,6 +352,15 @@ function teardown(s: LiveSession) {
|
|
|
342
352
|
if (sessions.get(recKey(s.workspaceId, s.sessionId)) === s) {
|
|
343
353
|
sessions.delete(recKey(s.workspaceId, s.sessionId))
|
|
344
354
|
}
|
|
355
|
+
if (s.messages.live === s) s.messages.live = undefined
|
|
356
|
+
publishMessageActivity(s.messages)
|
|
357
|
+
forgetEmptyQueue(s.messages)
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function forgetEmptyQueue(messages: SessionMessages) {
|
|
361
|
+
if (messages.live || messages.dispatching || messages.active || messages.pending.length) return
|
|
362
|
+
const key = recKey(messages.workspaceId, messages.sessionId)
|
|
363
|
+
if (messageQueues.get(key) === messages) messageQueues.delete(key)
|
|
345
364
|
}
|
|
346
365
|
|
|
347
366
|
function isCurrentLiveSession(s: LiveSession, abort: AbortController): boolean {
|
|
@@ -386,39 +405,46 @@ function startClaudeSessionTitleJob(s: LiveSession) {
|
|
|
386
405
|
})()
|
|
387
406
|
}
|
|
388
407
|
|
|
389
|
-
//
|
|
390
|
-
// that differs from the client's temporary id, so we rekey the registry and
|
|
391
|
-
// tell the client to move its optimistic state. Subsequent inits report the
|
|
392
|
-
// same id and no-op.
|
|
408
|
+
// Move both registries to the SDK's real id, preserving the temporary alias.
|
|
393
409
|
function renameSession(s: LiveSession, realId: string): string {
|
|
394
410
|
const from = s.sessionId
|
|
395
411
|
sessions.delete(recKey(s.workspaceId, from))
|
|
396
412
|
s.sessionId = realId
|
|
397
413
|
sessions.set(recKey(s.workspaceId, realId), s)
|
|
398
414
|
aliases.set(recKey(s.workspaceId, from), realId)
|
|
415
|
+
messageQueues.delete(recKey(s.workspaceId, from))
|
|
416
|
+
s.messages.sessionId = realId
|
|
417
|
+
s.messages.isNew = false
|
|
418
|
+
messageQueues.set(recKey(s.workspaceId, realId), s.messages)
|
|
399
419
|
return from
|
|
400
420
|
}
|
|
401
421
|
|
|
402
|
-
//
|
|
403
|
-
//
|
|
404
|
-
// effort/streaming change or arm the idle timer.
|
|
422
|
+
// Keep the active message reserved across async bookkeeping. Sends arriving
|
|
423
|
+
// here join moi's queue; they cannot race a teardown or change the live model.
|
|
405
424
|
async function onSessionIdle(s: LiveSession) {
|
|
425
|
+
const active = s.messages.active
|
|
426
|
+
if (s.messages.dispatching || (active && !s.turnEnded)) return
|
|
406
427
|
await markViewBuilderWaitingBySession(
|
|
407
428
|
s.workspaceId,
|
|
408
429
|
s.workspacePath,
|
|
409
430
|
s.sessionId,
|
|
410
431
|
s.lastBuilderError
|
|
411
432
|
)
|
|
412
|
-
if (s.
|
|
413
|
-
|
|
433
|
+
if (s.closed || s.messages.dispatching || s.messages.active !== active) return
|
|
434
|
+
active?.complete()
|
|
435
|
+
s.messages.active = null
|
|
436
|
+
setActivity(s, 'idle')
|
|
437
|
+
armIdle(s)
|
|
438
|
+
void dispatchNextMessage(s.messages)
|
|
414
439
|
}
|
|
415
440
|
|
|
416
441
|
async function consume(s: LiveSession) {
|
|
417
442
|
try {
|
|
418
443
|
for await (const msg of s.q) {
|
|
419
|
-
|
|
444
|
+
if (s.closed) break
|
|
420
445
|
tapWire(s.workspaceId, 'recv', msg)
|
|
421
446
|
if (msg.type === 'system' && msg.subtype === 'init') {
|
|
447
|
+
s.messages.isNew = false
|
|
422
448
|
const realId = msg.session_id
|
|
423
449
|
if (realId && realId !== s.sessionId) {
|
|
424
450
|
const from = renameSession(s, realId)
|
|
@@ -433,10 +459,7 @@ async function consume(s: LiveSession) {
|
|
|
433
459
|
})
|
|
434
460
|
}
|
|
435
461
|
startClaudeSessionTitleJob(s)
|
|
436
|
-
// Seed
|
|
437
|
-
// it has none yet, so an explicit user PUT (or a migrated temp-id edit)
|
|
438
|
-
// always wins. A default run leaves no file and falls back to the
|
|
439
|
-
// workspace defaults.
|
|
462
|
+
// Seed explicit startup settings only when no saved picker choice exists.
|
|
440
463
|
if (
|
|
441
464
|
(s.model || s.effort || s.fastMode !== undefined) &&
|
|
442
465
|
!(await hasSessionConfig(s.workspacePath, s.sessionId))
|
|
@@ -450,8 +473,7 @@ async function consume(s: LiveSession) {
|
|
|
450
473
|
}
|
|
451
474
|
for (const ev of s.adapter.ingest(msg)) {
|
|
452
475
|
if (ev.kind === 'preview') {
|
|
453
|
-
//
|
|
454
|
-
// it never enters the persisted/replayable transcript path.
|
|
476
|
+
// Token previews are transient and stay outside transcript history.
|
|
455
477
|
broadcast(s.workspaceId, {
|
|
456
478
|
type: 'preview',
|
|
457
479
|
sessionId: s.sessionId,
|
|
@@ -466,18 +488,12 @@ async function consume(s: LiveSession) {
|
|
|
466
488
|
if (msg.type === 'system' && msg.subtype === 'init') {
|
|
467
489
|
debug(`cc init ws=${s.workspaceId} session=${s.sessionId}`)
|
|
468
490
|
}
|
|
469
|
-
//
|
|
470
|
-
// queued message the CLI ran as its own turn after the previous result,
|
|
471
|
-
// or an SDK-initiated turn (e.g. a background-task notification waking
|
|
472
|
-
// the model). Re-assert running so the spinner tracks real activity.
|
|
491
|
+
// Background notifications can start an SDK turn without a user send.
|
|
473
492
|
if ((msg.type === 'assistant' || msg.type === 'stream_event') && s.activity === 'idle') {
|
|
474
493
|
setActivity(s, 'running')
|
|
475
494
|
}
|
|
476
|
-
//
|
|
477
|
-
//
|
|
478
|
-
// (one `result` for N sends) still end in a clean idle here. Observed
|
|
479
|
-
// empirically: current CLIs don't emit this in streaming-input mode, so
|
|
480
|
-
// the `result` fallback below is the everyday path.
|
|
495
|
+
// Prefer explicit idle events when available; otherwise use the result
|
|
496
|
+
// fallback below. Some CLIs omit these events in streaming-input mode.
|
|
481
497
|
if (msg.type === 'system' && msg.subtype === 'session_state_changed') {
|
|
482
498
|
s.sawStateEvents = true
|
|
483
499
|
s.lastActivityAt = Date.now()
|
|
@@ -485,35 +501,54 @@ async function consume(s: LiveSession) {
|
|
|
485
501
|
if (msg.state === 'running') setActivity(s, 'running')
|
|
486
502
|
else if (msg.state === 'requires_action') setActivity(s, 'requires-action')
|
|
487
503
|
else if (msg.state === 'idle') {
|
|
488
|
-
setActivity(s, 'idle')
|
|
489
504
|
await onSessionIdle(s)
|
|
490
505
|
}
|
|
491
506
|
}
|
|
492
|
-
//
|
|
493
|
-
//
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
if (
|
|
497
|
-
s.
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
507
|
+
// Snapshots replace the entire set, healing missed starts/completions.
|
|
508
|
+
// Keep the edge-based fallback only until this process sends a snapshot.
|
|
509
|
+
if (msg.type === 'system') {
|
|
510
|
+
let tasksChanged = false
|
|
511
|
+
if (msg.subtype === 'background_tasks_changed') {
|
|
512
|
+
s.sawBackgroundSnapshot = true
|
|
513
|
+
s.bgTasks = new Set(msg.tasks.map(task => task.task_id))
|
|
514
|
+
tasksChanged = true
|
|
515
|
+
} else if (!s.sawBackgroundSnapshot) {
|
|
516
|
+
if (
|
|
517
|
+
msg.subtype === 'task_started' &&
|
|
518
|
+
(msg.is_backgrounded || LEGACY_BG_TASK_TYPES.has(msg.task_type ?? ''))
|
|
519
|
+
) {
|
|
520
|
+
s.bgTasks.add(msg.task_id)
|
|
521
|
+
} else if (msg.subtype === 'task_notification') {
|
|
522
|
+
tasksChanged = s.bgTasks.delete(msg.task_id)
|
|
523
|
+
} else if (msg.subtype === 'task_updated') {
|
|
524
|
+
const status = msg.patch.status
|
|
525
|
+
if (
|
|
526
|
+
status === 'completed' ||
|
|
527
|
+
status === 'failed' ||
|
|
528
|
+
status === 'killed' ||
|
|
529
|
+
msg.patch.is_backgrounded === false
|
|
530
|
+
) {
|
|
531
|
+
tasksChanged = s.bgTasks.delete(msg.task_id)
|
|
532
|
+
} else if (msg.patch.is_backgrounded) {
|
|
533
|
+
s.bgTasks.add(msg.task_id)
|
|
534
|
+
}
|
|
535
|
+
}
|
|
508
536
|
}
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
if (status === 'completed' || status === 'failed' || status === 'killed') {
|
|
513
|
-
s.bgTasks.delete(msg.task_id)
|
|
537
|
+
if (tasksChanged) {
|
|
538
|
+
debug(`cc bg-tasks ws=${s.workspaceId} session=${s.sessionId} live=${s.bgTasks.size}`)
|
|
539
|
+
void dispatchNextMessage(s.messages)
|
|
514
540
|
}
|
|
515
541
|
}
|
|
516
542
|
if (msg.type === 'result') {
|
|
543
|
+
// Newer CLIs identify the user messages consumed by a result. An
|
|
544
|
+
// autonomous background turn can finish while our prompt is still
|
|
545
|
+
// waiting inside the CLI; its result must not release that prompt.
|
|
546
|
+
const active = s.messages.active
|
|
547
|
+
const consumed =
|
|
548
|
+
msg.user_message_uuids ?? (msg.user_message_uuid ? [msg.user_message_uuid] : undefined)
|
|
549
|
+
const turnFinished =
|
|
550
|
+
!active || (!msg.queued_turn_count && (!consumed || consumed.includes(active.wireId)))
|
|
551
|
+
if (turnFinished) s.turnEnded = true
|
|
517
552
|
s.lastActivityAt = Date.now()
|
|
518
553
|
// Remembered for the idle transition — the view builder shows the last
|
|
519
554
|
// turn's error once the queue drains.
|
|
@@ -526,11 +561,9 @@ async function consume(s: LiveSession) {
|
|
|
526
561
|
s.refreshSessionsOnResult = false
|
|
527
562
|
broadcast(s.workspaceId, { type: 'sessions_changed', sessionId: s.sessionId })
|
|
528
563
|
}
|
|
529
|
-
//
|
|
530
|
-
//
|
|
531
|
-
|
|
532
|
-
if (!s.sawStateEvents) {
|
|
533
|
-
setActivity(s, 'idle')
|
|
564
|
+
// Without state events, only a result that finishes the active prompt
|
|
565
|
+
// (or an autonomous turn when none is active) can release the queue.
|
|
566
|
+
if (!s.sawStateEvents && turnFinished) {
|
|
534
567
|
await onSessionIdle(s)
|
|
535
568
|
}
|
|
536
569
|
}
|
|
@@ -549,18 +582,40 @@ async function consume(s: LiveSession) {
|
|
|
549
582
|
await markViewBuilderWaitingBySession(s.workspaceId, s.workspacePath, s.sessionId, message)
|
|
550
583
|
}
|
|
551
584
|
} finally {
|
|
552
|
-
//
|
|
585
|
+
// An expected restart only replaces the subprocess. An unexpected exit
|
|
586
|
+
// cancels pending sends visibly rather than leaving their promises hanging.
|
|
587
|
+
if (!s.closed) {
|
|
588
|
+
const error = new Error('Agent session closed before queued messages were sent')
|
|
589
|
+
if (s.messages.pending.length)
|
|
590
|
+
broadcast(s.workspaceId, { kind: 'error', sessionId: s.sessionId, content: error.message })
|
|
591
|
+
cancelPendingMessages(s.messages, error)
|
|
592
|
+
s.messages.active?.complete()
|
|
593
|
+
s.messages.active = null
|
|
594
|
+
}
|
|
553
595
|
teardown(s)
|
|
554
596
|
}
|
|
555
597
|
}
|
|
556
598
|
|
|
599
|
+
function cancelPendingMessages(messages: SessionMessages, error: Error) {
|
|
600
|
+
for (const message of messages.pending.splice(0)) {
|
|
601
|
+
message.reject(error)
|
|
602
|
+
message.complete()
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
557
606
|
// Close one idle session to stay under the cap. A running session — or one
|
|
558
607
|
// with live background tasks — is never evicted; if everything is busy we allow
|
|
559
608
|
// a temporary overflow rather than killing a run.
|
|
560
609
|
function evictIfNeeded() {
|
|
561
610
|
if (sessions.size < MAX_LIVE_SESSIONS) return
|
|
562
611
|
for (const s of sessions.values()) {
|
|
563
|
-
if (
|
|
612
|
+
if (
|
|
613
|
+
s.activity === 'idle' &&
|
|
614
|
+
s.bgTasks.size === 0 &&
|
|
615
|
+
!s.messages.dispatching &&
|
|
616
|
+
!s.messages.active &&
|
|
617
|
+
s.messages.pending.length === 0
|
|
618
|
+
) {
|
|
564
619
|
teardown(s)
|
|
565
620
|
return
|
|
566
621
|
}
|
|
@@ -568,6 +623,7 @@ function evictIfNeeded() {
|
|
|
568
623
|
}
|
|
569
624
|
|
|
570
625
|
function createLiveSession(input: {
|
|
626
|
+
messages: SessionMessages
|
|
571
627
|
workspaceId: string
|
|
572
628
|
workspacePath: string
|
|
573
629
|
sessionId: string
|
|
@@ -575,11 +631,8 @@ function createLiveSession(input: {
|
|
|
575
631
|
model: string | undefined
|
|
576
632
|
effort: string | undefined
|
|
577
633
|
fastMode: boolean | undefined
|
|
578
|
-
// Live token streaming (`includePartialMessages`). Only enabled when the
|
|
579
|
-
// client opts in; off leaves the query byte-for-byte as before.
|
|
580
634
|
stream: boolean
|
|
581
|
-
// Resolved workspace env
|
|
582
|
-
// Bash tool can use workspace secrets. Frozen at spawn — see restartWorkspaceSessions.
|
|
635
|
+
// Resolved workspace env, fixed for the lifetime of the subprocess.
|
|
583
636
|
workspaceEnv: Record<string, string>
|
|
584
637
|
sessionTitleSource: string | undefined
|
|
585
638
|
}): LiveSession {
|
|
@@ -590,25 +643,17 @@ function createLiveSession(input: {
|
|
|
590
643
|
const options: Options = {
|
|
591
644
|
abortController: abort,
|
|
592
645
|
pathToClaudeCodeExecutable: requireHarnessExecutable('claude-code'),
|
|
593
|
-
//
|
|
594
|
-
// (limit hit / closed / error) the session is torn down and the next
|
|
595
|
-
// message recreates it via resume.
|
|
646
|
+
// One query spans many user messages.
|
|
596
647
|
maxTurns: 1000,
|
|
597
648
|
cwd: input.workspacePath,
|
|
598
|
-
//
|
|
599
|
-
// display to 'omitted' — the API still emits a `thinking` block but with
|
|
600
|
-
// empty text, which the adapter drops (`if (b.thinking)`), so no
|
|
601
|
-
// "Thinking" row ever reaches the timeline. Request the summary
|
|
602
|
-
// explicitly so reasoning stays visible.
|
|
649
|
+
// Request summaries explicitly; some models otherwise omit thinking text.
|
|
603
650
|
thinking: { type: 'adaptive', display: 'summarized' },
|
|
604
651
|
...(input.model ? { model: input.model } : {}),
|
|
605
|
-
//
|
|
606
|
-
//
|
|
607
|
-
// the SDK under-types the union (no 'xhigh') vs our pass-through string.
|
|
652
|
+
// Harness-neutral settings are strings; the picker supplies this model's
|
|
653
|
+
// supported effort levels from the SDK catalog.
|
|
608
654
|
...(input.effort ? { effort: input.effort as Options['effort'] } : {}),
|
|
609
655
|
...(input.fastMode !== undefined ? { settings: { fastMode: input.fastMode } } : {}),
|
|
610
|
-
//
|
|
611
|
-
// live token-by-token preview. Off = unchanged behavior (whole blocks only).
|
|
656
|
+
// Partial frames enable the opt-in live preview.
|
|
612
657
|
includePartialMessages: input.stream,
|
|
613
658
|
permissionMode: 'auto',
|
|
614
659
|
// Every tool call is approved before the permission system runs — see
|
|
@@ -625,6 +670,7 @@ function createLiveSession(input: {
|
|
|
625
670
|
if (!input.isNew) options.resume = input.sessionId
|
|
626
671
|
|
|
627
672
|
const session: LiveSession = {
|
|
673
|
+
messages: input.messages,
|
|
628
674
|
workspaceId: input.workspaceId,
|
|
629
675
|
workspacePath: input.workspacePath,
|
|
630
676
|
workspaceEnv: input.workspaceEnv,
|
|
@@ -635,13 +681,14 @@ function createLiveSession(input: {
|
|
|
635
681
|
abort,
|
|
636
682
|
activity: 'idle',
|
|
637
683
|
sawStateEvents: false,
|
|
684
|
+
turnEnded: false,
|
|
638
685
|
bgTasks: new Set(),
|
|
686
|
+
sawBackgroundSnapshot: false,
|
|
639
687
|
model: input.model,
|
|
640
688
|
fastMode: input.fastMode,
|
|
641
689
|
effort: input.effort,
|
|
642
|
-
desiredEffort: input.effort,
|
|
643
690
|
stream: input.stream,
|
|
644
|
-
|
|
691
|
+
staleCli: false,
|
|
645
692
|
idleTimer: null,
|
|
646
693
|
closed: false,
|
|
647
694
|
lastBuilderError: undefined,
|
|
@@ -653,6 +700,7 @@ function createLiveSession(input: {
|
|
|
653
700
|
sessionTitleAbort: null
|
|
654
701
|
}
|
|
655
702
|
sessions.set(recKey(session.workspaceId, session.sessionId), session)
|
|
703
|
+
input.messages.live = session
|
|
656
704
|
debug(
|
|
657
705
|
`cc create ${input.isNew ? 'new' : 'resume'} ws=${input.workspaceId} session=${input.sessionId} model=${input.model ?? 'default'} effort=${input.effort ?? 'default'} fast=${input.fastMode ?? 'default'} live=${sessions.size}`
|
|
658
706
|
)
|
|
@@ -660,38 +708,17 @@ function createLiveSession(input: {
|
|
|
660
708
|
return session
|
|
661
709
|
}
|
|
662
710
|
|
|
663
|
-
//
|
|
664
|
-
//
|
|
665
|
-
export async function sendCCMessage(input: {
|
|
666
|
-
|
|
667
|
-
workspacePath: string
|
|
668
|
-
sessionId: string
|
|
669
|
-
isNew: boolean
|
|
670
|
-
content: string
|
|
671
|
-
// Upload ids attached to this turn (resolved from the upload store here).
|
|
672
|
-
attachments?: string[]
|
|
673
|
-
optimisticId?: string
|
|
674
|
-
model?: string
|
|
675
|
-
effort?: string
|
|
676
|
-
fastMode?: boolean
|
|
677
|
-
stream?: boolean
|
|
678
|
-
// Structured moi context (lib/moi-context.ts), rendered here and injected
|
|
679
|
-
// as a leading system-reminder text block; the display parts never see it.
|
|
680
|
-
context?: MoiContext
|
|
681
|
-
}): Promise<void> {
|
|
682
|
-
// Resolve any attachments into agent content blocks + display parts. Unknown
|
|
683
|
-
// or expired ids are silently dropped (resolveUploads filters them) — if that
|
|
684
|
-
// leaves nothing to say at all, don't spin up a session for an empty turn.
|
|
711
|
+
// Accept immediately, but keep the prompt and its settings in moi until its
|
|
712
|
+
// turn starts. The returned promise settles when the message reaches the SDK.
|
|
713
|
+
export async function sendCCMessage(input: SendMessageInput): Promise<void> {
|
|
714
|
+
// Expired uploads are omitted. Avoid starting a session if nothing remains.
|
|
685
715
|
const uploads = input.attachments?.length
|
|
686
716
|
? resolveUploads(input.workspaceId, input.attachments)
|
|
687
717
|
: []
|
|
688
718
|
if (!input.content && uploads.length === 0) return
|
|
689
719
|
const { content: userContent, parts } = buildUserMessage(input.content, uploads)
|
|
690
|
-
//
|
|
691
|
-
//
|
|
692
|
-
// home-card previews) skips tag-leading text, so a prefixed string would
|
|
693
|
-
// hide every moi message from it. On replay the adapter strips the block to
|
|
694
|
-
// empty and drops it.
|
|
720
|
+
// Keep context in its own block: the SDK skips tag-leading blocks when
|
|
721
|
+
// extracting titles and previews, and the adapter strips them on replay.
|
|
695
722
|
const content: MessageContent = input.context
|
|
696
723
|
? [
|
|
697
724
|
{ type: 'text', text: moiContextSystemReminder(renderMoiContext(input.context)) },
|
|
@@ -701,95 +728,26 @@ export async function sendCCMessage(input: {
|
|
|
701
728
|
]
|
|
702
729
|
: userContent
|
|
703
730
|
|
|
704
|
-
const
|
|
705
|
-
let
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
// session down and recreate it via resume — the change lands on this very
|
|
709
|
-
// turn. A busy session keeps its settings until the in-flight turn ends.
|
|
710
|
-
if (s && (input.effort !== s.effort || wantStream !== s.stream) && s.activity === 'idle') {
|
|
711
|
-
teardown(s)
|
|
712
|
-
s = undefined
|
|
713
|
-
}
|
|
714
|
-
if (s) {
|
|
715
|
-
clearIdle(s)
|
|
716
|
-
if (input.model !== s.model) {
|
|
717
|
-
try {
|
|
718
|
-
await s.q.setModel(input.model)
|
|
719
|
-
s.model = input.model
|
|
720
|
-
} catch (err) {
|
|
721
|
-
console.error('[cc-session] setModel failed', err)
|
|
722
|
-
}
|
|
723
|
-
// setModel is a control round-trip to the subprocess. During that await a
|
|
724
|
-
// concurrent turn `result` can drain this session to idle and — if effort
|
|
725
|
-
// or streaming diverged — tear it down (see the `result` handler). If that
|
|
726
|
-
// happened, drop the dead handle and fall through to recreate a fresh
|
|
727
|
-
// session below, rather than enqueue onto a closed input queue (which would
|
|
728
|
-
// silently lose the message and hang the spinner).
|
|
729
|
-
if (s.closed) s = undefined
|
|
730
|
-
}
|
|
731
|
-
if (s && input.fastMode !== s.fastMode) {
|
|
732
|
-
try {
|
|
733
|
-
await s.q.applyFlagSettings({ fastMode: input.fastMode ?? null })
|
|
734
|
-
s.fastMode = input.fastMode
|
|
735
|
-
} catch (err) {
|
|
736
|
-
console.error('[cc-session] applyFlagSettings failed', err)
|
|
737
|
-
}
|
|
738
|
-
if (s.closed) s = undefined
|
|
739
|
-
}
|
|
740
|
-
if (s) {
|
|
741
|
-
// Effort/streaming can't change on a running query; record the request so
|
|
742
|
-
// the session rebuilds once its turns drain (see the `result` handler).
|
|
743
|
-
// Reaching here with a divergent value means the session is busy — an idle
|
|
744
|
-
// one was torn down above.
|
|
745
|
-
s.desiredEffort = input.effort
|
|
746
|
-
s.desiredStream = wantStream
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
if (!s) {
|
|
750
|
-
// The agent only sees secrets scoped to the 'agent' sink (plus .env).
|
|
751
|
-
// Resolved before the probe below so both see the same env.
|
|
752
|
-
const workspaceEnv = await resolveWorkspaceEnv(input.workspacePath)
|
|
753
|
-
// Resuming a session with no file on disk hard-fails the CLI with "No
|
|
754
|
-
// conversation found" — and a dangling id can be selected forever (a
|
|
755
|
-
// brand-new chat whose first turn died before init persisted anything,
|
|
756
|
-
// or session files cleaned up externally), wedging the chat. Start fresh
|
|
757
|
-
// instead: the init rename then migrates this id to the real one
|
|
758
|
-
// everywhere (selected session, session config, view builders, client).
|
|
759
|
-
const isNew =
|
|
760
|
-
input.isNew ||
|
|
761
|
-
!(await claudeSessionExists(input.sessionId, input.workspacePath, workspaceEnv))
|
|
762
|
-
if (isNew !== input.isNew) {
|
|
763
|
-
debug(`cc resume-missing ws=${input.workspaceId} session=${input.sessionId} — starting fresh`)
|
|
764
|
-
}
|
|
765
|
-
s = createLiveSession({
|
|
731
|
+
const key = liveKey(input.workspaceId, input.sessionId)
|
|
732
|
+
let messages = messageQueues.get(key)
|
|
733
|
+
if (!messages) {
|
|
734
|
+
messages = {
|
|
766
735
|
workspaceId: input.workspaceId,
|
|
767
736
|
workspacePath: input.workspacePath,
|
|
768
|
-
sessionId: input.sessionId,
|
|
769
|
-
isNew,
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
uploads.map(upload => upload.filename)
|
|
778
|
-
)
|
|
779
|
-
: undefined,
|
|
780
|
-
workspaceEnv
|
|
781
|
-
})
|
|
737
|
+
sessionId: aliases.get(recKey(input.workspaceId, input.sessionId)) ?? input.sessionId,
|
|
738
|
+
isNew: input.isNew && !aliases.has(recKey(input.workspaceId, input.sessionId)),
|
|
739
|
+
pending: [],
|
|
740
|
+
active: null,
|
|
741
|
+
dispatching: false,
|
|
742
|
+
stopping: false,
|
|
743
|
+
publishedActivity: 'idle'
|
|
744
|
+
}
|
|
745
|
+
messageQueues.set(key, messages)
|
|
782
746
|
}
|
|
783
|
-
// Streaming-input mode does NOT echo the pushed user message back in the
|
|
784
|
-
// output stream (string-prompt mode did — that's what expectUserEcho was
|
|
785
|
-
// for), so the adapter never emits a user turn. Synthesize and broadcast it
|
|
786
|
-
// ourselves so EVERY connected tab shows the user's bubble — not just the
|
|
787
|
-
// sender (which inserts it optimistically). Keyed by optimisticId, so the
|
|
788
|
-
// sender's optimistic turn upserts in place rather than duplicating.
|
|
789
747
|
const turnId = input.optimisticId ?? crypto.randomUUID()
|
|
790
|
-
broadcast(
|
|
748
|
+
broadcast(messages.workspaceId, {
|
|
791
749
|
kind: 'turn',
|
|
792
|
-
sessionId:
|
|
750
|
+
sessionId: messages.sessionId,
|
|
793
751
|
turn: {
|
|
794
752
|
id: turnId,
|
|
795
753
|
role: 'user',
|
|
@@ -798,50 +756,177 @@ export async function sendCCMessage(input: {
|
|
|
798
756
|
timestamp: new Date().toISOString()
|
|
799
757
|
}
|
|
800
758
|
})
|
|
801
|
-
// Safety net: if a future SDK does echo the user message, the adapter re-ids
|
|
802
|
-
// that echo to the same optimisticId so it collapses onto the turn above
|
|
803
|
-
// instead of duplicating.
|
|
804
|
-
if (input.optimisticId) s.adapter.expectUserEcho(input.optimisticId, input.content)
|
|
805
|
-
|
|
806
|
-
s.lastActivityAt = Date.now()
|
|
807
|
-
// For an attachment-only message, fall back to the filenames so the thread
|
|
808
|
-
// list / status view don't show a blank label.
|
|
809
759
|
const label = input.content || uploads.map(u => u.filename).join(', ')
|
|
810
|
-
|
|
760
|
+
const completion = Promise.withResolvers<void>()
|
|
761
|
+
const accepted = new Promise<void>((resolve, reject) => {
|
|
762
|
+
messages.pending.push({
|
|
763
|
+
input,
|
|
764
|
+
content,
|
|
765
|
+
titleSource: buildSessionTitleSource(
|
|
766
|
+
input.content,
|
|
767
|
+
uploads.map(u => u.filename)
|
|
768
|
+
),
|
|
769
|
+
turnId,
|
|
770
|
+
wireId: crypto.randomUUID(),
|
|
771
|
+
label: label.replace(/\s+/g, ' ').slice(0, 120),
|
|
772
|
+
resolve,
|
|
773
|
+
reject,
|
|
774
|
+
completed: completion.promise,
|
|
775
|
+
complete: completion.resolve
|
|
776
|
+
})
|
|
777
|
+
})
|
|
778
|
+
publishMessageActivity(messages)
|
|
779
|
+
void dispatchNextMessage(messages)
|
|
780
|
+
return accepted
|
|
781
|
+
}
|
|
811
782
|
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
783
|
+
// Serialize session creation, per-message settings, and prompt writes.
|
|
784
|
+
// Recheck cancellation and replacement after awaits before sending the prompt.
|
|
785
|
+
async function dispatchNextMessage(messages: SessionMessages): Promise<void> {
|
|
786
|
+
if (messages.dispatching || messages.stopping || messages.active) return
|
|
787
|
+
const message = messages.pending[0]
|
|
788
|
+
if (!message) {
|
|
789
|
+
forgetEmptyQueue(messages)
|
|
790
|
+
return
|
|
791
|
+
}
|
|
792
|
+
let s = messages.live
|
|
793
|
+
if (s && s.activity !== 'idle') return
|
|
794
|
+
const { input } = message
|
|
795
|
+
const stream = input.stream === true
|
|
796
|
+
const rebuild = s && (s.staleCli || stream !== s.stream)
|
|
797
|
+
// Background jobs belong to their subprocess. Retain both the job and the
|
|
798
|
+
// queued prompt until it is safe to resume with the requested configuration.
|
|
799
|
+
if (s && rebuild && s.bgTasks.size > 0) return
|
|
800
|
+
|
|
801
|
+
messages.dispatching = true
|
|
802
|
+
const cancelled = () => messages.stopping || messages.pending[0] !== message
|
|
803
|
+
try {
|
|
804
|
+
if (s && rebuild) {
|
|
805
|
+
teardown(s)
|
|
806
|
+
s = undefined
|
|
807
|
+
}
|
|
808
|
+
if (!s) {
|
|
809
|
+
const workspaceEnv = await resolveWorkspaceEnv(messages.workspacePath)
|
|
810
|
+
if (cancelled()) return
|
|
811
|
+
const isNew =
|
|
812
|
+
messages.isNew ||
|
|
813
|
+
!(await claudeSessionExists(messages.sessionId, messages.workspacePath, workspaceEnv))
|
|
814
|
+
if (cancelled()) return
|
|
815
|
+
s = createLiveSession({
|
|
816
|
+
messages,
|
|
817
|
+
workspaceId: messages.workspaceId,
|
|
818
|
+
workspacePath: messages.workspacePath,
|
|
819
|
+
sessionId: messages.sessionId,
|
|
820
|
+
isNew,
|
|
821
|
+
model: input.model,
|
|
822
|
+
effort: input.effort,
|
|
823
|
+
fastMode: input.fastMode,
|
|
824
|
+
stream,
|
|
825
|
+
workspaceEnv,
|
|
826
|
+
sessionTitleSource: isNew ? message.titleSource : undefined
|
|
827
|
+
})
|
|
828
|
+
} else {
|
|
829
|
+
clearIdle(s)
|
|
830
|
+
// A failed setter must reject this send, never silently use the previous
|
|
831
|
+
// model or flags. Later queued messages can still use the healthy query.
|
|
832
|
+
if (input.model !== s.model) {
|
|
833
|
+
await s.q.setModel(input.model)
|
|
834
|
+
// Stop cancels the prompt, not a control request already acknowledged
|
|
835
|
+
// by the CLI. Remember the applied value so the next send can reset it.
|
|
836
|
+
if (!s.closed) s.model = input.model
|
|
837
|
+
if (cancelled()) return
|
|
838
|
+
if (s.closed) throw new Error('Agent session closed before the message was sent')
|
|
839
|
+
}
|
|
840
|
+
if (input.effort !== s.effort || input.fastMode !== s.fastMode) {
|
|
841
|
+
await s.q.applyFlagSettings({
|
|
842
|
+
...(input.effort !== s.effort
|
|
843
|
+
? { effortLevel: (input.effort as Options['effort']) ?? null }
|
|
844
|
+
: {}),
|
|
845
|
+
...(input.fastMode !== s.fastMode ? { fastMode: input.fastMode ?? null } : {})
|
|
846
|
+
})
|
|
847
|
+
if (!s.closed) {
|
|
848
|
+
s.effort = input.effort
|
|
849
|
+
s.fastMode = input.fastMode
|
|
850
|
+
}
|
|
851
|
+
if (cancelled()) return
|
|
852
|
+
if (s.closed) throw new Error('Agent session closed before the message was sent')
|
|
853
|
+
}
|
|
854
|
+
}
|
|
815
855
|
await markViewBuilderBuildingBySession(s.workspaceId, s.workspacePath, s.sessionId)
|
|
856
|
+
if (cancelled()) return
|
|
857
|
+
if (s.closed) throw new Error('Agent session closed before the message was sent')
|
|
858
|
+
// A catalog refresh can arrive during any of the awaits above. Retry
|
|
859
|
+
// before handing off the prompt; the queue still owns it at this point.
|
|
860
|
+
if (s.staleCli) {
|
|
861
|
+
if (s.bgTasks.size === 0) teardown(s)
|
|
862
|
+
return
|
|
863
|
+
}
|
|
864
|
+
messages.pending.shift()
|
|
865
|
+
messages.active = message
|
|
866
|
+
s.turnEnded = false
|
|
867
|
+
s.lastActivityAt = Date.now()
|
|
868
|
+
s.lastUserText = message.label
|
|
869
|
+
s.adapter.expectUserEcho(message.turnId, input.content)
|
|
816
870
|
setActivity(s, 'running')
|
|
871
|
+
clearIdle(s)
|
|
872
|
+
s.input.push(message.content, message.wireId)
|
|
873
|
+
tapWire(s.workspaceId, 'send', { type: 'user', content: message.content })
|
|
874
|
+
message.resolve()
|
|
875
|
+
} catch (error) {
|
|
876
|
+
if (!cancelled() && s?.staleCli) {
|
|
877
|
+
if (!s.closed && s.bgTasks.size === 0) teardown(s)
|
|
878
|
+
return
|
|
879
|
+
}
|
|
880
|
+
if (!cancelled()) {
|
|
881
|
+
messages.pending.shift()
|
|
882
|
+
const err = error instanceof Error ? error : new Error(String(error))
|
|
883
|
+
broadcast(messages.workspaceId, {
|
|
884
|
+
kind: 'error',
|
|
885
|
+
sessionId: messages.sessionId,
|
|
886
|
+
content: err.message
|
|
887
|
+
})
|
|
888
|
+
message.reject(err)
|
|
889
|
+
message.complete()
|
|
890
|
+
}
|
|
891
|
+
} finally {
|
|
892
|
+
messages.dispatching = false
|
|
893
|
+
publishMessageActivity(messages)
|
|
894
|
+
if (s && !s.closed && s.activity === 'idle') armIdle(s)
|
|
895
|
+
void dispatchNextMessage(messages)
|
|
817
896
|
}
|
|
818
|
-
clearIdle(s)
|
|
819
|
-
s.input.push(content)
|
|
820
|
-
tapWire(s.workspaceId, 'send', { type: 'user', content })
|
|
821
|
-
debug(
|
|
822
|
-
`cc enqueue ws=${s.workspaceId} session=${s.sessionId} activity=${s.activity} text=${JSON.stringify(s.lastUserText)}`
|
|
823
|
-
)
|
|
824
897
|
}
|
|
825
898
|
|
|
826
|
-
//
|
|
827
|
-
// subprocess wedged and tearing it down. A hung subprocess never answers, and
|
|
828
|
-
// without this cap the whole interrupt path (and the user's only escape hatch
|
|
829
|
-
// from a stuck spinner) hangs with it.
|
|
899
|
+
// Bound both interrupt acknowledgement and turn completion.
|
|
830
900
|
const INTERRUPT_TIMEOUT_MS = 5_000
|
|
831
901
|
|
|
832
|
-
//
|
|
833
|
-
//
|
|
834
|
-
// is torn down instead — the next message respawns via resume.
|
|
902
|
+
// Cancel queued sends and interrupt the active turn. A failed or timed-out
|
|
903
|
+
// interrupt closes the process so the next send can resume in a fresh one.
|
|
835
904
|
export async function interruptCCSession(workspaceId: string, sessionId: string): Promise<void> {
|
|
836
|
-
const
|
|
837
|
-
if (!
|
|
905
|
+
const messages = messageQueues.get(liveKey(workspaceId, sessionId))
|
|
906
|
+
if (!messages) return
|
|
907
|
+
messages.stopping = true
|
|
908
|
+
cancelPendingMessages(messages, new Error('Message cancelled'))
|
|
909
|
+
const s = messages.live
|
|
910
|
+
if (!s) {
|
|
911
|
+
messages.stopping = false
|
|
912
|
+
publishMessageActivity(messages)
|
|
913
|
+
forgetEmptyQueue(messages)
|
|
914
|
+
broadcast(workspaceId, { kind: 'stopped', sessionId: messages.sessionId })
|
|
915
|
+
return
|
|
916
|
+
}
|
|
838
917
|
debug(`cc interrupt ws=${workspaceId} session=${sessionId} activity=${s.activity}`)
|
|
839
918
|
s.input.clear()
|
|
840
919
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
841
920
|
const timedOut = Symbol('interrupt-timeout')
|
|
921
|
+
const active = messages.active
|
|
842
922
|
try {
|
|
843
923
|
const outcome = await Promise.race([
|
|
844
|
-
|
|
924
|
+
(async () => {
|
|
925
|
+
await s.q.interrupt()
|
|
926
|
+
// Receipt and result are separate protocol messages. Bound both so a
|
|
927
|
+
// CLI that acknowledges Stop but never finishes cannot wedge the chat.
|
|
928
|
+
await active?.completed
|
|
929
|
+
})(),
|
|
845
930
|
new Promise(resolve => {
|
|
846
931
|
timer = setTimeout(() => resolve(timedOut), INTERRUPT_TIMEOUT_MS)
|
|
847
932
|
})
|
|
@@ -855,25 +940,49 @@ export async function interruptCCSession(workspaceId: string, sessionId: string)
|
|
|
855
940
|
teardown(s)
|
|
856
941
|
} finally {
|
|
857
942
|
clearTimeout(timer)
|
|
943
|
+
if (s.closed) {
|
|
944
|
+
active?.complete()
|
|
945
|
+
messages.active = null
|
|
946
|
+
}
|
|
947
|
+
messages.stopping = false
|
|
858
948
|
}
|
|
859
949
|
broadcast(s.workspaceId, { kind: 'stopped', sessionId: s.sessionId })
|
|
860
|
-
setActivity(s, 'idle')
|
|
950
|
+
if (!messages.active) setActivity(s, 'idle')
|
|
861
951
|
await markViewBuilderWaitingBySession(s.workspaceId, s.workspacePath, s.sessionId)
|
|
862
|
-
if (!s.closed) armIdle(s)
|
|
952
|
+
if (!s.closed && !messages.active) armIdle(s)
|
|
953
|
+
void dispatchNextMessage(messages)
|
|
863
954
|
}
|
|
864
955
|
|
|
865
|
-
//
|
|
866
|
-
//
|
|
867
|
-
// mid-turn reload isn't supported — busy sessions keep their snapshot until the
|
|
868
|
-
// turn ends (then idle-evict or get recreated on the next message via resume).
|
|
956
|
+
// Evict idle sessions so their next send picks up fresh workspace env. Busy
|
|
957
|
+
// sessions retain their environment until a later teardown.
|
|
869
958
|
export function restartWorkspaceSessions(workspacePath: string): void {
|
|
870
959
|
for (const s of [...sessions.values()]) {
|
|
871
|
-
if (
|
|
960
|
+
if (
|
|
961
|
+
s.workspacePath === workspacePath &&
|
|
962
|
+
s.activity === 'idle' &&
|
|
963
|
+
s.bgTasks.size === 0 &&
|
|
964
|
+
!s.messages.dispatching &&
|
|
965
|
+
!s.messages.active &&
|
|
966
|
+
s.messages.pending.length === 0
|
|
967
|
+
)
|
|
968
|
+
teardown(s)
|
|
872
969
|
}
|
|
873
970
|
}
|
|
874
971
|
|
|
875
|
-
//
|
|
876
|
-
//
|
|
972
|
+
// A CLI update may introduce models the current process cannot use. Mark it
|
|
973
|
+
// for replacement at the next safe dispatch boundary.
|
|
974
|
+
export function retireCCSessionsOnCliChange(): void {
|
|
975
|
+
for (const s of sessions.values()) s.staleCli = true
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
// Server shutdown must settle pending sends and close every subprocess.
|
|
877
979
|
export function killAllCCSessions(): void {
|
|
980
|
+
for (const messages of messageQueues.values()) {
|
|
981
|
+
messages.stopping = true
|
|
982
|
+
cancelPendingMessages(messages, new Error('Agent sessions stopped'))
|
|
983
|
+
messages.active?.complete()
|
|
984
|
+
messages.active = null
|
|
985
|
+
}
|
|
878
986
|
for (const s of [...sessions.values()]) teardown(s)
|
|
987
|
+
messageQueues.clear()
|
|
879
988
|
}
|