Skip to main content

agentmux_srv/server/agent_handlers/
instance.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4
5use std::sync::Arc;
6
7use crate::backend::rpc::engine::WshRpcEngine;
8use crate::backend::rpc_types::{
9    COMMAND_LIST_AGENT_INSTANCES, COMMAND_GET_AGENT_INSTANCE,
10    COMMAND_CREATE_AGENT_INSTANCE, COMMAND_UPDATE_AGENT_INSTANCE,
11    COMMAND_DELETE_AGENT_INSTANCE, COMMAND_AGENT_LAST_RUNTIME,
12    AgentLastRuntime, CommandAgentLastRuntimeData,
13    CommandListAgentInstancesData, CommandGetAgentInstanceData,
14    CommandCreateAgentInstanceData, CommandUpdateAgentInstanceData,
15    CommandDeleteAgentInstanceData, DeleteAgentInstanceResult,
16};
17use crate::backend::storage::store::{
18    AgentInstance, InstanceStatus,
19};
20
21use super::super::AppState;
22
23/// `listagentinstances`.
24//
25// `Option<_>` rather than the bare struct, which is what the previous
26// `unwrap_or_default()` was really buying: both encodings of "no
27// filter" -- the `{}` the stub sends and the `null` a client that
28// omits `data` sends -- still mean "no filter". What it no longer
29// buys is swallowing a MALFORMED filter: `{"status": 5}` used to
30// return the unfiltered list, which is the wrong answer to give
31// silently, so it is an error now.
32pub(crate) fn list_agent_instances(
33    state: &AppState,
34    cmd: Option<CommandListAgentInstancesData>,
35) -> Result<Vec<AgentInstance>, String> {
36    let cmd = cmd.unwrap_or_default();
37    let rows = state
38        .mstore
39        .instance_list(cmd.definition_id.as_deref(), cmd.status.as_deref())
40        .map_err(|e| format!("listagentinstances: {e}"))?;
41    Ok(rows)
42}
43
44/// `getagentinstance`.
45pub(crate) fn get_agent_instance(
46    state: &AppState,
47    cmd: CommandGetAgentInstanceData,
48) -> Result<AgentInstance, String> {
49    // Not-found stays an Err rather than becoming `Option<..>`:
50    // the stub types this `Promise<AgentInstance>`, so answering
51    // null would be a shape change, not just a typing change.
52    state
53        .mstore
54        .instance_get(&cmd.id)
55        .map_err(|e| format!("getagentinstance: {e}"))?
56        .ok_or_else(|| format!("getagentinstance: not found id={}", cmd.id))
57}
58
59/// Option E (PR 1 of 2) — stamp the agent-anchored
60/// session zone reference onto the block meta. Every
61/// block of this agent definition reads/writes through
62/// `agent:<defId>:current`. Continuation is now
63/// structural (same zone, different block) rather than
64/// parametric (per-block snapshot copy + --continue).
65fn stamp_session_zone(state: &AppState, inst: &AgentInstance) {
66    if !inst.block_id.is_empty()
67        && crate::backend::agent_session::is_valid_definition_id(&inst.definition_id)
68    {
69        let zone = crate::backend::agent_session::agent_current_zone(
70            &inst.definition_id,
71        );
72        let mut meta_update = crate::backend::obj::MetaMapType::new();
73        meta_update.insert(
74            "agent:sessionZone".to_string(),
75            serde_json::json!(zone),
76        );
77        let oref_str = format!("block:{}", inst.block_id);
78        if let Err(e) = crate::server::service::update_object_meta(
79            &state.mstore, &oref_str, &meta_update,
80        ) {
81            // Non-fatal — the instance row is the source
82            // of truth, the meta stamp is a frontend
83            // convenience. Log + continue so the launch
84            // doesn't abort mid-flow.
85            tracing::warn!(
86                block_id = %inst.block_id,
87                definition_id = %inst.definition_id,
88                error = %e,
89                "createagentinstance: failed to stamp agent:sessionZone"
90            );
91        }
92    }
93}
94
95/// `createagentinstance`.
96pub(crate) fn create_agent_instance(
97    state: &AppState,
98    cmd: CommandCreateAgentInstanceData,
99) -> Result<AgentInstance, String> {
100    let mstore = &state.mstore;
101    // A fresh launch of a template would put a pane on the template's own transcript
102    // zone (`agent:<templateId>:current`, shared by every launch of it), with a row
103    // of its own: two keys for one conversation. Templates are cloned into a user
104    // agent first (the picker does; `agent.open` refuses them). A continuation of an
105    // existing launch folds into its row and stays allowed.
106    if cmd.parent_instance_id.is_empty()
107        && mstore.agent_def_get(&cmd.definition_id).ok().flatten().is_some_and(|d| d.is_seeded == 1)
108    {
109        return Err(format!(
110            "TEMPLATE_NOT_LAUNCHABLE: '{}' is a template; create an agent from it first",
111            cmd.definition_id
112        ));
113    }
114    let now = agentmux_common::time::now_ms();
115    let inst = AgentInstance {
116        id: uuid::Uuid::new_v4().to_string(),
117        definition_id: cmd.definition_id,
118        parent_instance_id: cmd.parent_instance_id,
119        block_id: cmd.block_id,
120        session_id: String::new(),
121        status: InstanceStatus::Running.as_str().to_string(),
122        github_context: String::new(),
123        started_at: now,
124        ended_at: 0,
125        created_at: now,
126        // PR-F.3: the launch passes through its account +
127        // bundle picks. Empty string = blank
128        // singleton (no override; the resolver returns
129        // immediately on either "" or "blank").
130        identity_id: cmd.identity_id,
131        memory_id: cmd.memory_id,
132        // v8: named-agent continuation. instance_name +
133        // working_directory come from the launch
134        // overrides via CommandCreateAgentInstanceData
135        // (added in the same spec). Empty string for
136        // legacy/ambient launches.
137        instance_name: cmd.instance_name.clone(),
138        working_directory: cmd.working_directory.clone(),
139        display_hidden: false,
140    };
141    // The row the launch landed on — its id can differ from
142    // `inst.id` (a launch of a user agent folds into that agent's
143    // row; a continuation folds into the row it continues). The
144    // frontend stores THIS id as the block's `agentInstanceId`,
145    // so the response must carry the canonical row. The session
146    // zone stamp and the change event below deliberately keep
147    // using the REQUESTED definition id: Option E anchors the
148    // zone on the definition the launch started from
149    // (`agent:<defId>:current`), and the frontend subscribes to
150    // `agentinstances:changed:<defId>` by that same id.
151    let created = mstore
152        .instance_create(&inst)
153        .map_err(|e| format!("createagentinstance: {e}"))?;
154
155    stamp_session_zone(state, &inst);
156
157    state.broker.publish_event_for::<crate::backend::mps_events::AgentInstancesChanged>(&inst.definition_id, &(), vec![], 0);
158    Ok(created)
159}
160
161/// `updateagentinstance`.
162pub(crate) fn update_agent_instance(
163    state: &AppState,
164    cmd: CommandUpdateAgentInstanceData,
165) -> Result<AgentInstance, String> {
166    // Partial write — only the fields the command provided.
167    // No fetch-and-merge: this used to `instance_get` the full
168    // row to fill the unspecified fields, which was the sole
169    // production caller needing `instance_get`'s transient
170    // per-launch columns. The store builds a dynamic UPDATE
171    // and returns the post-write row (for the event scope +
172    // response) from the reload it already runs.
173    // SPEC_UPDATEAGENTINSTANCE_PARTIAL_UPDATE_2026_05_29.md.
174    let upd = crate::backend::storage::InstanceUpdate {
175        block_id: cmd.block_id,
176        session_id: cmd.session_id,
177        status: cmd.status,
178        github_context: cmd.github_context,
179        ended_at: cmd.ended_at,
180    };
181    let fresh = state
182        .mstore
183        .instance_update_partial(&cmd.id, &upd)
184        .map_err(|e| format!("updateagentinstance: {e}"))?
185        .ok_or_else(|| format!("updateagentinstance: not found id={}", cmd.id))?;
186    state.broker.publish_event_for::<crate::backend::mps_events::AgentInstancesChanged>(&fresh.definition_id, &(), vec![], 0);
187    Ok(fresh)
188}
189
190/// `agentlastruntime`.
191pub(crate) fn agent_last_runtime(
192    state: &AppState,
193    cmd: CommandAgentLastRuntimeData,
194) -> Result<AgentLastRuntime, String> {
195    if let Some(raw) = &cmd.runtime {
196        let normalized = crate::backend::storage::agents::normalize_last_runtime(raw)
197            .map_err(|e| format!("agentlastruntime: {e}"))?;
198        state
199            .mstore
200            .agent_last_runtime_set(&cmd.id, &normalized)
201            .map_err(|e| format!("agentlastruntime: {e}"))?;
202    }
203    let runtime = state
204        .mstore
205        .agent_last_runtime_get(&cmd.id)
206        .map_err(|e| format!("agentlastruntime: {e}"))?;
207    Ok(AgentLastRuntime { runtime })
208}
209
210/// `deleteagentinstance`.
211pub(crate) async fn delete_agent_instance(
212    state: &AppState,
213    cmd: CommandDeleteAgentInstanceData,
214) -> Result<DeleteAgentInstanceResult, String> {
215    // An agent's delete also deletes its parked block, and stops it (as `deleteagent` does).
216    crate::sagas::park_agents::delete_parked_blocks_of(state, &cmd.id).await;
217    // Read the row first so we can emit a scoped event after.
218    let definition_id = state
219        .mstore
220        .instance_get(&cmd.id)
221        .map_err(|e| format!("deleteagentinstance: {e}"))?
222        .map(|i| i.definition_id);
223    let deleted = state
224        .mstore
225        .instance_delete(&cmd.id)
226        .map_err(|e| format!("deleteagentinstance: {e}"))?;
227    // Unconditional, matching the sibling `deleteagent` handler
228    // (ReAgent P1 round 2 on PR #3262). Gating on `deleted`
229    // skipped the identity-store purge on a RETRY — where the
230    // local `db_agents` row is already gone but an earlier
231    // attempt's credential/identity-link cleanup failed — which
232    // is the "the confirm dialog promises a purge it doesn't
233    // deliver" bug, reproduced on this entry point. The purge
234    // is a no-op for an id with no rows, so there is nothing to
235    // gate on.
236    super::purge_identity_store_rows(&state.identity_store, &state.id_store, &cmd.id, "deleteagentinstance");
237    if let Some(def_id) = definition_id.filter(|_| deleted) {
238        state.broker.publish_event_for::<crate::backend::mps_events::AgentInstancesChanged>(&def_id, &(), vec![], 0);
239    }
240    Ok(DeleteAgentInstanceResult { deleted })
241}
242
243pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
244    let s = state.clone();
245    engine.register_typed(
246        COMMAND_LIST_AGENT_INSTANCES,
247        move |cmd: Option<CommandListAgentInstancesData>, _ctx| {
248            let s = s.clone();
249            async move { list_agent_instances(&s, cmd) }
250        },
251    );
252
253    let s = state.clone();
254    engine.register_typed(COMMAND_GET_AGENT_INSTANCE, move |cmd: CommandGetAgentInstanceData, _ctx| {
255        let s = s.clone();
256        async move { get_agent_instance(&s, cmd) }
257    });
258
259    let s = state.clone();
260    engine.register_typed(COMMAND_CREATE_AGENT_INSTANCE, move |cmd: CommandCreateAgentInstanceData, _ctx| {
261        let s = s.clone();
262        async move { create_agent_instance(&s, cmd) }
263    });
264
265    let s = state.clone();
266    engine.register_typed(COMMAND_UPDATE_AGENT_INSTANCE, move |cmd: CommandUpdateAgentInstanceData, _ctx| {
267        let s = s.clone();
268        async move { update_agent_instance(&s, cmd) }
269    });
270
271    let s = state.clone();
272    engine.register_typed(COMMAND_AGENT_LAST_RUNTIME, move |cmd: CommandAgentLastRuntimeData, _ctx| {
273        let s = s.clone();
274        async move { agent_last_runtime(&s, cmd) }
275    });
276
277    let s = state.clone();
278    engine.register_typed(COMMAND_DELETE_AGENT_INSTANCE, move |cmd: CommandDeleteAgentInstanceData, _ctx| {
279        let s = s.clone();
280        async move { delete_agent_instance(&s, cmd).await }
281    });
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use crate::backend::rpc::engine::WshRpcEngine;
288    use crate::server::tests::test_state;
289
290    /// `deleteagentinstance` is recorded in the engine's schema with its
291    /// exact type names — the property the RPC codegen plan depends on.
292    /// `DeleteAgentInstanceResult` didn't exist before this migration; the
293    /// The four CRUD commands record their request and response types, so the
294    /// whole of instance.rs is now in the registry rather than one command of
295    /// five. A command that falls back to `register_handler` disappears from
296    /// here rather than being recorded wrong.
297    #[tokio::test]
298    async fn register_typed_records_the_four_instance_crud_commands() {
299        let state = crate::server::tests::test_state();
300        let (engine, _rx) = WshRpcEngine::new();
301        register(&engine, &state);
302        let schema = engine.schema_json();
303        let rows = schema.as_array().unwrap();
304        let find = |cmd: &str| {
305            rows.iter()
306                .find(|r| r["command"] == cmd)
307                .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
308        };
309
310        for (cmd, resp) in [
311            (crate::backend::rpc_types::COMMAND_GET_AGENT_INSTANCE, "AgentInstance"),
312            (crate::backend::rpc_types::COMMAND_CREATE_AGENT_INSTANCE, "AgentInstance"),
313            (crate::backend::rpc_types::COMMAND_UPDATE_AGENT_INSTANCE, "AgentInstance"),
314        ] {
315            assert_eq!(find(cmd)["responseName"], resp, "{cmd} response");
316        }
317        let list = find(crate::backend::rpc_types::COMMAND_LIST_AGENT_INSTANCES);
318        let list_resp = list["responseName"].as_str().unwrap();
319        assert!(
320            list_resp.starts_with("alloc::vec::Vec<") && list_resp.contains("AgentInstance"),
321            "listagentinstances should answer Vec<AgentInstance>, got {list_resp:?}",
322        );
323    }
324
325    /// `listagentinstances` used to `unwrap_or_default()` its payload. That
326    /// bought two different things, and only one of them was wanted.
327    ///
328    /// Wanted: both encodings of "no filter" work -- the `{}` the stub sends
329    /// and the `null` a client that omits `data` sends. `Option<Req>` keeps
330    /// that.
331    ///
332    /// Not wanted: a MALFORMED filter silently became "no filter", so
333    /// `{"status": 5}` returned every row instead of erroring. Answering an
334    /// unfiltered list to a request whose filter failed to parse is the wrong
335    /// answer to give quietly, so it is an error now. This test pins both
336    /// halves so the change is visible rather than incidental.
337    #[tokio::test]
338    async fn listagentinstances_accepts_no_filter_but_rejects_a_malformed_one() {
339        let state = crate::server::tests::test_state();
340        let (engine, mut rx) = WshRpcEngine::new();
341        register(&engine, &state);
342
343        let call = |payload: serde_json::Value, reqid: &str| {
344            engine.handle_message(crate::backend::rpc_types::RpcMessage {
345                command: crate::backend::rpc_types::COMMAND_LIST_AGENT_INSTANCES.to_string(),
346                reqid: reqid.to_string(),
347                data: Some(payload),
348                ..Default::default()
349            });
350        };
351
352        for (i, payload) in [serde_json::json!({}), serde_json::Value::Null]
353            .into_iter()
354            .enumerate()
355        {
356            call(payload.clone(), &format!("ok-{i}"));
357            let resp = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
358                .await
359                .unwrap()
360                .unwrap();
361            assert!(
362                resp.error.is_empty(),
363                "{payload} means no filter and must be accepted, got {:?}",
364                resp.error,
365            );
366        }
367
368        call(serde_json::json!({ "status": 5 }), "bad");
369        let resp = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
370            .await
371            .unwrap()
372            .unwrap();
373        assert!(
374            !resp.error.is_empty(),
375            "a malformed filter must not be silently answered with the unfiltered list",
376        );
377    }
378
379    /// handler used to answer with an anonymous `json!({"deleted": ..})`.
380    #[tokio::test]
381    async fn register_typed_records_deleteagentinstance() {
382        let state = test_state();
383        let (engine, _rx) = WshRpcEngine::new();
384        register(&engine, &state);
385        let schema = engine.schema_json();
386        let rows = schema.as_array().unwrap();
387        let row = rows
388            .iter()
389            .find(|r| r["command"] == COMMAND_DELETE_AGENT_INSTANCE)
390            .expect("deleteagentinstance missing from the schema");
391        assert_eq!(row["requestName"], "CommandDeleteAgentInstanceData");
392        assert_eq!(row["responseName"], "DeleteAgentInstanceResult");
393        // The other four instance commands waited for the storage-level
394        // `AgentInstance` entity to be generated, which it now is, so they are
395        // present rather than absent. The property being asserted is the same
396        // one, with the opposite sign --
397        // `register_typed_records_the_four_instance_crud_commands` covers
398        // their exact types; here just assert instance.rs has nothing left
399        // outside the registry.
400        for cmd in [
401            COMMAND_LIST_AGENT_INSTANCES,
402            COMMAND_GET_AGENT_INSTANCE,
403            COMMAND_CREATE_AGENT_INSTANCE,
404            COMMAND_UPDATE_AGENT_INSTANCE,
405        ] {
406            assert!(
407                rows.iter().any(|r| r["command"] == cmd),
408                "{cmd} is migrated and must appear in the schema",
409            );
410        }
411    }
412
413    /// `createagentinstance` refuses a fresh launch of a template and records a user
414    /// agent's, so no pane is put on a template's shared transcript zone.
415    #[tokio::test]
416    async fn createagentinstance_refuses_a_fresh_template_launch() {
417        let state = crate::server::tests::test_state();
418        for (id, seeded) in [("tpl-x", 1), ("mine-x", 0)] {
419            let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
420                "id": id, "name": id, "icon": "wand-magic-sparkles", "provider": "claude",
421                "description": "", "created_at": 1, "is_seeded": seeded,
422            }))
423            .unwrap();
424            state.mstore.agent_def_insert(&mut def).unwrap();
425        }
426        let (engine, mut rx) = WshRpcEngine::new();
427        register(&engine, &state);
428        let mut call = |n: u32, id: &str| {
429            engine.handle_message(crate::backend::rpc_types::RpcMessage {
430                command: COMMAND_CREATE_AGENT_INSTANCE.to_string(),
431                reqid: format!("r{n}"),
432                data: Some(serde_json::json!({ "definition_id": id })),
433                ..Default::default()
434            });
435        };
436
437        call(1, "tpl-x");
438        let r = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()).await.unwrap().unwrap();
439        assert!(r.error.starts_with("TEMPLATE_NOT_LAUNCHABLE"), "{:?}", r.error);
440        assert!(state.mstore.instance_list(Some("tpl-x"), None).unwrap().is_empty(), "no row was made");
441
442        call(2, "mine-x");
443        let r = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()).await.unwrap().unwrap();
444        assert!(r.error.is_empty(), "{:?}", r.error);
445    }
446
447    /// `agentlastruntime`: read / replace / forget the remembered runtime, and
448    /// refuse a value the launch path could not read.
449    #[tokio::test]
450    async fn agentlastruntime_reads_replaces_forgets_and_refuses_bad_values() {
451        let state = crate::server::tests::test_state();
452        let mut agent: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
453            "id": "rt-agent",
454            "name": "rt-agent",
455            "icon": "wand-magic-sparkles",
456            "provider": "claude",
457            "description": "",
458            "created_at": 1,
459        }))
460        .unwrap();
461        state.mstore.agent_def_insert(&mut agent).unwrap();
462        let (engine, mut rx) = WshRpcEngine::new();
463        register(&engine, &state);
464
465        let mut n = 0;
466        let mut call = |payload: serde_json::Value| {
467            n += 1;
468            engine.handle_message(crate::backend::rpc_types::RpcMessage {
469                command: COMMAND_AGENT_LAST_RUNTIME.to_string(),
470                reqid: format!("r{n}"),
471                data: Some(payload),
472                ..Default::default()
473            });
474        };
475        macro_rules! next {
476            () => {
477                tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
478                    .await
479                    .unwrap()
480                    .unwrap()
481            };
482        }
483
484        call(serde_json::json!({ "id": "rt-agent" }));
485        let r = next!();
486        assert!(r.error.is_empty(), "{:?}", r.error);
487        assert_eq!(r.data.unwrap()["runtime"], "");
488
489        call(serde_json::json!({ "id": "rt-agent", "runtime": r#"{"model":"opus","effort":"high"}"# }));
490        let r = next!();
491        assert!(r.error.is_empty(), "{:?}", r.error);
492        assert_eq!(r.data.unwrap()["runtime"], r#"{"effort":"high","model":"opus"}"#);
493
494        call(serde_json::json!({ "id": "rt-agent", "runtime": r#"{"colour":"red"}"# }));
495        let r = next!();
496        assert!(!r.error.is_empty(), "an unknown key is refused");
497
498        call(serde_json::json!({ "id": "rt-agent" }));
499        assert_eq!(next!().data.unwrap()["runtime"], r#"{"effort":"high","model":"opus"}"#, "a refused write changes nothing");
500
501        call(serde_json::json!({ "id": "rt-agent", "runtime": "" }));
502        assert_eq!(next!().data.unwrap()["runtime"], "");
503    }
504
505    fn insert_agent(state: &AppState, id: &str, seeded: i64) {
506        let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
507            "id": id, "name": id, "icon": "wand-magic-sparkles", "provider": "claude",
508            "description": "", "created_at": 1, "is_seeded": seeded,
509        }))
510        .unwrap();
511        state.mstore.agent_def_insert(&mut def).unwrap();
512    }
513
514    fn launch(state: &AppState, def: &str) -> AgentInstance {
515        create_agent_instance(state, serde_json::from_value(serde_json::json!({ "definition_id": def })).unwrap()).unwrap()
516    }
517
518    /// The handlers run without the engine: a launch makes a running row that
519    /// `get` returns and `list` finds by definition, and `list` takes no filter.
520    #[tokio::test]
521    async fn create_get_and_list_agent_instances_agree() {
522        let state = test_state();
523        insert_agent(&state, "inst-a", 0);
524        insert_agent(&state, "inst-b", 0);
525        let a = launch(&state, "inst-a");
526        launch(&state, "inst-b");
527        assert_eq!(a.status, "running");
528
529        let got = get_agent_instance(&state, serde_json::from_value(serde_json::json!({ "id": a.id })).unwrap()).unwrap();
530        assert_eq!(got.definition_id, "inst-a");
531
532        let only_a = list_agent_instances(
533            &state,
534            Some(serde_json::from_value(serde_json::json!({ "definition_id": "inst-a" })).unwrap()),
535        )
536        .unwrap();
537        assert_eq!(only_a.len(), 1);
538        assert_eq!(list_agent_instances(&state, None).unwrap().len(), 2);
539    }
540
541    #[tokio::test]
542    async fn get_agent_instance_errors_when_the_row_is_missing() {
543        let state = test_state();
544        let err = get_agent_instance(&state, serde_json::from_value(serde_json::json!({ "id": "nope" })).unwrap()).unwrap_err();
545        assert_eq!(err, "getagentinstance: not found id=nope");
546    }
547
548    /// A template is refused unless the launch continues an existing one.
549    #[tokio::test]
550    async fn create_agent_instance_refuses_a_template_but_not_a_continuation() {
551        let state = test_state();
552        insert_agent(&state, "tpl-direct", 1);
553        let fresh = serde_json::from_value(serde_json::json!({ "definition_id": "tpl-direct" })).unwrap();
554        let err = create_agent_instance(&state, fresh).unwrap_err();
555        assert!(err.starts_with("TEMPLATE_NOT_LAUNCHABLE"), "{err}");
556        assert!(state.mstore.instance_list(Some("tpl-direct"), None).unwrap().is_empty());
557
558        let cont = serde_json::from_value(serde_json::json!({
559            "definition_id": "tpl-direct", "parent_instance_id": "earlier",
560        }))
561        .unwrap();
562        assert!(create_agent_instance(&state, cont).is_ok());
563    }
564
565    /// Only the fields the command names change; an unknown id is an error.
566    #[tokio::test]
567    async fn update_agent_instance_writes_only_the_named_fields() {
568        let state = test_state();
569        insert_agent(&state, "inst-u", 0);
570        let inst = launch(&state, "inst-u");
571
572        let upd = serde_json::from_value(serde_json::json!({ "id": inst.id, "status": "ended", "ended_at": 42 })).unwrap();
573        let fresh = update_agent_instance(&state, upd).unwrap();
574        assert_eq!(fresh.status, "ended");
575        assert_eq!(fresh.ended_at, 42);
576        assert_eq!(fresh.definition_id, "inst-u");
577
578        let missing = serde_json::from_value(serde_json::json!({ "id": "nope", "status": "ended" })).unwrap();
579        assert_eq!(update_agent_instance(&state, missing).unwrap_err(), "updateagentinstance: not found id=nope");
580    }
581
582    #[tokio::test]
583    async fn agent_last_runtime_handler_reads_replaces_and_refuses_bad_values() {
584        let state = test_state();
585        insert_agent(&state, "rt-direct", 0);
586        let call = |v: serde_json::Value| agent_last_runtime(&state, serde_json::from_value(v).unwrap());
587
588        assert_eq!(call(serde_json::json!({ "id": "rt-direct" })).unwrap().runtime, "");
589        let set = call(serde_json::json!({ "id": "rt-direct", "runtime": r#"{"model":"opus"}"# })).unwrap();
590        assert_eq!(set.runtime, r#"{"model":"opus"}"#);
591        assert!(call(serde_json::json!({ "id": "rt-direct", "runtime": r#"{"colour":"red"}"# })).is_err());
592        assert_eq!(call(serde_json::json!({ "id": "rt-direct" })).unwrap().runtime, r#"{"model":"opus"}"#);
593    }
594
595    /// Deleting reports whether a row went, and a second delete reports false
596    /// rather than erroring.
597    #[tokio::test]
598    async fn delete_agent_instance_reports_whether_a_row_was_removed() {
599        let state = test_state();
600        insert_agent(&state, "inst-d", 0);
601        let inst = launch(&state, "inst-d");
602        let del = |id: &str| delete_agent_instance(&state, serde_json::from_value(serde_json::json!({ "id": id })).unwrap());
603
604        assert!(del(&inst.id).await.unwrap().deleted);
605        assert!(state.mstore.instance_get(&inst.id).unwrap().is_none());
606        assert!(!del(&inst.id).await.unwrap().deleted);
607    }
608}