Skip to content

Commit a76c852

Browse files
calebedenCopilotkarkarl
authored
feat(chat): render user and agent media in native chat (#1119)
* Merge origin/main into calebeden-investigate-media-rendering Co-authored-by: Copilot App <[email protected]> * fix(chat): harden media replay and previews Bound local preview memory, enforce guarded local image decoding, preserve media metadata across history and reset reconciliation, and keep runtime V2 credential upgrades without allowing downgrades. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 4f74b3dc-62de-4bf8-abee-aae3915b2f89 --------- Co-authored-by: Copilot App <[email protected]> Co-authored-by: Karen Lai <[email protected]> Copilot-Session: 4f74b3dc-62de-4bf8-abee-aae3915b2f89
1 parent 428db77 commit a76c852

43 files changed

Lines changed: 5757 additions & 280 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/ARCHITECTURE.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,12 @@ leading and trailing pipe. Columns, in order:
206206
| reactor-chat-timeline | authoritative | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatTimeline.cs | production chat message virtualization, row realization, and imperative scroll follow | ReactorChatTimeline through OpenClawReactorChatRoot and ReactorHostControl | OpenClawChatTimeline remains a legacy focused-test surface while its runtime route is migrated | the default chat route mounts one direct ReactorHostControl per XAML chat target; Reactor owns stable-key ItemsView and ItemContainer realization without a custom native list, collection reconciler, or scroll-layout mutation | review-only: user explicitly deferred new tests for this migration; required build and existing shared/tray suites still run | review-only | when Reactor timeline proof coverage replaces the legacy focused UI host coverage |
207207
| chat-tool-activity-renderer | authoritative | src/OpenClaw.Tray.WinUI/Chat/ReactorChatTimeline.cs | production standalone tool-call and grouped activity presentation, summaries, disclosures, and detail rendering | ChatToolActivityPresentation + ToolCallCardRenderer | ReactorChatTimeline projects rows and delegates realization only | consecutive invocation grouping preserves source chronology; stable group identity comes from session, generation, and first tool entry; selectable output remains capped at 240px | ChatToolActivityPresentationTests.Project_GroupsOnlyConsecutiveSpansOfAtLeastTwoTools | behavioral | - |
208208
| chat-history-replay-projection | authoritative | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | array-valued history content ordering projection | ChatHistoryReplayProjection | provider applies projected text and tool parts to the reducer | interleaved text, calls, and results replay in source order without clearing active tool correlation | OpenClawChatDataProviderTests.LoadHistoryAsync_InterleavedContentParts_PreserveChronologyAndCorrelation | behavioral | - |
209+
| assistant-media-protocol-projection | authoritative | src/OpenClaw.Shared/OpenClawGatewayClient.cs | structured assistant media content parsing and assistant-only legacy MEDIA directive redaction/projection | AssistantMediaDirectiveParser + ChatMediaContentInfo | gateway client preserves ordered typed media while tray presentation receives only safe filenames and metadata | user text never activates media directives; accepted local sources never enter visible assistant text or notifications; media-only messages survive live and history parsing | AssistantMediaDirectiveParserTests.Project_AssistantAbsolutePath_ProducesMediaWithoutExposingPath | behavioral | - |
210+
| assistant-media-resolver | authoritative | src/OpenClaw.Shared/OpenClawGatewayClient.cs | authenticated structured artifact and legacy assistant-media byte retrieval | OpenClawGatewayClient.AssistantMedia | chat bridge exposes only lease-bound typed resolution results; renderer never receives credentials, tickets, or arbitrary URLs | accepts only current-connection results, matching media MIME families, managed ticket paths, and payloads within the 12 MiB image or 16 MiB playback caps | OpenClawGatewayClientAssistantMediaTests.ResolveLegacyMedia_UsesBearerMetadataAndSourceBoundTicket | behavioral | - |
211+
| provider-assistant-media-parsing-closed | closed | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | parsing legacy MEDIA directives or structured Gateway media blocks | AssistantMediaDirectiveParser + OpenClawGatewayClient | provider owns message identity, streaming reconciliation, timeline application, and safe presentation metadata orchestration | provider consumes typed content parts and never reparses model text or exposes raw media sources | ChatAssistantContentPresentationTests.Project_UsesSafeFilenameWithoutExposingLegacySource | behavioral | when assistant message ingestion leaves OpenClawChatDataProvider |
212+
| assistant-media-renderer | authoritative | src/OpenClaw.Tray.WinUI/Chat/ReactorChatTimeline.cs | assistant media card presentation, bounded image decode, retry, and row cancellation | ChatAssistantMediaRenderer | ReactorChatTimeline owns row placement and delegates media realization | at most four images render inline per message; unsupported or unresolved typed media remains visible as an accessible safe unavailable card; raw Gateway sources are never rendered | ChatAssistantContentPresentationTests.BuildRenderPlan_CapsImagesWithoutReorderingOtherMedia | behavioral | - |
213+
| gateway-media-message-projection | authoritative | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | gateway media-envelope parsing, safe filename/MIME normalization, attachment signatures, and provenance-safe attachment descriptors | GatewayMediaMessageProjection + ChatAttachmentPresentation | provider applies the projection to live, reset, backfill, and history ingress and owns stateful echo correlation | gateway text never becomes a private marker; gateway descriptors have no preview key; only local opaque preview keys can access image bytes | GatewayMediaMessageProjectionTests.ValidEnvelope_ProjectsSafeDescriptorAndCleanProse | behavioral | - |
214+
| provider-gateway-media-parsing-closed | closed | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | private gateway media-envelope parsing or descriptor construction | GatewayMediaMessageProjection | provider retains stateful pending-echo queues, reset gates, sidecar matching, and reducer application | all user ingress paths call the focused projection and do not independently parse gateway media text | review-only | review-only | when user-message ingestion leaves OpenClawChatDataProvider |
209215
| reactor-tool-rendering-closed | closed | src/OpenClaw.Tray.WinUI/Chat/ReactorChatTimeline.cs | per-tool and grouped activity summary/detail rendering implementation | ToolCallCardRenderer | row projection, virtualization, hover state, assistant runs, and renderer delegation only | ReactorChatTimeline contains no tool detail renderer and delegates both standalone and grouped tool rows | ChatTimelinePresentationTests.ReactorTimeline_DelegatesToolAndActivityRenderingToFocusedOwner | source-shape | when ReactorChatTimeline is replaced as the production virtualization owner |
210216
| functional-chat-default-mount | closed | src/OpenClaw.Tray.WinUI/Chat/FunctionalChatHostExtensions.cs | mounting the FunctionalUI chat tree as the default ChatPage or ChatWindow surface | ReactorChatHostExtensions and OpenClawReactorChatRoot | legacy FunctionalUI chat files may remain for focused compatibility coverage only | ChatPage and ChatWindow mount the Reactor root directly into their existing ChatHost Borders; no FunctionalUI component mounts or nests Reactor on the default path | review-only: user explicitly deferred new tests for this migration; required build and existing shared/tray suites still run | review-only | when legacy FunctionalUI chat surfaces are removed |
211217
| settings-store | authoritative | settings and permission UI surfaces | direct SettingsManager mutation and blanket self-write suppression | ISettingsStore | non-permission legacy surfaces may read SettingsManager until migrated; direct saves publish origin null | every save publishes one versioned event; only the matching writer ignores its own origin while all other active consumers refresh | SettingsSharedStateContractTests.TwoActiveSettingsPageViewModels_IgnoreOnlyOwnWrites_InBothDirections | behavioral | when every settings surface reads and writes through ISettingsStore |

‎src/OpenClaw.Connection/GatewayClientFactory.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ public IGatewayClientLifecycle Create(
2121
tokenIsBootstrapToken: credential.IsBootstrapToken,
2222
bootstrapPairAsNode: false,
2323
identityPath: identityPath,
24-
ignoreStoredDeviceToken: credential.IsBootstrapToken);
24+
ignoreStoredDeviceToken: credential.IsBootstrapToken,
25+
assistantMediaAuthToken: credential.InteractiveHttpToken);
2526

2627
return new GatewayClientLifecycleAdapter(client);
2728
}

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 155 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -526,7 +526,52 @@ await StopOwnedTunnelAfterFailedConnectionAsync(
526526
IGatewayClientLifecycle lifecycle;
527527
try
528528
{
529-
lifecycle = _clientFactory.Create(connectUrl, credential, perGatewayIdentityDir, diagLogger);
529+
var httpCredential =
530+
InteractiveGatewayCredentialResolver.ResolveForAssistantMediaHttpSurface(
531+
record,
532+
credential);
533+
var interactiveHttpToken = string.Empty;
534+
if (httpCredential is not null)
535+
{
536+
var httpAuthorization = await AuthorizeCredentialForEndpointAsync(
537+
record,
538+
httpCredential,
539+
_operationCts!.Token)
540+
.ConfigureAwait(false);
541+
if (_disposed ||
542+
Interlocked.Read(ref _generation) != gen ||
543+
_operationCts?.IsCancellationRequested != false)
544+
{
545+
return;
546+
}
547+
if (httpAuthorization.Allowed)
548+
{
549+
interactiveHttpToken = httpCredential.Token;
550+
}
551+
else
552+
{
553+
_diagnostics.Record(
554+
"credentials",
555+
"Interactive HTTP credential was withheld",
556+
httpAuthorization.Detail);
557+
}
558+
}
559+
else
560+
{
561+
_diagnostics.Record(
562+
"credentials",
563+
"Interactive HTTP credential was unavailable");
564+
}
565+
566+
var clientCredential = credential with
567+
{
568+
InteractiveHttpToken = interactiveHttpToken,
569+
};
570+
lifecycle = _clientFactory.Create(
571+
connectUrl,
572+
clientCredential,
573+
perGatewayIdentityDir,
574+
diagLogger);
530575
}
531576
catch (DeviceIdentityLoadException ex)
532577
{
@@ -557,6 +602,11 @@ await StopOwnedTunnelAfterFailedConnectionAsync(
557602
async Task<ReconnectAuthorizationResult> AuthorizeLiveCredentialHandoffAsync(
558603
CancellationToken cancellationToken)
559604
{
605+
// Clear the assistant-media HTTP credential up front so any
606+
// in-flight media request never outlives this handoff attempt;
607+
// it is only restored below once the fresh credential (or its
608+
// interactive HTTP fallback) is re-authorized for this generation.
609+
lifecycle.DataClient.SetAssistantMediaAuthToken(null);
560610
var authorization = await AuthorizeCredentialHandoffAsync(
561611
record,
562612
credential,
@@ -578,6 +628,58 @@ await RecordOperatorCredentialHandoffFailureAsync(
578628
record.Id)
579629
.ConfigureAwait(false);
580630
}
631+
632+
if (authorization.Allowed &&
633+
IsCurrentGatewayAttempt(gen, record.Id) &&
634+
IsAutomaticReconnectAllowed(record.Id))
635+
{
636+
var currentRecord = _registry.GetById(record.Id);
637+
if (currentRecord is not null)
638+
{
639+
GatewayCredential? currentHttpFallback = null;
640+
if (string.IsNullOrWhiteSpace(currentRecord.SharedGatewayToken))
641+
{
642+
currentHttpFallback = _credentialResolver.ResolveOperator(
643+
currentRecord,
644+
perGatewayIdentityDir);
645+
}
646+
var reconnectHttpCredential =
647+
InteractiveGatewayCredentialResolver.ResolveForAssistantMediaHttpSurface(
648+
currentRecord,
649+
currentHttpFallback);
650+
if (reconnectHttpCredential is null)
651+
{
652+
_diagnostics.Record(
653+
"credentials",
654+
"Interactive HTTP credential was unavailable during reconnect");
655+
}
656+
else
657+
{
658+
var httpAuthorization = await AuthorizeCredentialForEndpointAsync(
659+
currentRecord,
660+
reconnectHttpCredential,
661+
cancellationToken)
662+
.ConfigureAwait(false);
663+
if (IsCurrentGatewayAttempt(gen, record.Id) &&
664+
IsAutomaticReconnectAllowed(record.Id))
665+
{
666+
if (httpAuthorization.Allowed)
667+
{
668+
lifecycle.DataClient.SetAssistantMediaAuthToken(
669+
reconnectHttpCredential.Token);
670+
}
671+
else
672+
{
673+
_diagnostics.Record(
674+
"credentials",
675+
"Interactive HTTP credential was withheld during reconnect",
676+
httpAuthorization.Detail);
677+
}
678+
}
679+
}
680+
}
681+
}
682+
581683
return authorization;
582684
}
583685

@@ -2463,7 +2565,7 @@ private static bool IsSameCredentialHandoffRecord(
24632565
expected.BootstrapToken,
24642566
StringComparison.Ordinal) &&
24652567
current.IsLocal == expected.IsLocal &&
2466-
current.RequiresV2Signature == expected.RequiresV2Signature &&
2568+
(current.RequiresV2Signature || !expected.RequiresV2Signature) &&
24672569
string.Equals(
24682570
current.SetupManagedDistroName,
24692571
expected.SetupManagedDistroName,
@@ -2549,23 +2651,66 @@ private async Task HandleDeviceTokenReceivedAsync(
25492651
identityPath,
25502652
token,
25512653
CancellationToken.None).ConfigureAwait(false);
2552-
if (result.Outcome != DeviceTokenHandlingOutcome.IdentityLoadFailure)
2654+
if (result.Outcome != DeviceTokenHandlingOutcome.IdentityLoadFailure &&
2655+
result.Outcome != DeviceTokenHandlingOutcome.Stored)
2656+
{
25532657
return;
2658+
}
25542659

2660+
var gatewayRecordId = attempt.GatewayRecordId ?? string.Empty;
25552661
await _transitionSemaphore.WaitAsync().ConfigureAwait(false);
25562662
try
25572663
{
2558-
if (!IsCurrentGatewayAttempt(
2559-
attempt.LifecycleGeneration,
2560-
attempt.GatewayRecordId ?? string.Empty))
2664+
if (!IsCurrentGatewayAttempt(attempt.LifecycleGeneration, gatewayRecordId))
25612665
{
25622666
return;
25632667
}
25642668

2565-
_stateMachine.TryTransition(
2566-
ConnectionTrigger.WebSocketError,
2567-
DeviceIdentityLoadException.RecoveryMessage);
2568-
EmitStateChanged();
2669+
if (result.Outcome == DeviceTokenHandlingOutcome.IdentityLoadFailure)
2670+
{
2671+
_stateMachine.TryTransition(
2672+
ConnectionTrigger.WebSocketError,
2673+
DeviceIdentityLoadException.RecoveryMessage);
2674+
EmitStateChanged();
2675+
return;
2676+
}
2677+
2678+
// Stored: refresh the assistant-media HTTP credential bound to the
2679+
// fresh operator device token when this connection relies on a
2680+
// device token rather than a shared gateway token.
2681+
if (!string.Equals(token.Role, "operator", StringComparison.OrdinalIgnoreCase))
2682+
return;
2683+
2684+
var currentRecord = _registry.GetById(gatewayRecordId);
2685+
if (currentRecord is null ||
2686+
!string.IsNullOrWhiteSpace(currentRecord.SharedGatewayToken))
2687+
{
2688+
return;
2689+
}
2690+
2691+
var deviceCredential = new GatewayCredential(
2692+
token.Token,
2693+
IsBootstrapToken: false,
2694+
CredentialResolver.SourceDeviceToken);
2695+
var authorization = await AuthorizeCredentialForEndpointAsync(
2696+
currentRecord,
2697+
deviceCredential,
2698+
_operationCts?.Token ?? CancellationToken.None)
2699+
.ConfigureAwait(false);
2700+
if (!IsCurrentGatewayAttempt(attempt.LifecycleGeneration, gatewayRecordId))
2701+
return;
2702+
if (authorization.Allowed)
2703+
{
2704+
_activeLifecycle?.DataClient.SetAssistantMediaAuthToken(token.Token);
2705+
}
2706+
else
2707+
{
2708+
_activeLifecycle?.DataClient.SetAssistantMediaAuthToken(null);
2709+
_diagnostics.Record(
2710+
"credentials",
2711+
"Interactive HTTP device credential was withheld after token refresh",
2712+
authorization.Detail);
2713+
}
25692714
}
25702715
finally
25712716
{

‎src/OpenClaw.Connection/ICredentialResolver.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ public sealed record GatewayCredential(string Token, bool IsBootstrapToken, stri
1111
GatewayCredentialResolutionStatus.Resolved;
1212
public bool FallbackUsed { get; init; }
1313
public string? ResolutionDetail { get; init; }
14+
public string? InteractiveHttpToken { get; init; }
1415
}
1516

1617
/// <summary>

‎src/OpenClaw.Connection/InteractiveGatewayCredentialResolver.cs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,22 @@ namespace OpenClaw.Connection;
1010
/// </summary>
1111
public static class InteractiveGatewayCredentialResolver
1212
{
13+
internal static GatewayCredential? ResolveForAssistantMediaHttpSurface(
14+
GatewayRecord record,
15+
GatewayCredential? fallback) =>
16+
!string.IsNullOrWhiteSpace(record.SharedGatewayToken)
17+
? new GatewayCredential(
18+
record.SharedGatewayToken!,
19+
IsBootstrapToken: false,
20+
CredentialResolver.SourceSharedGatewayToken)
21+
: fallback is
22+
{
23+
IsBootstrapToken: false,
24+
Source: CredentialResolver.SourceDeviceToken,
25+
}
26+
? fallback
27+
: null;
28+
1329
public static bool TryResolve(
1430
GatewayRegistry? registry,
1531
string settingsDirectory,

0 commit comments

Comments
 (0)