Skip to main content

mj_controller/server/
actions.rs

1use super::*;
2
3/// The complete set of operations a phone may ask the controller to perform.
4/// Secret/config editing is intentionally not representable here, and the one
5/// destructive variant, `ForceClose`, is not representable on the wire: it is
6/// `#[serde(skip)]` so only in-process callers such as the HTTP API can build
7/// it.
8#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
9#[serde(tag = "action", rename_all = "kebab-case", deny_unknown_fields)]
10pub enum ControllerAction {
11    New {
12        #[serde(default)]
13        create_managed_worktree: Option<bool>,
14        /// None follows the global `[subagents] enabled` setting.
15        #[serde(default)]
16        mjolnir_subagents: Option<bool>,
17        /// Which workspace the session belongs to. Optional on the wire so a
18        /// viewer cached from before workspaces reached the phone still parses,
19        /// but a controller holding more than one workspace refuses an empty
20        /// one rather than guessing.
21        #[serde(default)]
22        workspace_id: String,
23        profile_id: String,
24        bundle_id: String,
25        target_id: String,
26        /// Absent means "derive it", which is what the terminal does.
27        #[serde(default)]
28        title: Option<String>,
29        #[serde(default)]
30        project_directory: Option<PathBuf>,
31        /// The repositories the person was shown as having uncommitted changes
32        /// and chose to launch over anyway.
33        ///
34        /// This names them rather than being a bare yes, so an acknowledgement
35        /// cannot be replayed against a set the person never saw: if a
36        /// different repository has gone dirty since the preflight, the launch
37        /// stops and asks again.
38        #[serde(default, skip_serializing_if = "Vec::is_empty")]
39        dirty_ack: Vec<String>,
40    },
41    /// Give a session a new title. The terminal calls this a rename.
42    Rename {
43        session_id: String,
44        title: String,
45    },
46    /// Stop the turn the agent is working on, leaving the session alive. This
47    /// is not `Cancel`, which stops a provision, resume or stop.
48    CancelTurn {
49        session_id: String,
50    },
51    /// Change one setting the harness advertised, such as `model` or `effort`.
52    SetConfig {
53        session_id: String,
54        key: String,
55        value: String,
56    },
57    /// Turn plan mode on or off. The harness decides how, which is why this
58    /// carries an intent rather than a mode id.
59    SetPlanMode {
60        session_id: String,
61        active: bool,
62    },
63    RefreshQuota {
64        profile_id: String,
65    },
66    RefreshCapacity {
67        target_id: String,
68    },
69    Resume {
70        session_id: String,
71        workspace_id: String,
72        profile_id: String,
73        target_id: String,
74        queue: ResumeQueueDisposition,
75        /// A failed Move supplies the settings recorded before source
76        /// teardown. Ordinary Resume requests leave these absent and retain
77        /// the historical inheritance behavior.
78        #[serde(default)]
79        additional_mounts: Option<Vec<AdditionalMount>>,
80        #[serde(default)]
81        resource_allocation: Option<SessionResourceAllocation>,
82    },
83    /// Confirm a previously prepared move. Preparation is a separate
84    /// authenticated request so changing the destination cannot be smuggled
85    /// into a confirmation from an older browser form.
86    Move {
87        request: MoveSessionRequest,
88    },
89    Open {
90        session_id: String,
91    },
92    Prompt {
93        session_id: String,
94        text: String,
95        /// Images to send with the prompt. The controller turns each one into
96        /// the ACP image content block its prompt path already speaks.
97        #[serde(default, skip_serializing_if = "Vec::is_empty")]
98        images: Vec<ViewerPromptImage>,
99    },
100    RunShell {
101        session_id: String,
102        command: String,
103    },
104    CancelShell {
105        session_id: String,
106        shell_command_id: String,
107    },
108    Close {
109        session_id: String,
110    },
111    /// Destroy a session without checkpointing it: the live target is torn
112    /// down, the recovery archive is removed, and sub-agent children are
113    /// destroyed first. This is irreversible.
114    ///
115    /// Skipped by serde on purpose. The browser viewer posts this enum to
116    /// `/actions`, so a wire request must never be able to name this variant;
117    /// it is reachable only from the HTTP API, which builds it in process.
118    #[serde(skip)]
119    ForceClose {
120        session_id: String,
121    },
122    Cancel {
123        session_id: String,
124    },
125    /// Review the turn this session just finished.
126    StartReview {
127        session_id: String,
128    },
129    /// Forward the findings, dismiss them, or cancel the open review.
130    ResolveReview {
131        session_id: String,
132        /// `forward`, `dismiss`, or `cancel`.
133        resolution: String,
134    },
135    RemoveQueuedPrompt {
136        session_id: String,
137        queue_id: String,
138    },
139    /// Answer one of the session's pending form questions.
140    RespondElicitation {
141        session_id: String,
142        elicitation_id: String,
143        response: ElicitationResponse,
144    },
145}
146
147/// One image a phone attached to a prompt. Legacy callers may send inline
148/// base64 data; the server normalizes it into an attachment before dispatch.
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(deny_unknown_fields)]
151pub struct ViewerPromptImage {
152    /// Legacy inline image bytes. New browser uploads and normalized inline
153    /// prompts carry an attachment reference and leave this empty.
154    #[serde(default)]
155    pub data_base64: String,
156    pub mime_type: String,
157    pub width: u32,
158    pub height: u32,
159    /// Session-scoped, immutable image bytes. The worker resolves this just
160    /// before dispatch, keeping browser actions and durable commands small.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub attachment: Option<AttachmentRef>,
163}
164
165/// The controller's answer to one phone action.
166///
167/// The answer means "accepted", not "finished": provisioning, resume and close
168/// run for minutes, and a phone on a mobile network drops a request held open
169/// that long. How the action then goes travels in snapshots — session state,
170/// queued prompts, transcripts, and `has_error`.
171///
172/// Only the outcome crosses this boundary. The controller's own failure text
173/// names profile homes, project paths and SSH hosts, so it stays on the
174/// controller and the phone gets a fixed message it can act on.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub enum ActionOutcome {
177    /// Admitted and now running; watch the snapshot for what happens next.
178    ///
179    /// A `new` action carries the published session id, which is the only way
180    /// its caller learns what it just created.
181    Accepted { session_id: Option<String> },
182    /// The controller already runs as many phone actions as it allows.
183    Busy,
184    /// This session already has an operation running.
185    SessionBusy,
186    /// A cancel found no operation to cancel.
187    NotCancellable,
188    /// The controller could not start the action at all.
189    Failed,
190}
191
192impl ActionOutcome {
193    /// Admitted, with no session id to report.
194    pub const fn accepted() -> Self {
195        Self::Accepted { session_id: None }
196    }
197
198    /// The published session id, when this outcome carries one.
199    pub fn session_id(&self) -> Option<&str> {
200        match self {
201            Self::Accepted { session_id } => session_id.as_deref(),
202            _ => None,
203        }
204    }
205
206    /// The reply an outcome owes the phone, or `None` when it was accepted.
207    pub(super) fn rejection(&self) -> Option<ApiError> {
208        match self {
209            Self::Accepted { .. } => None,
210            Self::Busy => Some(ApiError::new(
211                StatusCode::TOO_MANY_REQUESTS,
212                "the controller is at its concurrent action limit; retry shortly",
213            )),
214            Self::SessionBusy => Some(ApiError::new(
215                StatusCode::CONFLICT,
216                "another operation is already running for this session",
217            )),
218            Self::NotCancellable => Some(ApiError::new(
219                StatusCode::CONFLICT,
220                "the session has no cancellable operation",
221            )),
222            Self::Failed => Some(ApiError::new(
223                StatusCode::INTERNAL_SERVER_ERROR,
224                "the controller could not start this action",
225            )),
226        }
227    }
228}
229
230#[derive(Debug)]
231pub struct ControllerRequest {
232    pub action: ControllerAction,
233    pub reply: tokio::sync::oneshot::Sender<ActionOutcome>,
234}
235
236/// A phone request to create or reuse a quick project bundle. This has its
237/// own channel because bundle creation returns a durable id and must publish a
238/// config snapshot before the HTTP request can succeed; [`ControllerAction`]
239/// intentionally carries only action admission outcomes.
240#[derive(Debug)]
241pub struct BundleRequest {
242    pub source: String,
243    pub reply: tokio::sync::oneshot::Sender<Result<String, BundleFailure>>,
244}
245
246/// Safe failure classes for bundle creation. Detailed controller errors stay
247/// in daemon logs; a browser only needs to know whether to fix its source or
248/// report a server-side failure.
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250pub enum BundleFailure {
251    InvalidSource,
252    Controller,
253}
254
255/// A phone acknowledging how far it has read a conversation.
256///
257/// This deliberately is not a `ControllerAction`: the viewer posts it after
258/// every conversation fetch, and a fetch follows every revision. Routing it
259/// through the action pipeline made each receipt reload the controller, bump
260/// the revision and broadcast a snapshot, which triggered the next fetch, so
261/// viewer and controller never went quiet; it also consumed the session's
262/// single action slot, intermittently rejecting real actions. A receipt
263/// therefore travels on its own channel and only persists one cursor field.
264/// A phone asking whether a session it is about to create would launch
265/// cleanly, and which network sources it will use first.
266///
267/// This is not a `ControllerAction`: it starts nothing, it takes no session
268/// slot, and it must answer before the person has decided anything. It also
269/// needs the controller, because resolving a local repository's configured
270/// remotes is a fact about the disk rather than about the projection.
271///
272/// Resume preflights share this channel, and so the concurrency cap on it,
273/// because they do the same kind of work on the same disk.
274#[derive(Debug)]
275pub enum PreflightRequest {
276    New(NewPreflightRequest),
277    Resume(ResumePreflightRequest),
278}
279
280#[derive(Debug)]
281pub struct NewPreflightRequest {
282    pub bundle_id: String,
283    pub target_id: String,
284    pub project_directory: Option<PathBuf>,
285    pub remote_repairs: Vec<mj_core::local_git::LocalRemoteRepair>,
286    pub reply: tokio::sync::oneshot::Sender<Result<PreflightNew, PreflightFailure>>,
287}
288
289/// A resume preflight for one stopped session and one destination target. It
290/// travels on the same channel and under the same concurrency cap as the
291/// new-session preflight because it does the same kind of work: reading a
292/// working tree and asking a remote about itself.
293#[derive(Debug)]
294pub struct ResumePreflightRequest {
295    pub session_id: String,
296    pub target_id: String,
297    pub reply: tokio::sync::oneshot::Sender<Result<PreflightResume, PreflightFailure>>,
298}
299
300/// What a resume preflight found.
301///
302/// `Ready` covers every resume that changes nothing about where repository
303/// content comes from. `ConvertingRawCheckout` means this resume moves a
304/// local checkout into an isolated workspace, and carries the preview the
305/// person has to confirm. `Unavailable` reports why the conversion cannot be
306/// planned, in the plan's own words, because that message says what to do
307/// about it (add a remote, commit a submodule) and the browser has no other
308/// way to learn it.
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310#[serde(tag = "kind", rename_all = "kebab-case")]
311pub enum PreflightResume {
312    Ready,
313    ConvertingRawCheckout {
314        preview: Box<mj_core::state::RawConversionPreview>,
315    },
316    Unavailable {
317        detail: String,
318    },
319}
320
321/// A move preparation is intentionally separate from action admission. It
322/// performs read-only compatibility checks and returns the exact fingerprint
323/// the later confirmation must echo; it never interrupts the source session.
324#[derive(Debug)]
325pub struct MovePreparationRequest {
326    pub selection: MoveSelection,
327    pub reply: tokio::sync::oneshot::Sender<Result<MovePreparation, String>>,
328}
329
330/// A preflight can fail because the requested bare directory is unusable, an
331/// isolated repository lacks a usable network source, or the controller-side
332/// check itself could not complete. The HTTP surface keeps those outcomes
333/// distinct without carrying filesystem, Git, or SSH details to the phone.
334#[derive(Debug)]
335pub enum PreflightFailure {
336    Validation,
337    /// A configured isolated-session repository cannot be used as a network
338    /// source. The detail is safe for the phone and tells the person how to
339    /// choose the supported raw-local path instead.
340    InvalidRepository(String),
341    Controller(String),
342}
343
344/// One configured repository's network clone and publication destinations.
345/// URLs have already been passed through the shared display sanitizer before
346/// they reach a phone.
347#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
348#[serde(deny_unknown_fields)]
349pub struct PreflightRepository {
350    pub id: String,
351    pub fetch_url: String,
352    pub default_branch: String,
353    pub push_urls: Vec<String>,
354}
355
356/// What a preflight found. Isolated sessions expose their complete network
357/// source plan so the person can review it before creation. Raw-local targets
358/// leave the plan empty because they use the selected checkout directly;
359/// isolated targets set `local_changes_excluded` to make the copy boundary
360/// explicit.
361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362#[serde(deny_unknown_fields)]
363pub struct PreflightNew {
364    #[serde(default, skip_serializing_if = "Option::is_none")]
365    pub project_directory: Option<PathBuf>,
366    #[serde(default)]
367    pub managed_worktree: mj_core::state::ManagedWorktreeOptions,
368    #[serde(default)]
369    pub remote_repairs: Vec<mj_core::local_git::LocalRemoteRepair>,
370    #[serde(default)]
371    pub dirty_repositories: Vec<String>,
372    #[serde(default)]
373    pub remote_repositories: Vec<PreflightRepository>,
374    pub local_changes_excluded: bool,
375}
376
377/// What a phone asks about, or stores against, its own identity.
378///
379/// These travel on their own channel rather than as actions, for the reason a
380/// read receipt does: they are frequent, they start nothing, and routing them
381/// through the action pipeline would consume the session's single action slot
382/// and reload the controller on every keystroke.
383#[derive(Debug)]
384pub enum ClientStateRequest {
385    Read {
386        client_id: String,
387        session_id: String,
388        reply: tokio::sync::oneshot::Sender<Result<ViewerClientState, String>>,
389    },
390    SaveDraft {
391        client_id: String,
392        session_id: String,
393        draft: String,
394        reply: tokio::sync::oneshot::Sender<Result<(), String>>,
395    },
396    MarkWorkspaceRead {
397        client_id: String,
398        workspace_id: String,
399        reply: tokio::sync::oneshot::Sender<Result<(), String>>,
400    },
401    History {
402        session_id: String,
403        query: String,
404        scope: String,
405        reply: tokio::sync::oneshot::Sender<Result<ViewerPromptHistory, String>>,
406    },
407}
408
409#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
410#[serde(deny_unknown_fields)]
411pub struct ViewerClientState {
412    pub draft: String,
413    pub through_event_ordinal: u64,
414}
415
416#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
417#[serde(deny_unknown_fields)]
418pub struct ViewerPromptHistory {
419    pub entries: Vec<String>,
420    /// Whether the search stopped before it ran out of history, so a phone can
421    /// say the answer is partial rather than presenting it as complete.
422    pub truncated: bool,
423}
424
425#[derive(Debug)]
426pub struct ReadReceiptRequest {
427    pub client_id: String,
428    pub session_id: String,
429    pub through: u64,
430    pub reply: tokio::sync::oneshot::Sender<Result<(), String>>,
431}
432
433/// A phone request to stop one currently projected background task.
434///
435/// This is intentionally not a [`ControllerAction`]. The request is already
436/// validated against the current operational snapshot by the HTTP handler,
437/// then the controller resolves the live session handle and waits for the
438/// provider acknowledgement in a supervised task.
439#[derive(Debug)]
440pub struct BackgroundTaskStopRequest {
441    pub session_id: String,
442    pub background_task_id: String,
443    pub reply: tokio::sync::oneshot::Sender<Result<(), BackgroundTaskStopFailure>>,
444}
445
446#[derive(Debug, Clone, Copy, PartialEq, Eq)]
447pub enum BackgroundTaskStopFailure {
448    /// The session manager could not resolve the live session handle.
449    SessionUnavailable,
450    /// The provider or relay rejected the stop request.
451    Provider,
452    /// The stop task itself failed before reaching the provider.
453    Internal,
454}