Skip to content
Open
3 changes: 3 additions & 0 deletions src/OpenClaw.Shared/Models.cs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,9 @@ public SessionInfo Clone()
}

public string Key { get; set; } = "";
/// <summary>True when an authoritative Gateway session roster returned this row, so the
/// Gateway has it stored. Rows tracked only from job or tool events remain false.</summary>
public bool IsGatewayListed { get; set; }
public bool IsMain { get; set; }
internal bool IsMainResolved { get; set; }
public string? Label { get; set; }
Expand Down
9 changes: 9 additions & 0 deletions src/OpenClaw.Shared/OpenClawGatewayClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ public partial class OpenClawGatewayClient : WebSocketClientBase, IOperatorGatew
private readonly object _sessionRefreshLock = new();
private CancellationTokenSource? _sessionRefreshCancellation;
private bool _sessionRefreshDirty;
// Chat compose waits for a roster from the current connection, so one rejected sessions.list gets one retry.
private int _sessionsListErrorRetried;
private static TimeSpan SessionRefreshWindow => TimeSpan.FromMilliseconds(
int.TryParse(Environment.GetEnvironmentVariable("OPENCLAW_SESSION_REFRESH_WINDOW_MS"), out var milliseconds)
&& milliseconds is > 0 and <= 5000 ? milliseconds : DefaultSessionRefreshWindowMs);
Expand Down Expand Up @@ -330,13 +332,15 @@ protected override Task OnConnectedAsync()
Volatile.Write(ref _startupRejection, null);
CancelScheduledSessionRefresh();
CancelScheduledAgentRosterRefresh();
Volatile.Write(ref _sessionsListErrorRetried, 0);
lock (_sessionsLock)
{
_sessionThinkingDefaults = null;
foreach (var session in _sessions.Values)
{
session.ThinkingContext = null;
session.ThinkingDefaults = null;
session.IsGatewayListed = false;
}
}
_handshakeChallengeGate.Reset(CurrentConnectionGeneration);
Expand Down Expand Up @@ -3681,6 +3685,9 @@ private void HandleRequestError(
}
}

if (method == "sessions.list" && Interlocked.Exchange(ref _sessionsListErrorRetried, 1) == 0)
ScheduleSessionRefresh(sourceConnectionGeneration);

if (IsSessionCommandMethod(method))
{
SessionCommandCompleted?.Invoke(this, new SessionCommandResult
Expand Down Expand Up @@ -5871,6 +5878,7 @@ private void ParseSessions(JsonElement sessions)
}

session.ThinkingDefaults = _sessionThinkingDefaults;
session.IsGatewayListed = true;
_sessions[sessionKey] = session;
incomingKeys.Add(sessionKey);
}
Expand Down Expand Up @@ -5916,6 +5924,7 @@ private void ParseSessions(JsonElement sessions)

PopulateSessionFromObject(session, item, authoritativeSessionList: true);
session.ThinkingDefaults = _sessionThinkingDefaults;
session.IsGatewayListed = true;

_sessions[session.Key] = session;
return session.Key;
Expand Down
6 changes: 5 additions & 1 deletion src/OpenClaw.Tray.WinUI/Chat/ChatConversationState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,11 @@ internal ChatSessionsTransition ApplySessions(
{
if (_disposed)
return new(BuildSnapshotLocked(context), [], []);
_presentation.ReplaceSessions(sessions);
// A roster snapshot holds only rows the current connection listed (possibly none);
// a job or tool event republish adds unlisted rows and must not count as a roster.
_presentation.ReplaceSessions(
sessions,
receivedFromGateway: sessions.All(session => session.IsGatewayListed));
var currentSessions = _presentation.SessionSnapshot();
List<ChatHistoryCommitToken>? carriedPromptReads = null;
foreach (var (threadId, previousSessionId, sessionId) in _history.SeedSessionIds(currentSessions))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ internal sealed record ChatLifecycleCommandResult(
ChatLifecycleCommandKind Command,
bool Succeeded,
string? NewSessionKey = null,
string? Error = null);
string? Error = null,
bool OutcomeUncertain = false);

internal static class ChatLifecycleCommandParser
{
Expand Down Expand Up @@ -117,7 +118,8 @@ private async Task<ChatLifecycleCommandResult> CreateSessionAsync(
return new ChatLifecycleCommandResult(
ChatLifecycleCommandKind.New,
Succeeded: false,
Error: result.Error ?? "The gateway could not create a new session.");
Error: result.Error ?? "The gateway could not create a new session.",
OutcomeUncertain: result.OutcomeUncertain);
}

var newSessionKey = result.Key.Trim();
Expand Down
93 changes: 92 additions & 1 deletion src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,8 @@ internal Task<bool> EnqueueCompactCommandAsync(
internal async Task<ChatLifecycleCommandResult> ExecuteLifecycleCommandAsync(
string threadId,
ChatLifecycleCommandKind command,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default,
Func<ChatLifecycleCommandResult, bool>? claimFailure = null)
{
ChatLifecycleCommandResult result;
try
Expand All @@ -515,6 +516,9 @@ internal async Task<ChatLifecycleCommandResult> ExecuteLifecycleCommandAsync(

if (!result.Succeeded)
{
// A caller that recovers from this failure owns it; do not report it in the thread.
if (claimFailure?.Invoke(result) == true)
return result;
// For /new timeouts, refresh the session list so the user can see
// whether a session was created server-side before the response
// arrived. The sessions.create protocol has no idempotency key,
Expand Down Expand Up @@ -1149,6 +1153,85 @@ await TrackSessionOptionPatchAsync(threadId,
internal Task<SessionCreateResult> CreateDefaultDraftSessionAsync(CancellationToken cancellationToken) =>
CreateDraftSessionAsync(agentId: null, cancellationToken);

/// <summary>
/// Creates the floating claw's independent quick-chat conversation. When the compose
/// target is a stored session it runs <c>/new</c> from it, keeping the parent link and
/// command hooks. A fresh Gateway advertises its main key before storing that session
/// and rejects it as an unknown parent, so an unstored target gets a root session (#2316).
/// Storage is read only from rows an authoritative Gateway roster returned: snapshot threads
/// can include a local placeholder, and job or tool events add tracked rows for unstored keys.
/// A stored parent beyond the roster's row limit gets a root session without hooks, not a failure.
/// If the Gateway still definitively rejects the parent as unknown (for example after it was
/// removed), quick chat retries once as a root session; timeouts and other errors do not retry.
/// A create that may have committed (timeout or lost connection) throws
/// <see cref="QuickChatCreationUncertainException"/> so the caller keeps the attempt and
/// reconciles it from a refreshed roster instead of sending a duplicate create.
/// </summary>
internal async Task<string> CreateQuickChatSessionAsync(
ChatDataSnapshot snapshot, CancellationToken cancellationToken)
{
var target = snapshot.ComposeTarget;
var knownKeys = (_bridge.GetSessionList() ?? [])
.Where(s => s.IsGatewayListed).Select(s => s.Key).ToHashSet(StringComparer.Ordinal);
if (target.SessionKey is { Length: > 0 } parentKey && knownKeys.Contains(parentKey))
{
var lifecycle = await ExecuteLifecycleCommandAsync(
parentKey, ChatLifecycleCommandKind.New, claimFailure: IsUnknownParentRejection)
.ConfigureAwait(false);
if (lifecycle.Succeeded && lifecycle.NewSessionKey is { } newSessionKey)
return newSessionKey;
if (lifecycle.OutcomeUncertain)
throw await QuickChatCreationUncertainAsync(knownKeys, parentKey).ConfigureAwait(false);
if (!IsUnknownParentRejection(lifecycle))
throw new InvalidOperationException("The dedicated conversation could not be created.");
}

// Null lets the Gateway choose its default agent; the projector's "main" is a fallback.
var result = await CreateDraftSessionAsync(agentId: null, cancellationToken).ConfigureAwait(false);
if (result.OutcomeUncertain)
throw await QuickChatCreationUncertainAsync(knownKeys, target.SessionKey).ConfigureAwait(false);
if (!result.IsSupported || !result.Ok || string.IsNullOrWhiteSpace(result.Key))
throw new InvalidOperationException(result.Error ?? "The dedicated conversation could not be created.");
await RefreshQuickChatSessionsAsync().ConfigureAwait(false);
return result.Key.Trim();
}

/// <summary>
/// Adopts an uncertain quick-chat create once the roster lists exactly one new session that is
/// a root or a child of the quick-chat parent. Otherwise refreshes the roster and returns null.
/// </summary>
internal string? TryReconcileQuickChatSession(QuickChatCreationUncertainException pending)
{
var created = (_bridge.GetSessionList() ?? [])
.Where(s => s.IsGatewayListed && !pending.KnownSessionKeys.Contains(s.Key) &&
(s.ParentSessionKey is null ||
string.Equals(s.ParentSessionKey, pending.ParentSessionKey, StringComparison.Ordinal)))
.Select(s => s.Key).Distinct(StringComparer.Ordinal).ToArray();
if (created.Length == 1)
return created[0];
_ = RefreshQuickChatSessionsAsync();
return null;
}

private async Task<QuickChatCreationUncertainException> QuickChatCreationUncertainAsync(
HashSet<string> knownKeys, string? parentKey)
{
if (parentKey is { Length: > 0 })
knownKeys.Add(parentKey);
await RefreshQuickChatSessionsAsync().ConfigureAwait(false);
return new QuickChatCreationUncertainException(knownKeys, parentKey);
}

private async Task RefreshQuickChatSessionsAsync()
{
try { await _bridge.RequestSessionsAsync().ConfigureAwait(false); }
catch (Exception ex) { Logger.Warn($"ChatDataProvider: quick chat session list refresh failed: {ex.Message}"); }
}

private static bool IsUnknownParentRejection(ChatLifecycleCommandResult result) =>
!result.Succeeded && !result.OutcomeUncertain &&
result.Error?.Contains("unknown parent session", StringComparison.OrdinalIgnoreCase) == true;

internal Task<SessionCreateResult> CreateDraftSessionAsync(
string? agentId, CancellationToken cancellationToken)
{
Expand Down Expand Up @@ -2955,3 +3038,11 @@ private void RaiseNotification(ChatProviderNotification notification)
}

}

/// <summary>A quick-chat create may have committed; reconcile it from the roster before creating another.</summary>
internal sealed class QuickChatCreationUncertainException(IReadOnlySet<string> knownSessionKeys, string? parentSessionKey)
: InvalidOperationException("The Gateway may have created the quick chat before the request failed.")
{
internal IReadOnlySet<string> KnownSessionKeys { get; } = knownSessionKeys;
internal string? ParentSessionKey { get; } = parentSessionKey;
}
27 changes: 21 additions & 6 deletions src/OpenClaw.Tray.WinUI/Presentation/DesktopCompanionState.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using OpenClawTray.Chat;
using OpenClawTray.Services;

namespace OpenClawTray.Presentation;
Expand Down Expand Up @@ -59,13 +60,24 @@ internal sealed class DesktopCompanionChatSessions
{
private readonly Dictionary<string, Task<string>> _sessions = new(StringComparer.Ordinal);

public Task<string> GetOrCreateAsync(string gatewayId, Func<Task<string>> create, CancellationToken ct)
/// <summary>
/// An uncertain create stays retained, so reopening never creates again; it is replaced only when
/// <paramref name="reconcile"/> finds the session it may have created.
/// </summary>
public Task<string> GetOrCreateAsync(string gatewayId, Func<Task<string>> create, CancellationToken ct,
Func<QuickChatCreationUncertainException, string?>? reconcile = null)
{
ct.ThrowIfCancellationRequested();
Task<string> session;
Task<string>? session;
lock (_sessions)
{
if (!_sessions.TryGetValue(gatewayId, out session!))
if (_sessions.TryGetValue(gatewayId, out session))
{
if (session.Exception?.InnerException is QuickChatCreationUncertainException pending &&
reconcile?.Invoke(pending) is { Length: > 0 } adopted)
_sessions[gatewayId] = session = Task.FromResult(adopted);
}
else
{
var completion = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
session = completion.Task;
Expand Down Expand Up @@ -93,9 +105,12 @@ private async Task CreateAsync(string gatewayId, Func<Task<string>> create, Task
}
catch (Exception ex)
{
lock (_sessions)
if (_sessions.TryGetValue(gatewayId, out var current) && ReferenceEquals(current, completion.Task))
_sessions.Remove(gatewayId);
if (ex is not QuickChatCreationUncertainException)
{
lock (_sessions)
if (_sessions.TryGetValue(gatewayId, out var current) && ReferenceEquals(current, completion.Task))
_sessions.Remove(gatewayId);
}
completion.TrySetException(ex);
}
}
Expand Down
12 changes: 4 additions & 8 deletions src/OpenClaw.Tray.WinUI/Windows/DesktopCompanionChatHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,10 @@ public async Task OpenAsync(string? replyKey = null)
var sessionKey = replyKey;
if (dedicated)
{
sessionKey = await _dedicatedSessions.GetOrCreateAsync(gatewayId, async () =>
{
var result = await provider.ExecuteLifecycleCommandAsync(
snapshot.ComposeTarget.SessionKey!, ChatLifecycleCommandKind.New);
if (!result.Succeeded || result.NewSessionKey is null)
throw new InvalidOperationException("The dedicated conversation could not be created.");
return result.NewSessionKey;
}, ct);
// The shared create outlives this window: its token cancels only this caller's wait.
sessionKey = await _dedicatedSessions.GetOrCreateAsync(gatewayId,
() => provider.CreateQuickChatSessionAsync(snapshot, CancellationToken.None), ct,
provider.TryReconcileQuickChatSession);
}
ct.ThrowIfCancellationRequested();
if (!ReferenceEquals(provider, _app?.ChatProvider) || gatewayId != _app?.Registry?.GetActive()?.Id)
Expand Down
12 changes: 12 additions & 0 deletions tests/OpenClaw.Shared.Tests/GatewayProtocolModelsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,18 @@ public void ParseSessionCreateResult_RejectsPayloadFailureEvenWhenKeyIsPresent()
Assert.Equal("session creation was rejected", result.Error);
}

[Theory]
[InlineData(null)]
[InlineData(" ")]
public void BuildSessionCreateParameters_OmitsMissingAgentId(string? agentId)
{
// Gateway schema rejects agentId:null; omission selects its default agent.
var parameters = OpenClawGatewayClient.BuildSessionCreateParameters(
new SessionCreateRequest { AgentId = agentId });

Assert.DoesNotContain("agentId", parameters);
}

[Fact]
public void BuildSessionCreateParameters_LegacyParallelFallbackUnlinksParent()
{
Expand Down
62 changes: 62 additions & 0 deletions tests/OpenClaw.Shared.Tests/OpenClawGatewayClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1082,6 +1082,28 @@ public void SessionCompletion_ParsesOptionalDurationAndClearsMissingAuthoritativ
Assert.Null(session.EndedAt);
}

[Fact]
public async Task TrackedSessionFromJobEvent_IsGatewayListedOnlyAfterSessionRosterOnCurrentConnection()
{
var helper = new GatewayClientTestHelper();
using var client = helper.Client;
helper.ProcessRawMessage("""
{"type":"event","event":"agent","payload":{"sessionKey":"agent:main:main","stream":"job","data":{"state":"running"}}}
""");
Assert.False(Assert.Single(helper.GetSessionList()).IsGatewayListed);

helper.ParseSessionsPayload("""{"sessions":[{"key":"agent:main:main"}]}""");

Assert.True(Assert.Single(helper.GetSessionList()).IsGatewayListed);

await helper.OnConnectedAsync();
helper.ProcessRawMessage("""
{"type":"event","event":"agent","payload":{"sessionKey":"agent:main:main","stream":"job","data":{"state":"running"}}}
""");

Assert.False(Assert.Single(helper.GetSessionList()).IsGatewayListed);
}

private static readonly TimeSpan CloseHandshakeTimeout = TimeSpan.FromSeconds(3);
// Session-event regressions explicitly unset the refresh-window override.
private static readonly TimeSpan SessionRefreshQuietInterval = TimeSpan.FromMilliseconds(600);
Expand Down Expand Up @@ -1948,6 +1970,46 @@ public async Task SessionEventRefresh_DisconnectCancelsOldWindow_AndNewEventsSti
Assert.False(fresh.RootElement.GetProperty("params").TryGetProperty("agentId", out _));
}

[Fact]
public async Task SessionsListError_RetriesOncePerConnection()
{
using var refreshWindow = new EnvironmentScope("OPENCLAW_SESSION_REFRESH_WINDOW_MS", null);
using var server = new LoopbackWebSocketServer();
using var identity = new TempDirectory("session-list-retry-");
await server.StartAsync();
var helper = new GatewayClientTestHelper(gatewayUrl: server.WebSocketUrl, identityPath: identity.Path);
using var client = helper.Client;
await client.ConnectAsync();
helper.MarkHandshakeReady();
const string failure = """{"type":"res","id":"roster","ok":false,"error":{"message":"temporarily unavailable"}}""";

async Task<JsonElement> NextFrameAsync()
{
using var frame = JsonDocument.Parse(await server.ReceiveTextAsync().WaitAsync(StepTimeout));
return frame.RootElement.Clone();
}

helper.TrackPendingRequest("roster", "sessions.list");
helper.ProcessRawMessage(failure);
Assert.Equal("sessions.list", (await NextFrameAsync()).GetProperty("method").GetString());

helper.TrackPendingRequest("roster", "sessions.list");
helper.ProcessRawMessage(failure);
// test-timing-exception: negative probe that a second failure on this connection is not retried.
await Task.Delay(SessionRefreshQuietInterval);
await client.RequestSessionsAsync("barrier");
Assert.Equal("barrier", (await NextFrameAsync()).GetProperty("params").GetProperty("agentId").GetString());

helper.OnDisconnected();
await helper.OnConnectedAsync();
helper.MarkHandshakeReady();
helper.TrackPendingRequest("roster", "sessions.list");
helper.ProcessRawMessage(failure);
var retried = await NextFrameAsync();
Assert.Equal("sessions.list", retried.GetProperty("method").GetString());
Assert.False(retried.GetProperty("params").TryGetProperty("agentId", out _));
}

[Fact]
public async Task AgentIdentityAndConfigEvents_CoalesceIntoOneRosterRefresh()
{
Expand Down
Loading
Loading