Skip to content

Commit 2e2de8e

Browse files
calebedenCopilot
andcommitted
Add gateway lifecycle telemetry
Co-authored-by: Copilot App <[email protected]> Copilot-Session: 23d8c6ac-3d44-4b96-adfe-1e8509594f79
1 parent 77c4244 commit 2e2de8e

10 files changed

Lines changed: 819 additions & 10 deletions

File tree

‎docs/TELEMETRY.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,31 @@ The OpenTelemetry log pipeline should not export:
7878

7979
If a new log category should be exported, add it deliberately and review the structured fields it can emit.
8080

81+
## Gateway connection lifecycle
82+
83+
The tray exports gateway lifecycle diagnostics when an endpoint is configured:
84+
85+
- operator connect traces: `openclaw.connection.operator.connect` and
86+
`openclaw.connection.operator.reconnect`
87+
- coarse operator phase spans:
88+
`openclaw.connection.operator.prepare`,
89+
`openclaw.connection.operator.transport`, and
90+
`openclaw.connection.operator.handshake`
91+
- metrics: `openclaw.connection.attempts`,
92+
`openclaw.connection.attempt.duration`, and
93+
`openclaw.connection.state.transitions`
94+
- structured state logs in the `OpenClaw.Telemetry.Connection` category
95+
96+
Lifecycle attributes are limited to role, operation, outcome, coarse error
97+
category, and finite operator/node/overall states. Gateway URLs, IDs, device
98+
IDs, pairing request IDs, credentials, error messages, and diagnostic-ring
99+
text are not exported.
100+
101+
The phase spans distinguish local credential/client/tunnel preparation, WebSocket
102+
transport establishment, and the gateway challenge/hello handshake. They
103+
intentionally do not trace signing, serialization, response parsing, or token
104+
persistence as separate operations.
105+
81106
## Endpoint handling
82107

83108
The endpoint setting is a collector endpoint, not a credential or request-parameter store. Accept plain `http` and `https` collector URLs with optional path prefixes. Reject URLs with embedded user info, query strings, or fragments.

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 304 additions & 3 deletions
Large diffs are not rendered by default.

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,13 @@ protected override Task ProcessMessageAsync(string json)
164164
protected override Task OnConnectedAsync()
165165
{
166166
ResetUnsupportedMethodFlags();
167+
RaiseTransportConnected();
167168
return Task.CompletedTask;
168169
}
169170

171+
protected void RaiseTransportConnected() =>
172+
TransportConnected?.Invoke(this, EventArgs.Empty);
173+
170174
protected override bool ShouldAutoReconnect()
171175
{
172176
// PairingRequired must stay visible, but approval only takes effect on a fresh socket.
@@ -232,6 +236,8 @@ protected override void OnDisposing()
232236
public event EventHandler<DeviceTokenReceivedEventArgs>? DeviceTokenReceived;
233237
/// <summary>Raised when the hello-ok handshake completes successfully.</summary>
234238
public event EventHandler? HandshakeSucceeded;
239+
/// <summary>Raised after the WebSocket transport connects, before the gateway handshake begins.</summary>
240+
public event EventHandler? TransportConnected;
235241
/// <summary>Raised when the gateway requires pairing approval for this device.</summary>
236242
public event EventHandler<string?>? PairingRequired;
237243
/// <summary>Raised when v3 signature was rejected and client fell back to v2.</summary>

‎src/OpenClaw.Shared/Telemetry/OpenClawTelemetry.cs‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,56 @@ public static class OpenClawTelemetry
4040
return activity;
4141
}
4242

43+
/// <summary>
44+
/// Starts a manually-controlled span without leaving it as the ambient activity.
45+
/// </summary>
46+
/// <remarks>
47+
/// Use this for operations that begin in one asynchronous callback and finish in another.
48+
/// The caller owns the returned activity and must stop or dispose it.
49+
/// </remarks>
50+
public static Activity? StartDetachedActivity(
51+
string spanName,
52+
IEnumerable<OpenClawTelemetryTag>? tags = null,
53+
System.Diagnostics.ActivityKind kind = System.Diagnostics.ActivityKind.Internal,
54+
OpenClawActivitySourceName source = OpenClawActivitySourceName.OpenClaw)
55+
{
56+
var previous = Activity.Current;
57+
try
58+
{
59+
return StartActivity(spanName, tags, kind, source);
60+
}
61+
finally
62+
{
63+
Activity.Current = previous;
64+
}
65+
}
66+
67+
/// <summary>
68+
/// Starts a manually-controlled child span without leaving it as the ambient activity.
69+
/// </summary>
70+
public static Activity? StartDetachedActivity(
71+
string spanName,
72+
ActivityContext parentContext,
73+
IEnumerable<OpenClawTelemetryTag>? tags = null,
74+
System.Diagnostics.ActivityKind kind = System.Diagnostics.ActivityKind.Internal,
75+
OpenClawActivitySourceName source = OpenClawActivitySourceName.OpenClaw)
76+
{
77+
if (string.IsNullOrWhiteSpace(spanName))
78+
throw new ArgumentException("Span name cannot be empty.", nameof(spanName));
79+
80+
var previous = Activity.Current;
81+
try
82+
{
83+
var activity = source.ToActivitySource().StartActivity(spanName, kind, parentContext);
84+
ApplyTags(activity, tags);
85+
return activity;
86+
}
87+
finally
88+
{
89+
Activity.Current = previous;
90+
}
91+
}
92+
4393
/// <summary>
4494
/// Runs a synchronous action inside a span and automatically marks success, cancellation, or failure.
4595
/// </summary>

‎src/OpenClaw.Tray.WinUI/App.xaml.cs‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,8 @@ private async Task OnLaunchedAsync(LaunchActivatedEventArgs args)
496496
_settings = new SettingsManager();
497497
_previousSettingsSnapshot = _settings.ToSettingsData().ToConnectionSnapshot();
498498
_openTelemetryConnection = new OpenTelemetryEndpointConnection();
499-
ApplyOpenTelemetryEndpointSettings();
499+
await _openTelemetryConnection.ApplyAsync(
500+
OpenTelemetryEndpointOptions.FromSettings(_settings));
500501
_chatCoordinator = new OpenClawTray.Chat.OpenClawChatCoordinator(
501502
_settings,
502503
() => _nodeService,
@@ -1934,6 +1935,7 @@ private void RaiseChatProviderChanged()
19341935
/// </summary>
19351936
private void OnManagerStateChanged(object? sender, GatewayConnectionSnapshot snap)
19361937
{
1938+
_openTelemetryConnection?.SendConnectionState(snap);
19371939
var mapped = ConnectionStatusPresenter.ToLegacyStatus(snap);
19381940
var connectedSideEffectsKey = snap.OperatorState == RoleConnectionState.Connected
19391941
? $"{snap.GatewayId ?? snap.GatewayUrl ?? "unknown"}|{snap.OperatorDeviceId ?? "unknown"}"
@@ -4461,12 +4463,6 @@ private async Task ExitApplicationAsync()
44614463
_chatCoordinator = null;
44624464
});
44634465

4464-
SafeShutdownStep("OpenTelemetry endpoint", () =>
4465-
{
4466-
_openTelemetryConnection?.Dispose();
4467-
_openTelemetryConnection = null;
4468-
});
4469-
44704466
// Dispose runtime services
44714467
var connectionManager = _connectionManager;
44724468
if (connectionManager != null)
@@ -4478,6 +4474,12 @@ await SafeShutdownStepAsync("gateway client", async () =>
44784474
_connectionManager = null;
44794475
}
44804476

4477+
SafeShutdownStep("OpenTelemetry endpoint", () =>
4478+
{
4479+
_openTelemetryConnection?.Dispose();
4480+
_openTelemetryConnection = null;
4481+
});
4482+
44814483
var nodeService = _nodeService;
44824484
if (nodeService != null)
44834485
{

0 commit comments

Comments
 (0)