using AIStudio.Provider;
using AIStudio.Tools.AssistantSessions;
using ComponentKind = AIStudio.Tools.Components;
using ProviderSettings = AIStudio.Settings.Provider;
namespace AIStudio.Assistants.VisualBriefing;
public partial class VisualBriefingAssistant
{
///
/// Gets the active or canceling build session for the selected briefing.
///
private AssistantSessionSnapshot? CurrentBuildSession => this.selectedBriefing is null ? null : this.AssistantSessionService.TryGetSnapshot(CreateBuildSessionKey(this.selectedBriefing.BriefingId));
///
/// Gets whether cancellation was already requested for the selected briefing build.
///
private bool IsCurrentBuildCanceling => this.CurrentBuildSession?.Status is AssistantSessionStatus.CANCELING;
///
/// Gets whether the selected revision cannot be recompiled without model calls.
///
private bool CannotRecompile => this.IsCurrentBusy || this.selectedBriefing is null || this.selectedRevisionId == Guid.Empty || !this.SelectedVersionSupportsEdits;
///
/// Gets the border that marks an action with the confidence of the selected provider.
///
///
/// Only the actions that actually hand briefing data to a provider carry this border. Recompiling
/// reuses the stored artifacts and calls no model at all, so marking it would announce a transfer
/// that never happens, and stopping a build sends nothing either.
///
private string ConfidenceBorderStyle => this.SettingsManager.ConfigurationData.Confidence.ShowProviderConfidence
? this.editor.Provider.UsedLLMProvider.GetConfidence(this.SettingsManager).StyleBorder(this.SettingsManager)
: string.Empty;
///
/// Gets whether one edit mode is currently blocked.
///
///
/// A mode is blocked by the very issues listed below the buttons, minus the ones that do not apply
/// to it. Changing only the design rebuilds the presentation from the validated content of a stored
/// version, so it neither needs source material nor cares whether a source file moved away in the
/// meantime. The two modes that edit a stored version instead require that version to still carry
/// its semantic artifacts.
///
/// The edit mode the user asked for.
/// true when the mode must stay disabled.
private bool CannotGenerate(VisualBriefingEditMode mode) =>
this.IsCurrentBusy ||
this.selectedBriefing is null ||
this.FieldIssues.Count > 0 ||
mode is not VisualBriefingEditMode.CHANGE_DESIGN && this.SourceIssues.Count > 0 ||
mode is VisualBriefingEditMode.CHANGE_DESIGN or VisualBriefingEditMode.UPDATE_CONTENT && !this.SelectedVersionSupportsEdits;
///
/// Runs one long-running briefing operation inside the shared session, progress, and error envelope.
///
///
/// Generating a new version and recompiling an existing one differ only in the guard, the call they
/// make, and the messages they show. Everything around that is identical: the per-briefing session,
/// the busy marker, the diagnostics, the reload of either the editor or the background list entry,
/// and the terminal status. Keeping that envelope in one place is what makes both paths behave the
/// same when an operation is canceled or fails unexpectedly.
///
/// The briefing the operation runs on.
/// The edit mode, used for diagnostics.
/// The orchestrator call to run.
/// The message shown after a new version was committed.
/// The issue recorded when the user canceled the operation.
/// The issue recorded when the operation threw.
/// A task that completes once the operation reached a terminal state.
private async Task RunBriefingOperationAsync(VisualBriefingManifest briefing, VisualBriefingEditMode mode, Func> operation,
string successMessage, string canceledMessage, string unexpectedFailureMessage)
{
var briefingId = briefing.BriefingId;
var sessionKey = CreateBuildSessionKey(briefingId);
if (this.AssistantSessionService.TryGetSnapshot(sessionKey)?.IsActive == true)
return;
// The session service disposes this token source when the session completes:
var cancellation = new CancellationTokenSource();
var session = await this.AssistantSessionService.TryBeginAsync(sessionKey, briefing.Name, cancellation, null,
new(StringComparer.Ordinal), this);
var terminalStatus = AssistantSessionStatus.FAILED;
var terminalIssue = string.Empty;
this.generatingBriefings.Add(briefingId);
this.StateHasChanged();
try
{
var result = await operation(cancellation.Token);
this.lastBuildDiagnostics = result.Diagnostics;
this.latestBuild = this.BuildProgressService.GetLatest(briefingId) ?? (await this.Store.ListBuildsAsync(briefingId, cancellation.Token)).FirstOrDefault();
if (!result.Success || result.Version is null)
{
terminalStatus = result.FailureCode is VisualBriefingFailureCode.CANCELED ? AssistantSessionStatus.CANCELED : AssistantSessionStatus.FAILED;
this.reusableContentBuildId = result.CanContinueAsRebuild ? result.Diagnostics.BuildId : null;
// The issue carried by the result is stable English contract language, because it also
// goes back to the model and into the persisted build record. What the user reads is
// derived from the stable enums in the current language instead:
terminalIssue = VisualBriefingFailureExtensions.ToUserMessage(result.FailureCode, result.Diagnostics.ValidationRule);
if (terminalStatus is not AssistantSessionStatus.CANCELED)
await this.MessageBus.SendError(new(Icons.Material.Filled.AutoAwesome, terminalIssue));
return;
}
this.reusableContentBuildId = null;
if (this.selectedBriefing?.BriefingId == briefingId)
{
await this.ReloadListAsync(briefingId);
await this.SelectRevisionAsync(result.Version.RevisionId);
}
else
{
var latest = await this.Store.LoadAsync(briefingId, cancellation.Token);
if (latest is not null)
this.UpdateProject(latest);
}
await this.MessageBus.SendSuccess(new(Icons.Material.Filled.AutoAwesome, successMessage));
terminalStatus = AssistantSessionStatus.COMPLETED;
}
catch (OperationCanceledException)
{
terminalStatus = AssistantSessionStatus.CANCELED;
terminalIssue = canceledMessage;
}
catch (Exception exception)
{
terminalIssue = unexpectedFailureMessage;
this.Logger.LogError("Unexpected visual briefing UI failure. BriefingId={BriefingId} Mode={Mode} ExceptionType={ExceptionType}", briefingId, mode, exception.GetType().Name);
await this.MessageBus.SendError(new(Icons.Material.Filled.AutoAwesome, terminalIssue));
}
finally
{
await this.AssistantSessionService.CompleteAsync(sessionKey, session.SessionId, terminalStatus, terminalIssue, null, new(StringComparer.Ordinal), this);
this.RetireFinishedSession(sessionKey);
this.generatingBriefings.Remove(briefingId);
this.StateHasChanged();
}
}
///
/// Generates a new immutable version of the selected briefing.
///
/// The edit mode to run.
/// An optional build whose validated content is reused.
/// An optional parent used while resuming a persisted operation.
private async Task GenerateAsync(VisualBriefingEditMode mode, Guid? reusableBuildId = null, Guid? parentRevisionOverride = null)
{
if (this.selectedBriefing is null || this.CannotGenerate(mode))
return;
// Saving reloads the list, which replaces the selected manifest. Everything below must use the
// reloaded instance, so the briefing is captured only after the save:
await this.SaveCurrentAsync(reload: true);
var generationBriefing = this.selectedBriefing;
var parentRevisionId = parentRevisionOverride ?? (generationBriefing.Versions.Count == 0 ? null : this.selectedRevisionId);
var generationProvider = this.editor.Provider;
var generationProfile = this.editor.Profile;
await this.RunBriefingOperationAsync(generationBriefing, mode, token => this.BuildOrchestrator.BuildAsync(generationBriefing, mode,
parentRevisionId, generationProvider, generationProfile, reusableBuildId, token),
T("A new visual briefing version was created."),
T("The visual briefing generation was canceled."),
T("The visual briefing operation failed unexpectedly. Copy the technical details for support."));
}
///
/// Recompiles the selected immutable revision with the current AI Studio export pipeline.
///
/// An optional parent used while resuming a persisted operation.
private async Task RecompileAsync(Guid? parentRevisionOverride = null)
{
var parentRevisionId = parentRevisionOverride ?? this.selectedRevisionId;
if (this.selectedBriefing is null || this.IsCurrentBusy || !this.VersionSupportsSemanticEdits(parentRevisionId))
return;
var recompileBriefing = this.selectedBriefing;
await this.RunBriefingOperationAsync(
recompileBriefing,
VisualBriefingEditMode.RECOMPILE,
token => this.BuildOrchestrator.RecompileAsync(recompileBriefing, parentRevisionId, token),
T("The briefing was recompiled with the current AI Studio version."),
T("The visual briefing recompilation was canceled."),
T("The visual briefing recompilation failed unexpectedly. Copy the technical details for support."));
}
///
/// Consumes the finished session of one briefing while this component is still showing it.
///
///
/// A briefing session carries no state, because the briefing itself is stored on disk. Its only
/// remaining purpose after completion is the indicator on the assistant overview. When the user
/// is still on this page, that indicator would be stale, so we retire the session the same way
/// AssistantBase does. When the user has navigated away, we keep it so the overview can
/// report that a background build has finished.
///
/// The session key of the briefing that just finished.
private void RetireFinishedSession(AssistantSessionKey sessionKey)
{
if (!this.isDisposed)
_ = this.AssistantSessionService.TryTakeInactiveSnapshot(sessionKey);
}
///
/// Automatically resumes the selected build that was active when the app stopped.
///
private async Task ResumeSelectedBuildAsync()
{
if (this.selectedBriefing is null)
return;
var activeBuild = (await this.Store.ListBuildsAsync(this.selectedBriefing.BriefingId))
.FirstOrDefault(build => build.Status is VisualBriefingBuildStatus.ACTIVE);
if (activeBuild is null)
return;
if (activeBuild.Mode is VisualBriefingEditMode.RECOMPILE)
{
await this.RecompileAsync(activeBuild.ParentRevisionId);
return;
}
if (this.editor.Provider == ProviderSettings.NONE)
return;
await this.GenerateAsync(
activeBuild.Mode,
reusableBuildId: null,
parentRevisionOverride: activeBuild.ParentRevisionId);
}
///
/// Applies a content-free live progress update for the selected project.
///
private void BuildProgressChanged(Guid briefingId)
{
if (this.selectedBriefing?.BriefingId != briefingId)
return;
_ = this.InvokeAsync(() =>
{
if (this.selectedBriefing?.BriefingId != briefingId)
return;
this.latestBuild = this.BuildProgressService.GetLatest(briefingId);
this.StateHasChanged();
});
}
///
/// Resumes the latest failed build with its persisted operation inputs.
///
private async Task ResumeLatestBuildAsync()
{
if (this.latestBuild?.Status is not (VisualBriefingBuildStatus.FAILED or VisualBriefingBuildStatus.CANCELED))
return;
if (this.latestBuild.Mode is VisualBriefingEditMode.RECOMPILE)
await this.RecompileAsync(this.latestBuild.ParentRevisionId);
else
await this.GenerateAsync(
this.latestBuild.Mode,
parentRevisionOverride: this.latestBuild.ParentRevisionId);
}
///
/// Requests cancellation for the build running on the selected briefing.
///
private async Task CancelCurrentBuildAsync()
{
if (this.selectedBriefing is null)
return;
var sessionKey = CreateBuildSessionKey(this.selectedBriefing.BriefingId);
if (this.AssistantSessionService.TryGetSnapshot(sessionKey)?.Status is not AssistantSessionStatus.RUNNING)
return;
await this.AssistantSessionService.CancelAsync(sessionKey, this);
this.StateHasChanged();
}
///
/// Defines CopyTechnicalDetailsAsync for the visual briefing feature.
///
private async Task CopyTechnicalDetailsAsync()
{
if (this.lastBuildDiagnostics is null)
return;
await this.RustService.CopyText2Clipboard(this.lastBuildDiagnostics.ToClipboardText());
}
///
/// Defines IsGenerating for the visual briefing feature.
///
private bool IsGenerating(Guid briefingId)
{
if (this.generatingBriefings.Contains(briefingId))
return true;
return this.AssistantSessionService.TryGetSnapshot(CreateBuildSessionKey(briefingId))?.IsActive == true;
}
///
/// Creates the assistant-session key used by a visual briefing build.
///
private static AssistantSessionKey CreateBuildSessionKey(Guid briefingId) => new(ComponentKind.VISUAL_BRIEFING_ASSISTANT, briefingId.ToString("D"));
}