Skip to content

Commit d6b1a72

Browse files
authored
Add provider-aware chat model picker
Add provider-rich model choices to the chat composer, route provider-qualified selections through sessions.patch, preserve clear-to-default behavior, serialize pending model patches before sends, and dedupe legacy cached raw model IDs for reconnect fallback selection.
1 parent 556e7da commit d6b1a72

13 files changed

Lines changed: 1235 additions & 46 deletions
Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
namespace OpenClaw.Chat;
2+
3+
using OpenClaw.Shared;
4+
5+
/// <summary>
6+
/// Provider-rich description of a model exposed by <c>models.list</c>.
7+
/// </summary>
8+
/// <param name="Id">Wire model id (e.g. <c>claude-opus-4.8</c>).</param>
9+
/// <param name="DisplayName">Human-friendly label (falls back to <paramref name="Id"/>).</param>
10+
/// <param name="Provider">Owning provider (e.g. <c>OpenAI</c>, <c>Anthropic</c>), when known.</param>
11+
/// <param name="ContextWindow">Context-window size in tokens, when known.</param>
12+
/// <param name="IsConfigured">True when the provider is configured on the gateway.</param>
13+
/// <param name="IsAvailable">
14+
/// True when the model can be selected right now. When false the picker shows it
15+
/// but does not let the user switch to it.
16+
/// </param>
17+
/// <param name="RequiresAuth">
18+
/// True when the model's provider still needs authentication/credentials before
19+
/// the model is usable.
20+
/// </param>
21+
/// <param name="IsDefault">True when the gateway marks this model as the default.</param>
22+
public sealed record ChatModelChoice(
23+
string Id,
24+
string DisplayName,
25+
string? Provider = null,
26+
int? ContextWindow = null,
27+
bool IsConfigured = true,
28+
bool IsAvailable = true,
29+
bool RequiresAuth = false,
30+
bool IsDefault = false)
31+
{
32+
/// <summary>
33+
/// Provider-qualified identity used for picker tags and <c>sessions.patch</c>
34+
/// model refs. Already-qualified ids are preserved.
35+
/// </summary>
36+
public string SelectionId => BuildSelectionId(Id, Provider);
37+
38+
/// <summary>
39+
/// True when the user may switch the session to this model. Auth-needed
40+
/// models remain selectable (selecting one routes the user toward the
41+
/// gateway's provider-auth flow); only explicitly unavailable models are
42+
/// blocked.
43+
/// </summary>
44+
public bool IsSelectable => IsAvailable;
45+
46+
/// <summary>
47+
/// Maps gateway models into ordered, selection-deduplicated picker entries.
48+
/// </summary>
49+
public static IReadOnlyList<ChatModelChoice> FromModelsList(ModelsListInfo? info)
50+
{
51+
if (info?.Models is not { Count: > 0 }) return Array.Empty<ChatModelChoice>();
52+
53+
var seen = new HashSet<string>(StringComparer.Ordinal);
54+
var list = new List<ChatModelChoice>(info.Models.Count);
55+
foreach (var m in info.Models)
56+
{
57+
if (m is null || string.IsNullOrEmpty(m.Id)) continue;
58+
// Hide explicitly unconfigured models unless the gateway reports an
59+
// auth flow for them; auth-needed rows are useful picker actions.
60+
if (m.HasConfiguredFlag && !m.IsConfigured && !m.RequiresAuth) continue;
61+
var choice = new ChatModelChoice(
62+
Id: m.Id,
63+
DisplayName: m.DisplayName,
64+
Provider: m.Provider,
65+
ContextWindow: m.ContextWindow,
66+
IsConfigured: m.IsConfigured,
67+
IsAvailable: m.IsAvailable,
68+
RequiresAuth: m.RequiresAuth,
69+
IsDefault: m.IsDefault);
70+
if (!seen.Add(choice.SelectionId)) continue;
71+
list.Add(choice);
72+
}
73+
return list;
74+
}
75+
76+
public bool MatchesModel(string? modelId, string? provider = null)
77+
{
78+
var normalizedModel = NormalizeId(modelId);
79+
if (normalizedModel is null) return false;
80+
81+
if (NormalizeId(provider) is { } normalizedProvider)
82+
{
83+
var providerQualified = BuildSelectionId(normalizedModel, normalizedProvider);
84+
return string.Equals(SelectionId, providerQualified, StringComparison.Ordinal)
85+
|| (string.Equals(Id, normalizedModel, StringComparison.Ordinal)
86+
&& string.Equals(NormalizeId(Provider), normalizedProvider, StringComparison.OrdinalIgnoreCase));
87+
}
88+
89+
return string.Equals(Id, normalizedModel, StringComparison.Ordinal)
90+
|| string.Equals(SelectionId, normalizedModel, StringComparison.Ordinal);
91+
}
92+
93+
public static string BuildSelectionId(string modelId, string? provider)
94+
{
95+
var normalizedModel = NormalizeId(modelId) ?? string.Empty;
96+
if (normalizedModel.Length == 0) return string.Empty;
97+
var normalizedProvider = NormalizeId(provider);
98+
if (normalizedProvider is null) return normalizedModel;
99+
100+
var prefix = normalizedProvider + "/";
101+
return normalizedModel.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
102+
? normalizedModel
103+
: $"{normalizedProvider}/{normalizedModel}";
104+
}
105+
106+
public static string? ResolveSelectionId(
107+
string? modelId,
108+
string? provider,
109+
IReadOnlyList<ChatModelChoice> choices)
110+
{
111+
var normalizedModel = NormalizeId(modelId);
112+
if (normalizedModel is null) return null;
113+
114+
if (NormalizeId(provider) is not null)
115+
{
116+
var match = choices.FirstOrDefault(c => c.MatchesModel(normalizedModel, provider));
117+
if (match is not null) return match.SelectionId;
118+
119+
var bareRawMatches = choices
120+
.Where(c => c.Id == normalizedModel && string.IsNullOrWhiteSpace(c.Provider))
121+
.Take(2)
122+
.ToArray();
123+
if (bareRawMatches.Length == 1) return bareRawMatches[0].SelectionId;
124+
125+
return BuildSelectionId(normalizedModel, provider);
126+
}
127+
128+
var direct = choices.FirstOrDefault(c => c.SelectionId == normalizedModel);
129+
if (direct is not null) return direct.SelectionId;
130+
131+
var rawMatches = choices.Where(c => c.Id == normalizedModel).Take(2).ToArray();
132+
return rawMatches.Length == 1 ? rawMatches[0].SelectionId : normalizedModel;
133+
}
134+
135+
private static string? NormalizeId(string? value)
136+
{
137+
var trimmed = value?.Trim();
138+
return string.IsNullOrEmpty(trimmed) ? null : trimmed;
139+
}
140+
}
141+
142+
/// <summary>
143+
/// Pure label/formatting helpers for the model picker. Lives in
144+
/// <c>OpenClaw.Chat</c> (no WinUI dependency) so the display strings can be unit
145+
/// tested without spinning up the composer.
146+
/// </summary>
147+
public static class ChatModelLabels
148+
{
149+
/// <summary>
150+
/// True when <paramref name="modelId"/> represents "no explicit model
151+
/// override" — i.e. the session is tracking the gateway/agent default.
152+
/// This predicate only describes the <em>current</em> state, derived from an
153+
/// empty/absent session model. Clearing an override (so a session tracks the
154+
/// default again) is performed via the tri-state <c>SessionPatch.Clear</c>
155+
/// (explicit JSON null), not by sending an empty model string.
156+
/// </summary>
157+
public static bool IsTrackingDefault(string? modelId) => string.IsNullOrEmpty(modelId);
158+
159+
/// <summary>
160+
/// Compact token-count label: 272000 → "272K", 1_048_576 → "1M",
161+
/// 200000 → "200K". Falls back to the raw number for small values.
162+
/// </summary>
163+
public static string FormatContextWindow(int contextWindow)
164+
{
165+
if (contextWindow <= 0) return string.Empty;
166+
if (contextWindow >= 1_000_000)
167+
{
168+
var millions = contextWindow / 1_000_000.0;
169+
// Trim a trailing ".0" so 2_000_000 → "2M" not "2.0M".
170+
return millions == Math.Floor(millions)
171+
? $"{(int)millions}M"
172+
: $"{millions:0.#}M";
173+
}
174+
if (contextWindow >= 1_000)
175+
{
176+
var thousands = contextWindow / 1_000.0;
177+
return thousands == Math.Floor(thousands)
178+
? $"{(int)thousands}K"
179+
: $"{thousands:0.#}K";
180+
}
181+
return contextWindow.ToString();
182+
}
183+
184+
/// <summary>
185+
/// Builds the secondary metadata segment ("OpenAI · 272K") from provider and
186+
/// context window, or an empty string when neither is known.
187+
/// </summary>
188+
public static string BuildMetaSegment(ChatModelChoice choice)
189+
{
190+
var hasProvider = !string.IsNullOrWhiteSpace(choice.Provider);
191+
var ctx = choice.ContextWindow is { } cw ? FormatContextWindow(cw) : string.Empty;
192+
var hasCtx = ctx.Length > 0;
193+
194+
if (hasProvider && hasCtx) return $"{choice.Provider} · {ctx}";
195+
if (hasProvider) return choice.Provider!;
196+
if (hasCtx) return ctx;
197+
return string.Empty;
198+
}
199+
200+
/// <summary>
201+
/// Trailing state marker for a model: "default", "auth needed",
202+
/// "unavailable", or empty. Unavailable takes precedence over auth-needed,
203+
/// which takes precedence over default. Only explicit gateway signals drive
204+
/// the markers — a missing <see cref="ChatModelChoice.IsConfigured"/> flag is
205+
/// not treated as "auth needed" because the gateway's <c>configured</c> view
206+
/// often omits the field entirely.
207+
/// </summary>
208+
public static string BuildStateMarker(ChatModelChoice choice)
209+
{
210+
if (!choice.IsAvailable) return "unavailable";
211+
if (choice.RequiresAuth) return "auth needed";
212+
if (choice.IsDefault) return "default";
213+
return string.Empty;
214+
}
215+
216+
/// <summary>
217+
/// Full menu/combo label, e.g. "Claude Opus 4.8 · Anthropic · 200K · default".
218+
/// State marker is appended last so default/auth-needed/unavailable reads at
219+
/// the end of the row.
220+
/// </summary>
221+
public static string BuildMenuLabel(ChatModelChoice choice)
222+
{
223+
var label = choice.DisplayName;
224+
var meta = BuildMetaSegment(choice);
225+
if (meta.Length > 0) label = $"{label} · {meta}";
226+
var marker = BuildStateMarker(choice);
227+
if (marker.Length > 0) label = $"{label} · {marker}";
228+
return label;
229+
}
230+
231+
/// <summary>
232+
/// Label for the "clear to gateway default" picker entry. Selecting it clears
233+
/// the session's explicit model override (the gateway falls back to its
234+
/// agent/default model). When the default model is known its name is
235+
/// surfaced, e.g. "Default (Claude Opus 4.8)".
236+
/// </summary>
237+
public static string BuildDefaultEntryLabel(ChatModelChoice? defaultChoice)
238+
{
239+
if (defaultChoice is not null && !string.IsNullOrWhiteSpace(defaultChoice.DisplayName))
240+
return $"Default ({defaultChoice.DisplayName})";
241+
return "Default";
242+
}
243+
}

‎src/OpenClaw.Chat/ChatModels.cs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ public record ChatThread
105105
public string? Compute { get; init; }
106106
public string? ProfileName { get; init; }
107107
public string? Model { get; init; }
108+
public string? ModelProvider { get; init; }
108109
public string? ThinkingLevel { get; init; }
109110
public long InputTokens { get; init; }
110111
public long OutputTokens { get; init; }
@@ -190,7 +191,8 @@ public record ChatDataSnapshot(
190191
string? DefaultThreadId,
191192
string? ConnectionStatus,
192193
string[] AvailableModels,
193-
ChatComposeTarget ComposeTarget);
194+
ChatComposeTarget ComposeTarget,
195+
IReadOnlyList<ChatModelChoice>? ModelChoices = null);
194196

195197
/// <summary>
196198
/// Describes where the UI may send the next chat message. Distinct from
@@ -257,6 +259,13 @@ Task SendMessageAsync(string threadId, string message, CancellationToken cancell
257259
Task SetThreadSuspendedAsync(string threadId, bool suspended, CancellationToken cancellationToken = default);
258260
Task DeleteThreadAsync(string threadId, CancellationToken cancellationToken = default);
259261
Task SetModelAsync(string threadId, string model, CancellationToken cancellationToken = default);
262+
/// <summary>
263+
/// Clears the session's explicit model override so it tracks the gateway's
264+
/// agent/default model again. Providers that don't support clearing leave
265+
/// the default no-op. Distinct from <see cref="SetModelAsync"/> because the
266+
/// gateway models this as an explicit null (tri-state), not an empty string.
267+
/// </summary>
268+
Task ClearModelAsync(string threadId, CancellationToken cancellationToken = default) => Task.CompletedTask;
260269
Task SetThinkingLevelAsync(string threadId, string thinkingLevel, CancellationToken cancellationToken = default);
261270
Task SetPermissionModeAsync(string threadId, bool allowAll, CancellationToken cancellationToken = default);
262271
Task RespondToPermissionAsync(string threadId, string requestId, string action, CancellationToken cancellationToken = default);

‎src/OpenClaw.Shared/Models.cs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2075,9 +2075,28 @@ public class ModelInfo
20752075
public string? Name { get; set; }
20762076
public string? Provider { get; set; }
20772077
public int? ContextWindow { get; set; }
2078+
2079+
/// <summary>True when the model's provider is configured on the gateway.</summary>
20782080
public bool IsConfigured { get; set; }
20792081
public bool HasConfiguredFlag { get; set; }
20802082

2083+
/// <summary>True when the gateway marks this model as the default choice.</summary>
2084+
public bool IsDefault { get; set; }
2085+
2086+
/// <summary>
2087+
/// True when the model can be selected/used right now. Defaults to
2088+
/// <c>true</c> so models lists from gateways that don't report availability
2089+
/// are treated as usable. The gateway may report <c>available:false</c> or
2090+
/// <c>unavailable:true</c> to mark a model as not selectable.
2091+
/// </summary>
2092+
public bool IsAvailable { get; set; } = true;
2093+
2094+
/// <summary>
2095+
/// True when the model's provider needs authentication/credentials before
2096+
/// it can be used (e.g. an API key has not been configured yet).
2097+
/// </summary>
2098+
public bool RequiresAuth { get; set; }
2099+
20812100
public string DisplayName => Name ?? Id;
20822101
}
20832102

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4126,16 +4126,27 @@ private void ParseModelsList(JsonElement payload)
41264126
{
41274127
foreach (var item in modelsArray.EnumerateArray())
41284128
{
4129+
if (item.ValueKind != JsonValueKind.Object) continue;
4130+
4131+
// Read readiness flags defensively; older gateways may omit
4132+
// them, and the UI only uses them for labels/selectability.
41294133
var hasConfiguredFlag = item.TryGetProperty("configured", out var cfg)
41304134
&& (cfg.ValueKind == JsonValueKind.True || cfg.ValueKind == JsonValueKind.False);
4135+
bool available = true;
4136+
if (TryReadBool(item, out var av, "available")) available = av;
4137+
else if (TryReadBool(item, out var un, "unavailable")) available = !un;
4138+
41314139
var model = new ModelInfo
41324140
{
41334141
Id = item.TryGetProperty("id", out var id) ? id.GetString() ?? "" : "",
41344142
Name = item.TryGetProperty("name", out var name) ? name.GetString() : null,
41354143
Provider = item.TryGetProperty("provider", out var prov) ? prov.GetString() : null,
41364144
ContextWindow = item.TryGetProperty("contextWindow", out var cw) && cw.ValueKind == JsonValueKind.Number ? cw.GetInt32() : null,
41374145
IsConfigured = hasConfiguredFlag && cfg.ValueKind == JsonValueKind.True,
4138-
HasConfiguredFlag = hasConfiguredFlag
4146+
HasConfiguredFlag = hasConfiguredFlag,
4147+
IsDefault = ReadBool(item, "default", "isDefault"),
4148+
IsAvailable = available,
4149+
RequiresAuth = ReadBool(item, "requiresAuth", "authRequired", "needsAuth", "authNeeded")
41394150
};
41404151
if (!string.IsNullOrEmpty(model.Id))
41414152
info.Models.Add(model);
@@ -4149,6 +4160,25 @@ private void ParseModelsList(JsonElement payload)
41494160
}
41504161
}
41514162

4163+
// Reads the first present boolean property among <paramref name="keys"/>.
4164+
// Returns false when none are present (or are non-boolean).
4165+
private static bool ReadBool(JsonElement obj, params string[] keys) =>
4166+
TryReadBool(obj, out var value, keys) && value;
4167+
4168+
private static bool TryReadBool(JsonElement obj, out bool value, params string[] keys)
4169+
{
4170+
foreach (var key in keys)
4171+
{
4172+
if (obj.TryGetProperty(key, out var prop))
4173+
{
4174+
if (prop.ValueKind == JsonValueKind.True) { value = true; return true; }
4175+
if (prop.ValueKind == JsonValueKind.False) { value = false; return true; }
4176+
}
4177+
}
4178+
value = false;
4179+
return false;
4180+
}
4181+
41524182
private void ParseNodePairList(JsonElement payload)
41534183
{
41544184
try

‎src/OpenClaw.Tray.WinUI/Chat/IChatGatewayBridge.cs‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,13 @@ public interface IChatGatewayBridge : IDisposable
3737
Task SendChatMessageAsync(string message, string? sessionKey, string? sessionId, IReadOnlyList<ChatAttachment>? attachments = null);
3838
Task<ChatSendResult> SendChatMessageForRunAsync(string message, string? sessionKey, string? sessionId, IReadOnlyList<ChatAttachment>? attachments = null);
3939
Task PatchSessionModelAsync(string sessionKey, string model);
40+
/// <summary>
41+
/// Clears the session's model override (tri-state <c>sessions.patch</c> with
42+
/// an explicit JSON null), reverting the session to the gateway/agent
43+
/// default. Distinct from <see cref="PatchSessionModelAsync"/>, which sets a
44+
/// concrete model.
45+
/// </summary>
46+
Task ClearSessionModelAsync(string sessionKey);
4047
Task PatchSessionThinkingLevelAsync(string sessionKey, string thinkingLevel);
4148
Task<ChatHistoryInfo> RequestChatHistoryAsync(string? sessionKey);
4249
Task SendChatAbortAsync(string runId, string? sessionKey = null);
@@ -160,10 +167,13 @@ public Task<ChatSendResult> SendChatMessageForRunAsync(string message, string? s
160167
_client.SendChatMessageForRunAsync(message, sessionKey, sessionId, attachments);
161168

162169
public Task PatchSessionModelAsync(string sessionKey, string model) =>
163-
_client.PatchSessionAsync(sessionKey, model: model);
170+
_client.PatchSessionAsync(sessionKey, new SessionPatch { Model = model });
171+
172+
public Task ClearSessionModelAsync(string sessionKey) =>
173+
_client.PatchSessionAsync(sessionKey, new SessionPatch { Model = SessionPatch.Clear });
164174

165175
public Task PatchSessionThinkingLevelAsync(string sessionKey, string thinkingLevel) =>
166-
_client.PatchSessionAsync(sessionKey, thinkingLevel: thinkingLevel);
176+
_client.PatchSessionAsync(sessionKey, new SessionPatch { ThinkingLevel = thinkingLevel });
167177

168178
public Task<ChatHistoryInfo> RequestChatHistoryAsync(string? sessionKey) =>
169179
_client.RequestChatHistoryAsync(sessionKey);

0 commit comments

Comments
 (0)