Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 71 additions & 14 deletions crates/dim-app-server/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -757,22 +757,79 @@ impl ProviderCatalog {
}
}

/// Image models whose listing may carry no media metadata: a relay or an
/// account catalog lists them under their bare id. The operations are the ones
/// the vendor documents for the id.
const KNOWN_IMAGE_MODELS: &[&str] = &[
"arcship-image",
"gpt-image-2",
"gpt-image-2.5-flare",
"gpt-image-2.5-sunburst",
"gpt-image-2.5-flare-2026-09-08",
"gpt-image-2.5-sunburst-2026-09-08",
"grok-imagine-image",
"grok-imagine-image-2.0",
"grok-imagine-image-quality",
];

impl ProviderModel {
/// The `<category>.<operation>` ids this entry declares for modality
/// (Modality §9.2), in their catalog order; `None` when it declares none.
/// The `<category>.<operation>` ids this entry serves for modality
/// (Modality §9.2, provider management §3.6); `None` when it serves none.
/// An explicit `modalityCapabilities` list is the answer, an empty one
/// included. Without one, an image model is recognized from its id or its
/// kind and output: `image.generate`, and `image.edit` when it also reads
/// images; `imageGeneration: false` recognizes nothing.
fn modality_operations(&self) -> Option<Vec<String>> {
let values = self
.metadata
.as_ref()?
.raw
.get("modalityCapabilities")?
.as_array()?;
let operations: Vec<String> = values
.iter()
.filter_map(serde_json::Value::as_str)
.map(str::to_owned)
.collect();
(!operations.is_empty()).then_some(operations)
let raw = self.metadata.as_ref().map(|metadata| &metadata.raw);
let field = |name: &str| raw.and_then(|raw| raw.get(name));
if let Some(values) = field("modalityCapabilities").and_then(serde_json::Value::as_array) {
let operations: Vec<String> = values
.iter()
.filter_map(serde_json::Value::as_str)
.map(str::to_owned)
.collect();
return (!operations.is_empty()).then_some(operations);
}
if field("imageGeneration") == Some(&serde_json::Value::Bool(false)) {
return None;
}
let modalities = |direction: &str| -> Vec<&str> {
field("modalities")
.and_then(|modalities| modalities.get(direction))
.and_then(serde_json::Value::as_array)
.map(|values| {
values
.iter()
.filter_map(serde_json::Value::as_str)
.collect()
})
.unwrap_or_default()
};
let (input, output) = (modalities("input"), modalities("output"));
let kind = field("type").and_then(serde_json::Value::as_str);
let operations: &[&str] = if KNOWN_IMAGE_MODELS.contains(&self.id.as_str())
|| self
.id
.split(['.', '/', '_', '-'])
.any(|part| part == "seedream")
{
&["image.generate", "image.edit"]
} else if kind == Some("image-edit") {
&["image.edit"]
} else if field("imageGeneration") == Some(&serde_json::Value::Bool(true))
|| (matches!(kind, Some("image" | "image-generation"))
&& (output.is_empty() || output.contains(&"image")))
|| (output == ["image"])
{
if input.contains(&"image") {
&["image.generate", "image.edit"]
} else {
&["image.generate"]
}
} else {
return None;
};
Some(operations.iter().map(|id| (*id).to_owned()).collect())
}

/// The realtime transport this entry's `metadata.raw.realtime` declares,
Expand Down
42 changes: 39 additions & 3 deletions crates/dim-app-server/tests/provider_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2195,7 +2195,33 @@ async fn selectable_modality_models_carry_declared_operations_without_chat_rules
"modality",
1000,
);
mine.models = vec![media(), both, model("modality-text", 1000)];
let undeclared = |id: &str, raw: Value| -> ModelEntry {
serde_json::from_value(json!({
"modelId": id, "displayName": id, "status": "active",
"capabilities":{"modalities":["image"],"toolCalling":false,"streaming":true,
"structuredOutput":false,"vision":false,"audio":false,"reasoning":false},
"metadata":{"raw": raw}
}))
.unwrap()
};
mine.models = vec![
media(),
both,
model("modality-text", 1000),
undeclared("arcship-image", json!({})),
undeclared(
"modality-inferred",
json!({"type":"image","modalities":{"input":["text","image"],"output":["image"]}}),
),
undeclared(
"modality-none",
json!({"type":"image-generation","modalityCapabilities":[]}),
),
undeclared(
"modality-off",
json!({"type":"image-generation","imageGeneration":false}),
),
];
let created = provider.create(mine, &cancel).await.unwrap();
let mut off = input(
OFF,
Expand Down Expand Up @@ -2254,8 +2280,18 @@ async fn selectable_modality_models_carry_declared_operations_without_chat_rules
"modality-both".to_owned(),
vec!["image.generate".to_owned()]
),
(
"arcship-image".to_owned(),
vec!["image.generate".to_owned(), "image.edit".to_owned()]
),
(
"modality-inferred".to_owned(),
vec!["image.generate".to_owned(), "image.edit".to_owned()]
),
],
"a model that declares no operation is omitted"
"a model that declares no operation is omitted; a known or image-output model \
without a declaration is recognized, and an explicit empty list or \
`imageGeneration: false` recognizes nothing"
);
assert!(
!modality
Expand Down Expand Up @@ -2390,7 +2426,7 @@ async fn selectable_modality_models_carry_declared_operations_without_chat_rules
.collect();
assert_eq!(
listed,
["modality-media"],
["modality-media", "arcship-image", "modality-inferred"],
"a disabled model leaves the modality options"
);
let cancelled = CancellationToken::new();
Expand Down
2 changes: 1 addition & 1 deletion crates/dim-modality-aimux/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ dim-app-server.workspace = true
http = "1"
serde_json.workspace = true
sha2 = "0.10.9"
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util", "time"] }
tokio-tungstenite.workspace = true
tokio-util.workspace = true
uuid.workspace = true
Expand Down
3 changes: 3 additions & 0 deletions crates/dim-modality-aimux/src/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ fn milliseconds(seconds: f64) -> i64 {
pub fn image_options(job: &Job, vendor: &Vendor) -> Result<ImageCallOptions, AdapterError> {
let params = &job.params;
let mut options = ImageCallOptions::new(text(params, "prompt").unwrap_or_default());
if vendor.catalog == "dimcode-api-oauth" {
options.max_retries = Some(0);
}
if text(params, "prompt").is_none() {
options.prompt = None;
}
Expand Down
12 changes: 12 additions & 0 deletions crates/dim-modality-aimux/src/vendor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,18 @@ pub static VENDORS: &[Vendor] = &[
base: Base::AsIs,
format: None,
},
// The Dim account relay speaks the OpenAI Image API on its `/v1` base:
// JSON `/images/generations` and multipart `/images/edits`, with the
// account's bearer. The relay names the model, so a model the package
// does not know keeps edit.
Vendor {
catalog: "dimcode-api-oauth",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This row makes the Dim account relay reach the image call path, but image_options (crates/dim-modality-aimux/src/job.rs:51-92) leaves ImageCallOptions.max_retries at its default. The locked aimux-core 0.6.1 (src/image_model.rs:269-281, src/retry.rs:12,41,87) retries twice, and the locked aimux-provider-utils 0.6.1 (src/post_to_api.rs:82,128-141) marks the 30-second exchange timeout retryable. A POST the relay received but did not finish within 30 seconds is sent again, so one click can bill up to three generations. Set options.max_retries = Some(0) for this path, or wait for an aimux idempotency or timeout policy; add a scripted transport test that receives the POST and times out, asserting one send.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f6cf5ca. crates/dim-modality-aimux/src/job.rs:54-56 sets max_retries = Some(0) for the dimcode-api-oauth catalog, and the_dim_account_relay_does_not_retry_a_timed_out_post (crates/dim-modality-aimux/tests/adapter.rs:630-659) accepts one POST, stalls the response through the exchange timeout, and asserts exactly one request. The test passes locally at ac2c7f6.

aimux: "openai",
options: "openai",
kinds: kinds(true, false, false, false),
base: Base::AsIs,
format: Some("outputFormat"),
},
// The catalog's `/speechtotext/v1` is the prefix the package appends.
Vendor {
catalog: "rev-ai",
Expand Down
115 changes: 109 additions & 6 deletions crates/dim-modality-aimux/tests/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,16 @@ fn unauthorized() -> Reply {
}
}

#[derive(Clone)]
struct Scripted {
struct Scripted<F> {
requests: Arc<Mutex<Vec<Recorded>>>,
respond: Arc<dyn Fn(&Recorded) -> Reply + Send + Sync>,
respond: F,
}

#[async_trait]
impl Fetch for Scripted {
impl<F> Fetch for Scripted<F>
where
F: Fn(&Recorded) -> Option<Reply> + Send + Sync + 'static,
{
async fn fetch(&self, request: FetchRequest) -> Result<FetchResponse, FetchError> {
let recorded = Recorded {
method: request.method.clone(),
Expand All @@ -97,7 +99,9 @@ impl Fetch for Scripted {
body: request.body.to_vec(),
};
self.requests.lock().unwrap().push(recorded.clone());
let reply = (self.respond)(&recorded);
let Some(reply) = (self.respond)(&recorded) else {
return std::future::pending().await;
};
Ok(FetchResponse::from_bytes(
reply.status,
HeaderMap::new(),
Expand All @@ -114,7 +118,7 @@ fn scripted(
let requests = Arc::new(Mutex::new(Vec::new()));
let fetch: FetchFunction = Arc::new(Scripted {
requests: requests.clone(),
respond: Arc::new(respond),
respond: move |request: &Recorded| Some(respond(request)),
});
(Arc::new(MediaAdapter::scripted(fetch)), requests)
}
Expand Down Expand Up @@ -622,6 +626,105 @@ fn path_is_inside(path: &Path, dir: &Path) -> bool {
path.strip_prefix(dir).is_ok()
}

#[tokio::test(start_paused = true)]
async fn the_dim_account_relay_does_not_retry_a_timed_out_post() {
let requests = Arc::new(Mutex::new(Vec::new()));
let adapter = Arc::new(MediaAdapter::scripted(Arc::new(Scripted {
requests: requests.clone(),
respond: |_: &Recorded| None,
})));
let dir = work_dir("relay-timeout");
let error = run(
&adapter,
job(
"dimcode-api-oauth",
"arcship-image",
"image",
"generate",
json!({"prompt": "a red circle"}),
Vec::new(),
&dir,
),
"https://relay.example.test/v1",
"arcship-image",
)
.await
.unwrap_err();
assert_eq!(error.code, AdapterErrorCode::ProviderError);
let requests = requests.lock().unwrap();
assert_eq!(requests.len(), 1, "{requests:?}");
assert_eq!(requests[0].method, Method::POST);
assert!(requests[0].url.ends_with("/images/generations"));
std::fs::remove_dir_all(dir).unwrap();
}

/// The Dim account relay speaks the OpenAI Image API on its `/v1` base with
/// the account's bearer, for a model id only the relay knows (#1887).
#[tokio::test]
async fn the_dim_account_relay_serves_its_image_models_over_the_openai_image_api() {
let relay = ModelId {
provider_id: "dimcode-api-oauth".into(),
model_id: "arcship-image".into(),
};
let names: Vec<String> = MediaAdapter::new()
.operations(&relay)
.into_iter()
.map(|operation| format!("{}.{}", operation.category, operation.operation))
.collect();
assert_eq!(names, ["realtime.voice", "image.generate", "image.edit"]);

let dir = work_dir("relay");
let (adapter, requests) =
scripted(|_| ok_json(json!({"created": 1, "data": [{"b64_json": base64(PNG_HEADER)}]})));
let base = "https://relay.example.test/v1";
let generate = job(
"dimcode-api-oauth",
"arcship-image",
"image",
"generate",
json!({"prompt": "a red circle"}),
Vec::new(),
&dir,
);
let output = run(&adapter, generate, base, "arcship-image")
.await
.unwrap();
assert_eq!(output.files[0].media_type, "image/png");
let reference = input(&dir, "in.png", "image/png", PNG_HEADER);
let edit = job(
"dimcode-api-oauth",
"arcship-image",
"image",
"edit",
json!({"prompt": "add a hat"}),
vec![reference],
&dir,
);
run(&adapter, edit, base, "arcship-image").await.unwrap();

let requests = requests.lock().unwrap();
let urls: Vec<&str> = requests
.iter()
.map(|request| request.url.as_str())
.collect();
assert_eq!(
urls,
[
"https://relay.example.test/v1/images/generations",
"https://relay.example.test/v1/images/edits"
]
);
for request in requests.iter() {
assert_eq!(
request.header("authorization"),
Some("Bearer test-credential")
);
}
let body: Value = serde_json::from_slice(&requests[0].body).unwrap();
assert_eq!(body["model"], "arcship-image");
assert_eq!(body["prompt"], "a red circle");
}

/// One (row, operation) pair with the exact request it must send.
struct Case {
provider: &'static str,
Expand Down
36 changes: 34 additions & 2 deletions crates/dim-modality-aimux/tests/flows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -943,15 +943,47 @@ async fn capabilities_show_the_mapped_provider_and_refuse_a_created_one() {
)
.await;
assert_ok(&reply);
let capabilities = client.rpc("modality.capabilities", json!({})).await;
let unserved = json!({"providerId": created, "modelId": "custom-image", "available": false,
"reason": {"dimension": "adapter", "detail": "No available adapter serves the model"}});
let generate = |snapshot: &Value| -> Value {
snapshot["result"]["categories"]
.as_array()
.unwrap()
.iter()
.find(|category| category["category"] == "image")
.unwrap()["operations"]
.as_array()
.unwrap()
.iter()
.find(|operation| operation["operation"] == "generate")
.unwrap()
.clone()
};
assert!(
generate(&capabilities)["options"]
.as_array()
.unwrap()
.contains(&unserved),
"the created provider's model is listed with the adapter reason: {capabilities}"
);
let revision = capabilities["result"]["revision"].as_str().unwrap();
let refused = client
let configured = client
.rpc(
"modality.configure",
json!({"expectedRevision": revision, "category": "image", "operation": "generate",
"model": model(created, "custom-image")}),
)
.await;
assert_eq!(app_error(&refused), "modality_invalid_selection");
assert_ok(&configured);
assert_eq!(generate(&configured)["default"], unserved);
let refused = client
.rpc(
"modality.task.submit",
json!({"category": "image", "operation": "generate", "params": {"prompt": "a cat"}, "files": []}),
)
.await;
assert_eq!(app_error(&refused), "default_unavailable", "{refused}");
assert!(
refused["error"]["message"]
.as_str()
Expand Down
Loading