Reworked coding context management

This commit is contained in:
Thorsten Sommer 2026-07-06 19:31:27 +02:00
parent 38fe814ff1
commit b87f7d1cc3
Signed by untrusted user who does not match committer: tsommer
GPG Key ID: 371BBA77A02C0108
6 changed files with 25 additions and 154 deletions

View File

@ -1,19 +1,13 @@
@attribute [Route(Routes.ASSISTANT_CODING)]
@inherits AssistantBaseCore<AIStudio.Dialogs.Settings.SettingsDialogCoding>
<MudExpansionPanels Class="mb-3">
@for (var contextIndex = 0; contextIndex < this.codingContexts.Count; contextIndex++)
{
var codingContext = this.codingContexts[contextIndex];
var index = contextIndex;
<ExpansionPanel HeaderText="@codingContext.Id" HeaderIcon="@Icons.Material.Filled.Code" ShowEndButton="@true" EndButtonColor="Color.Error" EndButtonIcon="@Icons.Material.Filled.Delete" EndButtonTooltip="@T("Delete context")" EndButtonClickAsync="@(() => this.DeleteContext(index))">
<CodingContextItem @bind-CodingContext="@codingContext"/>
</ExpansionPanel>
}
</MudExpansionPanels>
<MudButton Variant="Variant.Filled" OnClick="() => this.AddCodingContext()" Class="mb-3">
@T("Add context")
</MudButton>
<MudText Typo="Typo.h5" Class="mb-1 mt-3">@T("Context")</MudText>
<MudJustifiedText Typo="Typo.body1" Class="mb-2">
@T("You can attach source files as optional context for your coding question.")
</MudJustifiedText>
<div class="mb-3">
<AttachDocuments Name="Coding Source Files" Layer="@DropLayers.ASSISTANTS" @bind-DocumentPaths="@this.loadedDocumentPaths" CatchAllDocuments="true" UseSmallForm="false" Provider="@this.ProviderSettings"/>
</div>
<MudStack Row="@false" Class="mb-3">
<MudTextSwitch Label="@T("Do you want to provide compiler messages?")" @bind-Value="@this.provideCompilerMessages" LabelOn="@T("Yes, provide compiler messages")" LabelOff="@T("No, there are no compiler messages")" />
@ -24,4 +18,4 @@
</MudStack>
<MudTextField T="string" @bind-Text="@this.questions" Validation="@this.ValidateQuestions" AdornmentIcon="@Icons.Material.Filled.QuestionMark" Adornment="Adornment.Start" Label="@T("Your question(s)")" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<ProviderSelection @bind-ProviderSettings="@this.ProviderSettings" ValidateProvider="@this.ValidatingProvider"/>
<ProviderSelection @bind-ProviderSettings="@this.ProviderSettings" ValidateProvider="@this.ValidatingProvider"/>

View File

@ -1,5 +1,6 @@
using System.Text;
using AIStudio.Chat;
using AIStudio.Dialogs.Settings;
using AIStudio.Tools.AssistantSessions;
@ -11,7 +12,7 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
protected override string Title => T("Coding Assistant");
protected override string Description => T("This coding assistant supports you in writing code. Provide some coding context by copying and pasting your code into the input fields. You might assign an ID to your code snippet to easily reference it later. When you have compiler messages, you can paste them into the input fields to get help with debugging as well.");
protected override string Description => T("This coding assistant supports you in writing code. Ask your coding question and optionally attach source files as context. When you have compiler messages, you can paste them into the input fields to get help with debugging as well.");
protected override string SystemPrompt =>
"""
@ -20,6 +21,12 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
You know object-oriented programming, as well as functional programming and procedural programming. You are also
familiar with design patterns and can explain them. You are an expert of debugging and can help with compiler
messages. You can also help with code refactoring and optimization.
The user may attach source files, project files, configuration files, logs, or other documents as coding context.
Treat attached files as source context for the user's question. Use the file paths and file contents provided in
the message to reason about the code. Do not invent files or APIs that are not present in the user's question or
attached context. If the question conflicts with attached context, prioritize the user's explicit question and
explain any relevant mismatch.
When the user asks in a different language than English, you answer in the same language!
""";
@ -36,7 +43,7 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
protected override void ResetForm()
{
this.codingContexts.Clear();
this.loadedDocumentPaths.Clear();
this.compilerMessages = string.Empty;
this.questions = string.Empty;
if (!this.MightPreselectValues())
@ -56,11 +63,11 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
return false;
}
private readonly List<CodingContext> codingContexts = new();
private HashSet<FileAttachment> loadedDocumentPaths = [];
private bool provideCompilerMessages;
private string compilerMessages = string.Empty;
private string questions = string.Empty;
private static readonly AssistantSessionStateKey<List<CodingContext>> CODING_CONTEXTS_STATE_KEY = new(nameof(codingContexts));
private static readonly AssistantSessionStateKey<HashSet<FileAttachment>> LOADED_DOCUMENT_PATHS_STATE_KEY = new(nameof(loadedDocumentPaths));
private static readonly AssistantSessionStateKey<bool> PROVIDE_COMPILER_MESSAGES_STATE_KEY = new(nameof(provideCompilerMessages));
private static readonly AssistantSessionStateKey<string> COMPILER_MESSAGES_STATE_KEY = new(nameof(compilerMessages));
private static readonly AssistantSessionStateKey<string> QUESTIONS_STATE_KEY = new(nameof(questions));
@ -68,7 +75,7 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
/// <inheritdoc />
protected override void CaptureCustomAssistantSessionState(AssistantSessionStateWriter state)
{
state.SetList(CODING_CONTEXTS_STATE_KEY, this.codingContexts);
state.SetHashSet(LOADED_DOCUMENT_PATHS_STATE_KEY, this.loadedDocumentPaths);
state.Set(PROVIDE_COMPILER_MESSAGES_STATE_KEY, this.provideCompilerMessages);
state.Set(COMPILER_MESSAGES_STATE_KEY, this.compilerMessages);
state.Set(QUESTIONS_STATE_KEY, this.questions);
@ -77,7 +84,7 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
/// <inheritdoc />
protected override void RestoreCustomAssistantSessionState(AssistantSessionStateReader state)
{
state.RestoreList(CODING_CONTEXTS_STATE_KEY, this.codingContexts);
state.RestoreHashSet(LOADED_DOCUMENT_PATHS_STATE_KEY, this.loadedDocumentPaths);
state.Restore(PROVIDE_COMPILER_MESSAGES_STATE_KEY, value => this.provideCompilerMessages = value);
state.Restore(COMPILER_MESSAGES_STATE_KEY, value => this.compilerMessages = value);
state.Restore(QUESTIONS_STATE_KEY, value => this.questions = value);
@ -115,56 +122,12 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
return null;
}
private void AddCodingContext()
{
this.codingContexts.Add(new()
{
Id = string.Format(T("Context {0}"), this.codingContexts.Count + 1),
Language = this.SettingsManager.ConfigurationData.Coding.PreselectOptions ? this.SettingsManager.ConfigurationData.Coding.PreselectedProgrammingLanguage : default,
OtherLanguage = this.SettingsManager.ConfigurationData.Coding.PreselectOptions ? this.SettingsManager.ConfigurationData.Coding.PreselectedOtherProgrammingLanguage : string.Empty,
});
}
private ValueTask DeleteContext(int index)
{
if(this.codingContexts.Count < index + 1)
return ValueTask.CompletedTask;
this.codingContexts.RemoveAt(index);
this.Form?.ResetValidation();
this.StateHasChanged();
return ValueTask.CompletedTask;
}
private async Task GetSupport()
{
await this.Form!.Validate();
if (!this.InputIsValid)
return;
var sbContext = new StringBuilder();
if (this.codingContexts.Count > 0)
{
sbContext.AppendLine("I have the following coding context:");
sbContext.AppendLine();
foreach (var codingContext in this.codingContexts)
{
sbContext.AppendLine($"ID: {codingContext.Id}");
if(codingContext.Language is not CommonCodingLanguages.OTHER)
sbContext.AppendLine($"Language: {codingContext.Language.Name()}");
else
sbContext.AppendLine($"Language: {codingContext.OtherLanguage}");
sbContext.AppendLine("Content:");
sbContext.AppendLine("```");
sbContext.AppendLine(codingContext.Code);
sbContext.AppendLine("```");
sbContext.AppendLine();
}
}
var sbCompilerMessages = new StringBuilder();
if (this.provideCompilerMessages)
{
@ -179,12 +142,13 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
this.CreateChatThread();
var time = this.AddUserRequest(
$"""
{sbContext}
{sbCompilerMessages}
My questions are:
{this.questions}
""");
""",
false,
this.loadedDocumentPaths.ToList());
await this.AddAIResponseAsync(time);
}

View File

@ -1,16 +0,0 @@
namespace AIStudio.Assistants.Coding;
public sealed class CodingContext(string id, CommonCodingLanguages language, string otherLanguage, string code)
{
public CodingContext() : this(string.Empty, CommonCodingLanguages.NONE, string.Empty, string.Empty)
{
}
public string Id { get; set; } = id;
public CommonCodingLanguages Language { get; set; } = language;
public string OtherLanguage { get; set; } = otherLanguage;
public string Code { get; set; } = code;
}

View File

@ -1,18 +0,0 @@
@inherits MSGComponentBase
<MudTextField T="string" @bind-Text="@this.CodingContext.Id" AdornmentIcon="@Icons.Material.Filled.Numbers" Adornment="Adornment.Start" Label="@T("(Optional) Identifier")" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudStack Row="@true" Class="mb-3">
<MudSelect T="CommonCodingLanguages" @bind-Value="@this.CodingContext.Language" AdornmentIcon="@Icons.Material.Filled.Code" Adornment="Adornment.Start" Label="@T("Language")" Variant="Variant.Outlined" Margin="Margin.Dense">
@foreach (var language in Enum.GetValues<CommonCodingLanguages>())
{
<MudSelectItem Value="@language">
@language.Name()
</MudSelectItem>
}
</MudSelect>
@if (this.CodingContext.Language is CommonCodingLanguages.OTHER)
{
<MudTextField T="string" @bind-Text="@this.CodingContext.OtherLanguage" Validation="@this.ValidatingOtherLanguage" Label="@T("Other language")" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
}
</MudStack>
<MudTextField T="string" @bind-Text="@this.CodingContext.Code" Validation="@this.ValidatingCode" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="@T("Your code")" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" />

View File

@ -1,47 +0,0 @@
using AIStudio.Components;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Assistants.Coding;
public partial class CodingContextItem : MSGComponentBase
{
[Parameter]
public CodingContext CodingContext { get; set; } = new();
[Parameter]
public EventCallback<CodingContext> CodingContextChanged { get; set; }
private static readonly Dictionary<string, object?> USER_INPUT_ATTRIBUTES = new();
#region Overrides of ComponentBase
protected override async Task OnParametersSetAsync()
{
// Configure the spellchecking for the user input:
this.SettingsManager.InjectSpellchecking(USER_INPUT_ATTRIBUTES);
await base.OnParametersSetAsync();
}
#endregion
private string? ValidatingCode(string code)
{
if(string.IsNullOrWhiteSpace(code))
return string.Format(T("{0}: Please provide your input."), this.CodingContext.Id);
return null;
}
private string? ValidatingOtherLanguage(string language)
{
if(this.CodingContext.Language != CommonCodingLanguages.OTHER)
return null;
if(string.IsNullOrWhiteSpace(language))
return T("Please specify the language.");
return null;
}
}

View File

@ -1,4 +1,3 @@
@using AIStudio.Assistants.Coding
@using AIStudio.Settings
@inherits SettingsDialogBase
@ -11,13 +10,8 @@
</TitleContent>
<DialogContent>
<MudPaper Class="pa-3 mb-8 border-dashed border rounded-lg">
<ConfigurationOption OptionDescription="@T("Preselect coding options?")" LabelOn="@T("Coding options are preselected")" LabelOff="@T("No coding options are preselected")" State="@(() => this.SettingsManager.ConfigurationData.Coding.PreselectOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.Coding.PreselectOptions = updatedState)" OptionHelp="@T("When enabled, you can preselect the coding options. This is might be useful when you prefer a specific programming language or LLM model.")"/>
<ConfigurationOption OptionDescription="@T("Preselect coding options?")" LabelOn="@T("Coding options are preselected")" LabelOff="@T("No coding options are preselected")" State="@(() => this.SettingsManager.ConfigurationData.Coding.PreselectOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.Coding.PreselectOptions = updatedState)" OptionHelp="@T("When enabled, you can preselect coding assistant options such as compiler message input, provider, and profile.")"/>
<ConfigurationOption OptionDescription="@T("Preselect compiler messages?")" Disabled="@(() => !this.SettingsManager.ConfigurationData.Coding.PreselectOptions)" LabelOn="@T("Compiler messages are preselected")" LabelOff="@T("Compiler messages are not preselected")" State="@(() => this.SettingsManager.ConfigurationData.Coding.PreselectCompilerMessages)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.Coding.PreselectCompilerMessages = updatedState)" />
<ConfigurationSelect OptionDescription="@T("Preselect a programming language")" Disabled="@(() => !this.SettingsManager.ConfigurationData.Coding.PreselectOptions)" SelectedValue="@(() => this.SettingsManager.ConfigurationData.Coding.PreselectedProgrammingLanguage)" Data="@ConfigurationSelectDataFactory.GetCommonCodingLanguagesData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.Coding.PreselectedProgrammingLanguage = selectedValue)" OptionHelp="@T("Which programming language should be preselected for added contexts?")"/>
@if (this.SettingsManager.ConfigurationData.Coding.PreselectedProgrammingLanguage is CommonCodingLanguages.OTHER)
{
<ConfigurationText OptionDescription="@T("Preselect another programming language")" Disabled="@(() => !this.SettingsManager.ConfigurationData.Coding.PreselectOptions)" Icon="@Icons.Material.Filled.Code" Text="@(() => this.SettingsManager.ConfigurationData.Coding.PreselectedOtherProgrammingLanguage)" TextUpdate="@(updatedText => this.SettingsManager.ConfigurationData.Coding.PreselectedOtherProgrammingLanguage = updatedText)"/>
}
<ConfigurationMinConfidenceSelection Disabled="@(() => !this.SettingsManager.ConfigurationData.Coding.PreselectOptions)" RestrictToGlobalMinimumConfidence="@true" SelectedValue="@(() => this.SettingsManager.ConfigurationData.Coding.MinimumProviderConfidence)" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.Coding.MinimumProviderConfidence = selectedValue)"/>
<ConfigurationProviderSelection Component="Components.CODING_ASSISTANT" Data="@this.AvailableLLMProviders" Disabled="@(() => !this.SettingsManager.ConfigurationData.Coding.PreselectOptions)" SelectedValue="@(() => this.SettingsManager.ConfigurationData.Coding.PreselectedProvider)" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.Coding.PreselectedProvider = selectedValue)"/>
<ConfigurationSelect OptionDescription="@T("Preselect a profile")" Disabled="@(() => !this.SettingsManager.ConfigurationData.Coding.PreselectOptions)" SelectedValue="@(() => ProfilePreselection.FromStoredValue(this.SettingsManager.ConfigurationData.Coding.PreselectedProfile))" Data="@ConfigurationSelectDataFactory.GetComponentProfilesData(this.SettingsManager.ConfigurationData.Profiles)" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.Coding.PreselectedProfile = selectedValue)" OptionHelp="@T("Choose whether the assistant should use the app default profile, no profile, or a specific profile.")"/>