diff --git a/src/Exceptionless.Web/Assistant/AssistantService.cs b/src/Exceptionless.Web/Assistant/AssistantService.cs index fd1f049ffc..5966e76483 100644 --- a/src/Exceptionless.Web/Assistant/AssistantService.cs +++ b/src/Exceptionless.Web/Assistant/AssistantService.cs @@ -1,9 +1,7 @@ -using System.Globalization; using System.Net.Http.Json; using System.Runtime.CompilerServices; using System.Text; using System.Text.Json; -using System.Text.RegularExpressions; using Exceptionless.Core; using Exceptionless.Core.Configuration; using Exceptionless.Core.Models.Billing; @@ -33,9 +31,6 @@ public sealed class AssistantService( private const string SetStackCriticalTool = "set_stack_critical"; private const string SnoozeStackTool = "snooze_stack"; private const string UpdateStackStatusTool = "update_stack_status"; - private static readonly Regex s_durationRegex = new( - @"(?\d+|one|two|three|four|five|six|seven|a|an)\s*(?m|min(?:ute)?s?|h|hrs?|hours?|d|days?|w|weeks?)(?![A-Za-z0-9])", - RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly JsonSerializerOptions s_jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web).ConfigureExceptionlessApiDefaults(); public async IAsyncEnumerable StreamAsync( @@ -310,17 +305,7 @@ public async IAsyncEnumerable StreamAsync( if (toolCall.Name == SearchStacksTool) remainingProjectSearches--; - result = IsWriteTool(toolCall.Name) && !HasExplicitWriteRequest(request, toolCall.Name, arguments) - ? JsonSerializer.Serialize(new - { - ok = false, - error = new - { - code = "write_confirmation_required", - message = "Ask the user to explicitly request this exact change before using a write tool." - } - }, s_jsonOptions) - : await ExecuteToolAsync(toolCall.Name, arguments, request, cancellationToken); + result = await ExecuteToolAsync(toolCall.Name, arguments, request, cancellationToken); } if (toolCall.Name == GetProjectSetupTool) @@ -487,444 +472,6 @@ private async Task ExecuteToolAsync( return String.IsNullOrWhiteSpace(requestedProjectName) ? currentProjectId : null; } - private static bool IsWriteTool(string name) - => name is AddStackReferenceLinkTool or RemoveStackReferenceLinkTool or SetStackCriticalTool or SnoozeStackTool or UpdateStackStatusTool; - - internal static bool HasExplicitWriteRequest(AssistantChatRequest request, string toolName, string arguments = "{}") - { - var latestUserMessage = request.Messages - .LastOrDefault(message => message is not null && String.Equals(message.Role, "user", StringComparison.OrdinalIgnoreCase)); - if (latestUserMessage is null || String.IsNullOrWhiteSpace(latestUserMessage.Content)) - return false; - - string message = latestUserMessage.Content; - if (!HasAffirmativeWriteIntent(message) || HasAlternativeWriteIntent(message)) - return false; - - using var document = ParseArguments(arguments); - var root = document.RootElement; - string? requestedStackId = GetString(root, "stackId", "stack_id"); - string? currentStackId = GetRouteValue(request.Path, "stack"); - if (latestUserMessage.IsSuggestedAction == true - && (!String.Equals(latestUserMessage.SuggestedActionPath, request.Path, StringComparison.Ordinal) - || !HasVisibleSuggestedActionWriteIntent(latestUserMessage.SuggestedActionLabel, toolName, root, requestedStackId, currentStackId))) - { - return false; - } - - if (!HasValidStackTarget(message, requestedStackId, currentStackId, allowImplicitCurrentStack: false)) - return false; - - return toolName switch - { - UpdateStackStatusTool => HasExplicitStackStatusRequest(message, root), - SnoozeStackTool => HasExplicitSnoozeRequest(message, root), - SetStackCriticalTool => HasExplicitCriticalRequest(message, GetBoolean(root, "critical")), - AddStackReferenceLinkTool => HasExplicitReferenceLinkRequest(message, root, remove: false), - RemoveStackReferenceLinkTool => HasExplicitReferenceLinkRequest(message, root, remove: true), - _ => false - }; - } - - private static bool HasVisibleSuggestedActionWriteIntent( - string? label, - string toolName, - JsonElement arguments, - string? requestedStackId, - string? currentStackId) - { - if (String.IsNullOrWhiteSpace(label)) - { - return false; - } - - bool allowImplicitCurrentStack = HasCanonicalImplicitCurrentStackLabel(label, toolName, arguments); - if (!allowImplicitCurrentStack && !HasExplicitSuggestedActionStackTarget(label, requestedStackId, currentStackId)) - { - return false; - } - - if (!HasValidStackTarget(label, requestedStackId, currentStackId, allowImplicitCurrentStack)) - { - return false; - } - - string visibleRequest = $"{label.Trim()} this stack"; - if (!HasAffirmativeWriteIntent(visibleRequest) || HasAlternativeWriteIntent(visibleRequest)) - { - return false; - } - - return toolName switch - { - UpdateStackStatusTool => HasExplicitStackStatusRequest(visibleRequest, arguments), - SnoozeStackTool => HasExplicitSnoozeRequest(visibleRequest, arguments), - SetStackCriticalTool => HasExplicitCriticalRequest(visibleRequest, GetBoolean(arguments, "critical")), - AddStackReferenceLinkTool => HasExplicitReferenceLinkRequest(visibleRequest, arguments, remove: false), - RemoveStackReferenceLinkTool => HasExplicitReferenceLinkRequest(visibleRequest, arguments, remove: true), - _ => false - }; - } - - private static bool HasCanonicalImplicitCurrentStackLabel(string label, string toolName, JsonElement arguments) - { - const string prefix = @"^\s*(?:(?:please|kindly)\s+)?"; - const string currentTarget = @"(?:(?:this|current)\s+(?:stack|issue)\s+)?"; - string pattern = toolName switch - { - UpdateStackStatusTool => GetString(arguments, "status")?.Trim().ToLowerInvariant() switch - { - "fixed" => prefix + @"(?:mark|set|change)\s+" + currentTarget + @"(?:as\s+)?fixed(?:\s+(?:in|for)\s+(?:version\s+)?[A-Za-z0-9._+\-]+)?\s*$", - "ignored" => prefix + @"(?:ignore\s+" + currentTarget + @"|(?:mark|set|change)\s+" + currentTarget + @"(?:as\s+)?ignored)\s*$", - "discarded" => prefix + @"(?:discard\s+" + currentTarget + @"|(?:mark|set|change)\s+" + currentTarget + @"(?:as\s+)?discarded)\s*$", - "open" => prefix + @"(?:reopen\s+" + currentTarget + @"|(?:mark|set|change)\s+" + currentTarget + @"(?:as\s+)?open)\s*$", - _ => "(?!)" - }, - SnoozeStackTool => prefix + @"snooze\s+" + currentTarget + @"(?:for\s+(?:a|an|one|two|three|four|five|six|seven|\d+)\s+(?:minutes?|hours?|days?|weeks?)|until\s+\d{4}-\d{2}-\d{2}(?:T\d{1,2}:\d{2}(?::\d{2})?Z|\s+\d{1,2}:\d{2}(?:\s*[AP]M)?\s+UTC))\s*$", - SetStackCriticalTool when GetBoolean(arguments, "critical") == true => prefix + @"(?:mark|set|make)\s+" + currentTarget + @"(?:as\s+)?critical\s*$", - SetStackCriticalTool when GetBoolean(arguments, "critical") == false => prefix + @"(?:(?:remove|unmark)\s+" + currentTarget + @"critical|(?:mark|set|make)\s+" + currentTarget + @"(?:as\s+)?not\s+critical)\s*$", - AddStackReferenceLinkTool => prefix + @"(?:add|attach)\s+(?:link|reference)\s+https?://\S+\s*$", - RemoveStackReferenceLinkTool => prefix + @"(?:remove|delete)\s+(?:link|reference)\s+https?://\S+\s*$", - _ => "(?!)" - }; - - return Regex.IsMatch(label, pattern, RegexOptions.IgnoreCase); - } - - private static bool HasExplicitSuggestedActionStackTarget(string label, string? requestedStackId, string? currentStackId) - { - string targetText = RemoveAbsoluteUrls(label); - string? expectedStackId = !String.IsNullOrWhiteSpace(requestedStackId) ? requestedStackId : currentStackId; - if (String.IsNullOrWhiteSpace(expectedStackId)) - { - return false; - } - - string[] namedTargets = GetNamedStackTargets(targetText).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); - return namedTargets.Length > 0 - && namedTargets.All(target => String.Equals(target, expectedStackId, StringComparison.OrdinalIgnoreCase)); - } - - private static bool HasAffirmativeWriteIntent(string message) - { - if (Regex.IsMatch( - message, - @"\b(?:do not|don['’]?t|never|should not|shouldn['’]?t|must not|mustn['’]?t)\b", - RegexOptions.IgnoreCase)) - { - return false; - } - - return !Regex.IsMatch( - message.TrimStart(), - @"^(?:should\s+(?:i|we)|(?:can|could|would)\s+(?:i|we)|do\s+(?:i|we)|does\b|did\b|is\s+(?:it|this|the)\b|are\s+(?:we|you|these|those)\b|what\b|why\b|how\b)", - RegexOptions.IgnoreCase); - } - - private static bool HasAlternativeWriteIntent(string message) - => Regex.IsMatch( - message, - @"\b(?:rather\s+than|instead\s+of|except(?:\s+for)?|but\s+not)\b|[,;]\s*not\b", - RegexOptions.IgnoreCase); - - private static bool ReferencesCurrentStack(string message, string currentStackId) - => ContainsExactToken(message, currentStackId) - || ReferencesCurrentStackByPhrase(message); - - private static bool ReferencesCurrentStackByPhrase(string message) - => Regex.IsMatch( - message, - @"\b(?:this|current)\s+(?:stack|issue)\b(?!['’\-])", - RegexOptions.IgnoreCase); - - private static bool HasAmbiguousStackTargets(string message, string? currentStackId) - { - IEnumerable targets = GetNamedStackTargets(message); - if (ReferencesCurrentStackByPhrase(message)) - targets = targets.Append(currentStackId?.ToLowerInvariant() ?? "__current_stack"); - - return targets - .Distinct(StringComparer.Ordinal) - .Skip(1) - .Any(); - } - - private static IEnumerable GetNamedStackTargets(string message) - => Regex.Matches( - message, - $@"\b(?:stack|issue)\s+(?[A-Za-z0-9][A-Za-z0-9_-]*){StackTargetTerminatorPattern}", - RegexOptions.IgnoreCase) - .Select(match => match.Groups["target"].Value.ToLowerInvariant()) - .Where(target => target is not ("this" or "current" or "the" or "fixed" or "ignored" or "discarded" or "open" or "critical" or "not" or "as" or "to" or "with" or "for" or "until")); - - private static bool HasValidStackTarget( - string message, - string? requestedStackId, - string? currentStackId, - bool allowImplicitCurrentStack) - { - string targetText = RemoveAbsoluteUrls(message); - string? expectedStackId = !String.IsNullOrWhiteSpace(requestedStackId) ? requestedStackId : currentStackId; - string[] namedTargets = GetNamedStackTargets(targetText).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); - if (HasAmbiguousStackTargets(targetText, currentStackId) - || (namedTargets.Length > 0 - && (String.IsNullOrWhiteSpace(expectedStackId) - || namedTargets.Any(target => !String.Equals(target, expectedStackId, StringComparison.OrdinalIgnoreCase)))) - || (!String.IsNullOrWhiteSpace(requestedStackId) && IsExcludedStackTarget(targetText, requestedStackId)) - || (!String.IsNullOrWhiteSpace(currentStackId) - && (IsExcludedStackTarget(targetText, currentStackId) || IsExcludedCurrentStackTarget(targetText)))) - { - return false; - } - - bool namesStackTarget = namedTargets.Length > 0; - bool referencesCurrentStack = !String.IsNullOrWhiteSpace(currentStackId) && ReferencesCurrentStack(targetText, currentStackId); - if (String.IsNullOrWhiteSpace(requestedStackId)) - { - return !String.IsNullOrWhiteSpace(currentStackId) - && (referencesCurrentStack || (allowImplicitCurrentStack && !namesStackTarget)); - } - - return ContainsExactToken(targetText, requestedStackId) - || (!String.IsNullOrWhiteSpace(currentStackId) - && String.Equals(requestedStackId, currentStackId, StringComparison.Ordinal) - && (referencesCurrentStack || (allowImplicitCurrentStack && !namesStackTarget))); - } - - private static bool IsExcludedStackTarget(string message, string stackId) - => Regex.IsMatch( - message, - $@"\b(?:not|except|rather\s+than|instead\s+of)\s+(?:the\s+)?(?:stack|issue)\s+{Regex.Escape(stackId)}\b", - RegexOptions.IgnoreCase); - - private static bool IsExcludedCurrentStackTarget(string message) - => Regex.IsMatch( - message, - @"\b(?:not|except|rather\s+than|instead\s+of)\s+(?:the\s+)?(?:this|current)\s+(?:stack|issue)\b|\b(?:the\s+)?(?:other|another|different)\s+(?:stack|issue)\b", - RegexOptions.IgnoreCase); - - private static bool HasExplicitStackStatusRequest(string message, JsonElement arguments) - { - string? status = GetString(arguments, "status")?.Trim().ToLowerInvariant(); - if (status is null || Regex.IsMatch(message, $@"\bnot\s+{Regex.Escape(status)}\b", RegexOptions.IgnoreCase)) - return false; - - string[] requestedStatuses = Regex.Matches(message, @"\b(?:fixed|ignored|ignore|discarded|discard|open|reopen)\b", RegexOptions.IgnoreCase) - .Select(match => match.Value.ToLowerInvariant() switch - { - "ignore" => "ignored", - "discard" => "discarded", - "reopen" => "open", - var value => value - }) - .Distinct(StringComparer.Ordinal) - .Take(2) - .ToArray(); - if (requestedStatuses is not [var requestedStatus] || requestedStatus != status) - return false; - - bool explicitlyRequested = status switch - { - "fixed" => MatchesAffirmativeCommand(message, @"(?:mark|set|change)\b[^\r\n.!?]*\bfixed"), - "ignored" => MatchesAffirmativeCommand(message, @"(?:ignore\b[^\r\n.!?]*\b(?:stack|issue)|(?:mark|set|change)\b[^\r\n.!?]*\bignored)"), - "discarded" => MatchesAffirmativeCommand(message, @"(?:discard\b[^\r\n.!?]*\b(?:stack|issue)|(?:mark|set|change)\b[^\r\n.!?]*\bdiscarded)"), - "open" => MatchesAffirmativeCommand(message, @"(?:reopen\b|(?:mark|set|change)\b[^\r\n.!?]*\bopen)"), - _ => false - }; - if (!explicitlyRequested) - return false; - - string? fixedInVersion = GetString(arguments, "fixedInVersion", "fixed_in_version")?.Trim(); - string[] requestedVersions = Regex.Matches( - message, - @"\bfixed\s+(?:in|for)\s+(?:version\s+)?(?[A-Za-z0-9][A-Za-z0-9._+\-]*)", - RegexOptions.IgnoreCase) - .Select(match => match.Groups["version"].Value) - .Distinct(StringComparer.OrdinalIgnoreCase) - .Take(2) - .ToArray(); - return requestedVersions switch - { - [] => String.IsNullOrWhiteSpace(fixedInVersion), - [var requestedVersion] => String.Equals(fixedInVersion, requestedVersion, StringComparison.OrdinalIgnoreCase), - _ => false - }; - } - - private static bool HasExplicitCriticalRequest(string message, bool? critical) - { - bool requestsCritical = MatchesAffirmativeCommand(message, @"(?:mark|set|make)\b[^\r\n.!?]*\bcritical") - && !Regex.IsMatch(message, @"\bnot\s+critical\b", RegexOptions.IgnoreCase); - bool requestsNotCritical = MatchesAffirmativeCommand( - message, - @"(?:(?:remove|unmark)\b[^\r\n.!?]*\bcritical|(?:mark|set|make)\b[^\r\n.!?]*\bnot\s+critical)"); - bool mentionsRemovingCritical = Regex.IsMatch( - message, - @"\b(?:remove|unmark)\b[^\r\n.!?]*\bcritical|\bnot\s+critical\b", - RegexOptions.IgnoreCase); - - if (requestsCritical && mentionsRemovingCritical) - return false; - - return critical switch - { - true => requestsCritical, - false => requestsNotCritical, - _ => false - }; - } - - private static bool MatchesAffirmativeCommand(string message, string commandPattern) - => Regex.IsMatch( - message, - $@"^\s*(?:(?:please|kindly)\s+)?(?:(?:can|could|would|will)\s+you\s+)?(?:(?:please|kindly)\s+)?(?:{commandPattern})\b", - RegexOptions.IgnoreCase); - - private static bool HasExplicitSnoozeRequest(string message, JsonElement arguments) - { - if (!MatchesAffirmativeCommand(message, @"snooze\b[^\r\n.!?]*\b(?:stack|issue)")) - return false; - - string? duration = GetString(arguments, "duration")?.Trim(); - string? snoozeUntilUtc = GetString(arguments, "snoozeUntilUtc", "snooze_until_utc")?.Trim(); - if (String.IsNullOrWhiteSpace(duration) == String.IsNullOrWhiteSpace(snoozeUntilUtc)) - return false; - - return duration is not null - ? MessageContainsDuration(message, duration) - : MessageContainsUtcDateTime(message, snoozeUntilUtc!); - } - - private static bool MessageContainsDuration(string message, string duration) - { - if (!TryParseDuration(duration, out var expectedDuration)) - return false; - - TimeSpan[] requestedDurations = s_durationRegex.Matches(message) - .Select(match => TryParseDuration(match.Value, out var requestedDuration) ? requestedDuration : TimeSpan.Zero) - .Where(requestedDuration => requestedDuration > TimeSpan.Zero) - .Distinct() - .Take(2) - .ToArray(); - - return requestedDurations is [var requestedDuration] && requestedDuration == expectedDuration; - } - - private static bool TryParseDuration(string value, out TimeSpan duration) - { - duration = TimeSpan.Zero; - string normalized = value.Trim(); - var match = s_durationRegex.Match(normalized); - if (!match.Success || match.Index != 0 || match.Length != normalized.Length) - return false; - - string rawValue = match.Groups["value"].Value; - int amount = rawValue.ToLowerInvariant() switch - { - "a" or "an" or "one" => 1, - "two" => 2, - "three" => 3, - "four" => 4, - "five" => 5, - "six" => 6, - "seven" => 7, - _ when Int32.TryParse(rawValue, NumberStyles.None, CultureInfo.InvariantCulture, out int parsed) => parsed, - _ => 0 - }; - if (amount <= 0) - return false; - - string unit = match.Groups["unit"].Value.ToLowerInvariant(); - try - { - duration = unit[0] switch - { - 'm' => TimeSpan.FromMinutes(amount), - 'h' => TimeSpan.FromHours(amount), - 'd' => TimeSpan.FromDays(amount), - 'w' => TimeSpan.FromDays(amount * 7L), - _ => TimeSpan.Zero - }; - } - catch (OverflowException) - { - return false; - } - - return duration > TimeSpan.Zero; - } - - private static bool MessageContainsUtcDateTime(string message, string snoozeUntilUtc) - { - if (!DateTimeOffset.TryParse( - snoozeUntilUtc, - CultureInfo.InvariantCulture, - DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, - out var untilUtc)) - { - return false; - } - - DateTimeOffset[] requestedDateTimes = Regex.Matches( - message, - @"\b\d{4}-\d{2}-\d{2}(?:T\d{1,2}:\d{2}(?::\d{2})?Z|\s+\d{1,2}:\d{2}(?:\s*[AP]M)?\s+UTC)\b", - RegexOptions.IgnoreCase) - .Select(match => DateTimeOffset.TryParse( - match.Value, - CultureInfo.InvariantCulture, - DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, - out var requestedDateTime) - ? requestedDateTime - : DateTimeOffset.MinValue) - .Where(requestedDateTime => requestedDateTime != DateTimeOffset.MinValue) - .Distinct() - .Take(2) - .ToArray(); - - return requestedDateTimes is [var requestedDateTime] && requestedDateTime == untilUtc; - } - - private static bool HasExplicitReferenceLinkRequest(string message, JsonElement arguments, bool remove) - { - bool explicitlyRequested = remove - ? MatchesAffirmativeCommand(message, @"(?:remove|delete)\b[^\r\n.!?]*\b(?:link|reference)") - : MatchesAffirmativeCommand(message, @"(?:add|attach)\b[^\r\n.!?]*\b(?:link|reference)"); - if (!explicitlyRequested) - return false; - - string? url = GetString(arguments, "url"); - return !String.IsNullOrWhiteSpace(url) && MessageContainsExactUrl(message, url); - } - - private static bool MessageContainsExactUrl(string message, string requestedUrl) - { - if (!Uri.TryCreate(requestedUrl, UriKind.Absolute, out var requestedUri)) - return false; - - Uri[] requestedUris = Regex.Matches(message, """https?://[^\s<>"']+""", RegexOptions.IgnoreCase) - .Select(match => match.Value.TrimEnd('.', ',', ';', ':', '!', '?', ')', ']', '}')) - .Select(candidate => Uri.TryCreate(candidate, UriKind.Absolute, out var candidateUri) ? candidateUri : null) - .Where(candidateUri => candidateUri is not null) - .Select(candidateUri => candidateUri!) - .DistinctBy(candidateUri => candidateUri.AbsoluteUri, StringComparer.Ordinal) - .Take(2) - .ToArray(); - - return requestedUris is [var candidateUri] - && String.Equals(candidateUri.AbsoluteUri, requestedUri.AbsoluteUri, StringComparison.Ordinal); - } - - private static bool ContainsExactToken(string message, string value) - => Regex.IsMatch( - message, - $@"(? Regex.Replace(message, """https?://[^\s<>"']+""", " ", RegexOptions.IgnoreCase); - private static bool ContainsAny(string value, params string[] terms) => terms.Any(term => value.Contains(term, StringComparison.OrdinalIgnoreCase)); diff --git a/src/Exceptionless.Web/ClientApp/e2e/tests/exie-full-page.e2e.ts b/src/Exceptionless.Web/ClientApp/e2e/tests/exie-full-page.e2e.ts new file mode 100644 index 0000000000..d74ba3e8dd --- /dev/null +++ b/src/Exceptionless.Web/ClientApp/e2e/tests/exie-full-page.e2e.ts @@ -0,0 +1,89 @@ +import { expect, test } from '../fixtures/e2e-test'; + +test('Exie opens from navigation and expands without losing the conversation', async ({ e2eScenario, page }) => { + await page.route('**/api/v2/assistant/access**', async (route) => { + await route.fulfill({ + body: JSON.stringify({ enabled: true, has_access: true, upgrade_required: false }), + contentType: 'application/json', + status: 200 + }); + }); + await page.route('**/api/v2/assistant/chat', async (route) => { + await route.fulfill({ + body: `${JSON.stringify({ text: 'This conversation followed you into the full-page chat.', type: 'text_delta' })}\n${JSON.stringify({ type: 'done' })}\n`, + contentType: 'text/event-stream', + status: 200 + }); + }); + + await page.goto('/next/event?filter=status%3Aopen'); + await expect(page.getByText(e2eScenario.organizationName, { exact: true })).toBeVisible(); + + await test.step('open the full-page chat without rendering the outgoing page in the Exie layout', async () => { + const outgoingPageTitle = page.getByRole('heading', { exact: true, name: 'Events' }); + await expect(outgoingPageTitle).toBeVisible(); + await outgoingPageTitle.evaluate((element) => { + element.dataset.outgoingPageTitle = ''; + }); + await page.evaluate(() => { + document.documentElement.dataset.exieTransitionOverlap = 'false'; + const monitorUntil = performance.now() + 1_000; + const monitorTransition = () => { + const outgoingTitle = document.querySelector('[data-outgoing-page-title]'); + if (window.location.pathname.endsWith('/exie') && outgoingTitle && outgoingTitle.getBoundingClientRect().width > 0) { + document.documentElement.dataset.exieTransitionOverlap = 'true'; + } + + if (performance.now() < monitorUntil) { + requestAnimationFrame(monitorTransition); + } + }; + requestAnimationFrame(monitorTransition); + }); + + await page.getByRole('link', { exact: true, name: 'Exie' }).click(); + + await expect(page).toHaveURL(/\/next\/exie(?:[?#]|$)/); + await expect(page.locator('[data-assistant-page]')).toBeVisible(); + await expect(page.getByRole('log', { name: 'Conversation with Exie' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Clear conversation' })).toBeDisabled(); + await page.waitForTimeout(200); + expect(await page.locator('html').getAttribute('data-exie-transition-overlap')).toBe('false'); + }); + + await test.step('expand the side panel and retain its conversation and source URL', async () => { + await page.getByRole('link', { name: 'Collapse Exie to side panel' }).click(); + await expect(page).toHaveURL(/\/next\/stack(?:[?#]|$)/); + await expect(page.locator('[data-assistant-panel]')).toBeVisible(); + await page.getByRole('button', { name: 'Close Exie' }).click(); + + await page.goto('/next/stack?filter=status%3Aopen'); + await page.getByRole('button', { name: 'Open Exie' }).click(); + await page.getByRole('textbox', { name: 'Message Exie' }).fill('Keep this conversation when I expand it.'); + await page.getByRole('button', { name: 'Send message' }).click(); + await expect(page.getByText('This conversation followed you into the full-page chat.')).toBeVisible(); + + await page.getByRole('link', { name: 'Expand Exie to full page' }).click(); + await expect(page).toHaveURL(/\/next\/exie\?/); + const expandedUrl = new URL(page.url()); + expect(expandedUrl.searchParams.get('from')).toBe('/next/stack?filter=status%3Aopen'); + + const fullPageChat = page.locator('[data-assistant-page]'); + await expect(fullPageChat).toBeVisible(); + await expect(fullPageChat.getByText('This conversation followed you into the full-page chat.')).toBeVisible(); + await expect(fullPageChat.getByRole('button', { name: 'Clear conversation' })).toBeEnabled(); + + await expect.poll(async () => (await fullPageChat.boundingBox())?.height ?? 0).toBeGreaterThan(500); + const fullPageBox = await fullPageChat.boundingBox(); + const contentAreaBox = await page.locator('main').boundingBox(); + const contentScrollerBox = await page.locator('main').locator('..').boundingBox(); + expect(fullPageBox).not.toBeNull(); + expect(contentAreaBox).not.toBeNull(); + expect(contentScrollerBox).not.toBeNull(); + expect(fullPageBox!.width).toBeGreaterThan(700); + expect(fullPageBox!.x).toBeCloseTo(contentAreaBox!.x, 1); + expect(fullPageBox!.width).toBeCloseTo(contentAreaBox!.width, 1); + expect(fullPageBox!.x + fullPageBox!.width).toBeCloseTo(contentScrollerBox!.x + contentScrollerBox!.width, 1); + expect(await fullPageChat.evaluate((element) => getComputedStyle(element).borderTopWidth)).toBe('0px'); + }); +}); diff --git a/src/Exceptionless.Web/ClientApp/src/lib/features/assistant/components/assistant-panel.svelte b/src/Exceptionless.Web/ClientApp/src/lib/features/assistant/components/assistant-panel.svelte index 33c7a1e729..1d5d58fefe 100644 --- a/src/Exceptionless.Web/ClientApp/src/lib/features/assistant/components/assistant-panel.svelte +++ b/src/Exceptionless.Web/ClientApp/src/lib/features/assistant/components/assistant-panel.svelte @@ -10,6 +10,8 @@ import Bot from '@lucide/svelte/icons/bot'; import CircleAlert from '@lucide/svelte/icons/circle-alert'; import Eraser from '@lucide/svelte/icons/eraser'; + import Maximize2 from '@lucide/svelte/icons/maximize-2'; + import Minimize2 from '@lucide/svelte/icons/minimize-2'; import { tick, untrack } from 'svelte'; import type { AssistantAccessState, AssistantChatMessage, AssistantFeedback, AssistantPromptRequest, AssistantSuggestedAction } from '../models'; @@ -24,8 +26,12 @@ interface Props { accessMessage?: string; accessState?: AssistantAccessState; + collapseHref?: string; + expandHref?: string; minimumPlanId?: string; + mode?: 'page' | 'sheet'; onAccessChanged?: () => Promise | void; + onCollapse?: () => void; onRetryAccess?: () => Promise | void; open?: boolean; organizationId?: string; @@ -37,8 +43,12 @@ let { accessMessage, accessState = 'available', + collapseHref, + expandHref, minimumPlanId, + mode = 'sheet', onAccessChanged, + onCollapse, onRetryAccess, open = $bindable(false), organizationId, @@ -313,6 +323,10 @@ showScrollToBottom = false; } + function collapseToSidePanel(): void { + onCollapse?.(); + } + function handleConversationScroll(): void { if (!conversationElement) { return; @@ -350,108 +364,78 @@ } - - - -
-
-
-
- Exie - Your Exceptionless assistant. -
-
- {#if accessState === 'available' && messages.length > 0} - - {/if} -
- -
- {#if accessState !== 'available'} - - {:else} -
- {#if messages.length === 0} -
-
-
-
-

Hi, I’m Exie. How can I help?

- - I can use tools to investigate your Exceptionless data and make the stack changes you request. I’ll automatically use the - page or detail panel you’re viewing as context. - -
-
- {#each suggestions as suggestion (suggestion)} - - {/each} -
+{#snippet conversation()} +
+ {#if accessState !== 'available'} + + {:else} +
+ {#if messages.length === 0} +
+
+
- {:else} -
- {#each messages as message (message.id)} - setMessageFeedback(message.id, feedback)} - onRegenerate={() => regenerateResponse(message.id)} - onSuggestedAction={(action) => void handleSuggestedAction(action)} - suggestionsDisabled={isStreaming} - /> +
+

Hi, I’m Exie. How can I help?

+ + I can use tools to investigate your Exceptionless data and make the stack changes you request. I’ll automatically use the page + or detail panel you’re viewing as context. + +
+
+ {#each suggestions as suggestion (suggestion)} + {/each}
- {/if} -
- {/if} - {#if accessState === 'available' && showScrollToBottom} - - {/if} -
+
+ {:else} +
+ {#each messages as message (message.id)} + setMessageFeedback(message.id, feedback)} + onRegenerate={() => regenerateResponse(message.id)} + onSuggestedAction={(action) => void handleSuggestedAction(action)} + suggestionsDisabled={isStreaming} + /> + {/each} +
+ {/if} +
+ {/if} + {#if accessState === 'available' && showScrollToBottom} + + {/if} +
+{/snippet} - {#if accessState === 'available'} - +{#snippet composer()} + {#if accessState === 'available'} +
+
{#if errorMessage}
+
+ {/if} +{/snippet} + +{#if mode === 'page'} +
+
+
+
+
+
+

Exie

+ Your Exceptionless assistant. +
+
+
+ {#if accessState === 'available'} + + {/if} + {#if collapseHref} + + {/if} +
+
+ {@render conversation()} + {@render composer()} +
+{:else} + + + +
+
+
+
+ Exie + Your Exceptionless assistant. +
+
+
+ {#if accessState === 'available' && messages.length > 0} + + {/if} + {#if expandHref} + + {/if} +
+
+ {@render conversation()} + {@render composer()} +
+
+{/if} diff --git a/src/Exceptionless.Web/ClientApp/src/lib/features/assistant/components/assistant-panel.svelte.test.ts b/src/Exceptionless.Web/ClientApp/src/lib/features/assistant/components/assistant-panel.svelte.test.ts index 18489bbea0..6f43ab1d5d 100644 --- a/src/Exceptionless.Web/ClientApp/src/lib/features/assistant/components/assistant-panel.svelte.test.ts +++ b/src/Exceptionless.Web/ClientApp/src/lib/features/assistant/components/assistant-panel.svelte.test.ts @@ -29,6 +29,61 @@ describe('AssistantPanel', () => { expect(screen.getByText('Bring Exie onto your team')).toBeTruthy(); }); + it('renders as a full-page chat and opens the side panel when collapsed', async () => { + const onCollapse = vi.fn(); + render(AssistantPanel, { + props: { + collapseHref: '/next/stack', + mode: 'page', + onCollapse, + open: false, + organizationId: 'organization-1' + } + }); + + expect(screen.getByRole('log', { name: 'Conversation with Exie' })).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Clear conversation' }).hasAttribute('disabled')).toBe(true); + const collapseLink = screen.getByRole('link', { name: 'Collapse Exie to side panel' }); + expect(collapseLink.getAttribute('href')).toBe('/next/stack'); + + collapseLink.addEventListener('click', (event) => event.preventDefault()); + await fireEvent.click(collapseLink); + + expect(onCollapse).toHaveBeenCalledOnce(); + }); + + it('keeps the conversation when expanding the side panel to the full page', async () => { + const fetchMock = vi.fn( + async () => + new Response(`${JSON.stringify({ text: 'The conversation is still here.', type: 'text_delta' })}\n${JSON.stringify({ type: 'done' })}\n`) + ); + vi.stubGlobal('fetch', fetchMock); + + const view = render(AssistantPanel, { + props: { + expandHref: '/next/exie?from=%2Fnext%2Fstack', + open: true, + organizationId: 'organization-1', + promptRequest: { id: 'request-1', prompt: 'Keep this conversation.' } + } + }); + + expect(screen.getByRole('link', { name: 'Expand Exie to full page' }).getAttribute('href')).toBe('/next/exie?from=%2Fnext%2Fstack'); + expect(await screen.findByText('The conversation is still here.')).toBeTruthy(); + + await view.rerender({ + collapseHref: '/next/stack', + mode: 'page', + open: true, + organizationId: 'organization-1', + promptRequest: { id: 'request-1', prompt: 'Keep this conversation.' } + }); + + expect(screen.getByText('The conversation is still here.')).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Clear conversation' }).hasAttribute('disabled')).toBe(false); + expect(fetchMock).toHaveBeenCalledOnce(); + }); + afterEach(() => { vi.unstubAllGlobals(); goto.mockClear(); diff --git a/src/Exceptionless.Web/ClientApp/src/routes/(app)/+layout.svelte b/src/Exceptionless.Web/ClientApp/src/routes/(app)/+layout.svelte index d44338c1f0..2c9ceec495 100644 --- a/src/Exceptionless.Web/ClientApp/src/routes/(app)/+layout.svelte +++ b/src/Exceptionless.Web/ClientApp/src/routes/(app)/+layout.svelte @@ -52,6 +52,7 @@ import { useQueryClient } from '@tanstack/svelte-query'; import { useInterval } from 'runed'; import { tick } from 'svelte'; + import { SvelteURLSearchParams } from 'svelte/reactivity'; import { fade } from 'svelte/transition'; import { type NavigationItemContext, routes } from '../routes.svelte'; @@ -68,6 +69,7 @@ } let { children }: Props = $props(); + const assistantPageHref = resolve('/(app)/exie'); let isAuthenticated = $derived(!!accessToken.current); let requiresPremium = $derived( premiumPage.requiresPremium || filterUsesPremiumFeatures(page.url.searchParams.get('filter'), getSearchResourceForPathname(page.url.pathname)) @@ -77,9 +79,14 @@ let isAssistantOpen = $state(false); let AssistantPanel = $state(); let assistantPromptRequest = $state(); - let assistantResourceContext = $derived(assistantPageContext.getContext(page.params.eventId, page.params.stackId)); - let assistantProjectId = $derived(assistantResourceContext?.projectId ?? page.params.projectId); - let assistantPath = $derived(getAssistantPath(assistantResourceContext, `${page.url.pathname}${page.url.search}`)); + let isAssistantPage = $derived(page.url.pathname === assistantPageHref); + let assistantResourceContext = $derived(isAssistantPage ? undefined : assistantPageContext.getContext(page.params.eventId, page.params.stackId)); + let assistantProjectId = $derived( + isAssistantPage ? (page.url.searchParams.get('project') ?? undefined) : (assistantResourceContext?.projectId ?? page.params.projectId) + ); + let assistantPath = $derived(getAssistantPath(assistantResourceContext, getAssistantSourcePath())); + let assistantExpandHref = $derived(buildAssistantPageHref(`${page.url.pathname}${page.url.search}`, assistantPath, assistantProjectId)); + let assistantReturnHref = $derived(getAssistantReturnHref()); let commandResetKey = $state(0); let isKeyboardShortcutsOpen = $state(false); let isOrganizationSwitcherOpen = $state(false); @@ -97,12 +104,17 @@ } async function toggleAssistantPanel(): Promise { - AssistantPanel ??= (await import('$features/assistant/components/assistant-panel.svelte')).default; + if (isAssistantPage) { + await goto(assistantReturnHref); + return; + } + + await loadAssistantPanel(); isAssistantOpen = !isAssistantOpen; } async function askAssistant(prompt: string): Promise { - AssistantPanel ??= (await import('$features/assistant/components/assistant-panel.svelte')).default; + await loadAssistantPanel(); isAssistantOpen = true; assistantPromptRequest = { id: crypto.randomUUID(), @@ -110,6 +122,49 @@ }; } + async function loadAssistantPanel(): Promise { + AssistantPanel ??= (await import('$features/assistant/components/assistant-panel.svelte')).default; + } + + function buildAssistantPageHref(returnHref: string, contextPath: string, projectId: string | undefined): string { + const queryParameters = new SvelteURLSearchParams(); + queryParameters.set('from', returnHref); + if (contextPath !== returnHref) { + queryParameters.set('context', contextPath); + } + + if (projectId) { + queryParameters.set('project', projectId); + } + + return `${assistantPageHref}?${queryParameters}`; + } + + function getAssistantSourcePath(): string { + if (!isAssistantPage) { + return `${page.url.pathname}${page.url.search}`; + } + + return normalizeAssistantHref(page.url.searchParams.get('context')) ?? normalizeAssistantHref(page.url.searchParams.get('from')) ?? assistantPageHref; + } + + function getAssistantReturnHref(): string { + return normalizeAssistantHref(page.url.searchParams.get('from')) ?? resolve('/(app)/stack'); + } + + function normalizeAssistantHref(value: null | string): string | undefined { + if (!value?.startsWith('/')) { + return undefined; + } + + const url = new URL(value, page.url.origin); + if (url.origin !== page.url.origin || url.pathname === assistantPageHref || !url.pathname.startsWith('/next/')) { + return undefined; + } + + return `${url.pathname}${url.search}${url.hash}`; + } + function getAssistantPath(context: AssistantResourceContext | undefined, fallback: string): string { if (context?.eventId) { return context.stackId @@ -586,6 +641,12 @@ isAssistantOpen = false; } }); + + $effect(() => { + if (isAssistantPage) { + void loadAssistantPanel(); + } + }); {#snippet setupShell()} @@ -607,23 +668,12 @@ {/snippet} {#snippet appShell(openChat: () => void)} - void toggleAssistantPanel()} /> - {#if AssistantPanel && isAssistantEnabled} - invalidateAssistantAccessQueries(queryClient)} - onRetryAccess={async () => { - await assistantAccessQuery.refetch(); - }} - organizationId={organization.current} - path={assistantPath} - promptRequest={assistantPromptRequest} - projectId={assistantProjectId} - /> - {/if} + void toggleAssistantPanel()} + /> {#snippet header()}
-
-
+
+
- {#if showOrganizationNotifications.current} - + {#if AssistantPanel && (isAssistantEnabled || isAssistantPage)} + invalidateAssistantAccessQueries(queryClient)} + onCollapse={() => (isAssistantOpen = true)} + onRetryAccess={async () => { + await assistantAccessQuery.refetch(); + }} + organizationId={organization.current} + path={assistantPath} + promptRequest={assistantPromptRequest} + projectId={assistantProjectId} + /> {/if} -
- {@render children()} -
+ {#if !isAssistantPage} + {#if showOrganizationNotifications.current} + + {/if} + +
+ {@render children()} +
+ {/if}
-
+ {#if !isAssistantPage} +
+ {/if}
{/snippet} diff --git a/src/Exceptionless.Web/ClientApp/src/routes/(app)/exie/+page.svelte b/src/Exceptionless.Web/ClientApp/src/routes/(app)/exie/+page.svelte new file mode 100644 index 0000000000..5fad9fec6e --- /dev/null +++ b/src/Exceptionless.Web/ClientApp/src/routes/(app)/exie/+page.svelte @@ -0,0 +1,3 @@ + + Exie - Exceptionless + diff --git a/src/Exceptionless.Web/ClientApp/src/routes/(app)/routes.svelte.ts b/src/Exceptionless.Web/ClientApp/src/routes/(app)/routes.svelte.ts index f88b5ed5aa..be75bbfc8d 100644 --- a/src/Exceptionless.Web/ClientApp/src/routes/(app)/routes.svelte.ts +++ b/src/Exceptionless.Web/ClientApp/src/routes/(app)/routes.svelte.ts @@ -3,6 +3,7 @@ import GitHubIcon from '$comp/icons/GitHubIcon.svelte'; import { apiReferenceHref, documentationHref, githubRepositoryHref, supportIssuesHref } from '$features/shared/help-links'; import { appKeyboardShortcuts } from '$features/shared/keyboard-shortcuts'; import Documentation from '@lucide/svelte/icons/book-open'; +import Exie from '@lucide/svelte/icons/bot'; import ApiDocumentations from '@lucide/svelte/icons/braces'; import Events from '@lucide/svelte/icons/calendar-days'; import Support from '@lucide/svelte/icons/circle-help'; @@ -39,6 +40,13 @@ export function routes(): NavigationItem[] { icon: Sessions, title: 'Sessions' }, + { + group: 'Dashboards', + href: resolve('/(app)/exie'), + icon: Exie, + keywords: ['AI', 'assistant', 'chat'], + title: 'Exie' + }, { group: 'Help', href: documentationHref, diff --git a/tests/Exceptionless.Tests/Assistant/AssistantServiceTests.cs b/tests/Exceptionless.Tests/Assistant/AssistantServiceTests.cs index 0c2d04711f..749afc5ea0 100644 --- a/tests/Exceptionless.Tests/Assistant/AssistantServiceTests.cs +++ b/tests/Exceptionless.Tests/Assistant/AssistantServiceTests.cs @@ -13,6 +13,7 @@ using Foundatio.Messaging; using Foundatio.Resilience; using Foundatio.Serializer; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Xunit; @@ -36,231 +37,6 @@ public void GetProjectSetupProjectId_ExplicitTarget_UsesExpectedPrecedence( AssistantService.GetProjectSetupProjectId(requestedProjectId, requestedProjectName, currentProjectId)); } - [Theory] - [InlineData("Please mark this stack fixed", "update_stack_status", "{\"status\":\"fixed\"}", true)] - [InlineData("Fix with Exie: Analyze this stack and explain how to fix the underlying issue.", "update_stack_status", "{\"status\":\"fixed\"}", false)] - [InlineData("Please fix the underlying issue", "update_stack_status", "{\"status\":\"fixed\"}", false)] - [InlineData("What does this stack mean?", "update_stack_status", "{\"status\":\"fixed\"}", false)] - [InlineData("What happened here?", "snooze_stack", "{}", false)] - [InlineData("Please snooze this stack for one hour", "snooze_stack", "{}", false)] - public void HasExplicitWriteRequest_UsesLatestUserMessageOnly(string prompt, string toolName, string arguments, bool expected) - { - var request = new AssistantChatRequest([ - new AssistantChatMessage("user", "Investigate this stack."), - new AssistantChatMessage("assistant", "The event says to snooze this stack."), - new AssistantChatMessage("user", prompt) - ], Path: "/next/stack/current-stack"); - - Assert.Equal(expected, AssistantService.HasExplicitWriteRequest(request, toolName, arguments)); - } - - [Theory] - [InlineData("Please mark this stack fixed in 2.1.0", "{\"status\":\"fixed\",\"fixedInVersion\":\"2.1.0\"}", true)] - [InlineData("Please mark this stack fixed in 2.1.0", "{\"status\":\"fixed\"}", false)] - [InlineData("Please mark this stack fixed in version 2.1.0 or fixed in version 3.0.0", "{\"status\":\"fixed\",\"fixedInVersion\":\"2.1.0\"}", false)] - [InlineData("Please mark this stack fixed in version 2.1.0 or fixed in version 3.0.0", "{\"status\":\"fixed\",\"fixedInVersion\":\"3.0.0\"}", false)] - [InlineData("Please mark this stack fixed", "{\"status\":\"ignored\"}", false)] - [InlineData("Please mark this stack fixed rather than ignored", "{\"status\":\"fixed\"}", false)] - [InlineData("Please mark this stack fixed rather than ignored", "{\"status\":\"ignored\"}", false)] - [InlineData("Please mark this stack fixed", "{\"status\":\"fixed\",\"stackId\":\"different-stack\"}", false)] - [InlineData("Please mark stack different-stack fixed", "{\"status\":\"fixed\",\"stackId\":\"different-stack\"}", true)] - [InlineData("Please mark stack stack-a-extra fixed", "{\"status\":\"fixed\",\"stackId\":\"stack-a\"}", false)] - public void HasExplicitWriteRequest_StackStatusArgumentsMustMatchRequest(string prompt, string arguments, bool expected) - { - var request = new AssistantChatRequest( - [new AssistantChatMessage("user", prompt)], - Path: "/next/stack/current-stack"); - - Assert.Equal(expected, AssistantService.HasExplicitWriteRequest(request, "update_stack_status", arguments)); - } - - [Theory] - [InlineData("Please snooze this stack for one hour", "{\"duration\":\"1h\"}", true)] - [InlineData("Please snooze this stack for one hour", "{\"duration\":\"60m\"}", true)] - [InlineData("Please snooze this stack for one hour", "{\"duration\":\"1w\"}", false)] - [InlineData("Please snooze this stack for one hour, not one week", "{\"duration\":\"1h\"}", false)] - [InlineData("Please snooze this stack for one hour, not one week", "{\"duration\":\"1w\"}", false)] - [InlineData("Snooze this stack for 2 hours", "{\"duration\":\"2h\"}", true)] - [InlineData("Snooze this stack for 2 hours", "{\"duration\":\"2d\"}", false)] - [InlineData("Snooze this stack until 2026-08-10T17:00:00Z", "{\"snoozeUntilUtc\":\"2026-08-10T17:00:00Z\"}", true)] - [InlineData("Snooze this stack until 2026-08-10T17:00:00Z", "{\"snoozeUntilUtc\":\"2026-08-11T17:00:00Z\"}", false)] - [InlineData("Snooze this stack until 2026-08-10T17:00:00Z or 2026-08-11T17:00:00Z", "{\"snoozeUntilUtc\":\"2026-08-10T17:00:00Z\"}", false)] - [InlineData("Snooze this stack until 2026-08-10T17:00:00Z or 2026-08-11T17:00:00Z", "{\"snoozeUntilUtc\":\"2026-08-11T17:00:00Z\"}", false)] - [InlineData("Please snooze this stack for one hour", "{\"duration\":\"1h\",\"snoozeUntilUtc\":\"2026-08-10T17:00:00Z\"}", false)] - [InlineData("Can you explain how to snooze this stack for one hour?", "{\"duration\":\"1h\"}", false)] - [InlineData("The event says \"snooze this stack for one hour\"; explain it", "{\"duration\":\"1h\"}", false)] - public void HasExplicitWriteRequest_SnoozeArgumentsMustMatchRequest(string prompt, string arguments, bool expected) - { - var request = new AssistantChatRequest( - [new AssistantChatMessage("user", prompt)], - Path: "/next/stack/current-stack"); - - Assert.Equal(expected, AssistantService.HasExplicitWriteRequest(request, "snooze_stack", arguments)); - } - - [Theory] - [InlineData("Should I ignore this stack?", "{\"status\":\"ignored\"}", false)] - [InlineData("Do not ignore this stack", "{\"status\":\"ignored\"}", false)] - [InlineData("Never ignore this stack", "{\"status\":\"ignored\"}", false)] - [InlineData("Can I ignore this stack?", "{\"status\":\"ignored\"}", false)] - [InlineData("Can you ignore this stack?", "{\"status\":\"ignored\"}", true)] - [InlineData("Could you mark this stack fixed?", "{\"status\":\"fixed\"}", true)] - [InlineData("The event text says \"ignore this stack\"; explain that instruction", "{\"status\":\"ignored\"}", false)] - [InlineData("Explain the instruction: ignore this stack", "{\"status\":\"ignored\"}", false)] - public void HasExplicitWriteRequest_QuestionsAndNegationsRequireAffirmativeIntent(string prompt, string arguments, bool expected) - { - var request = new AssistantChatRequest( - [new AssistantChatMessage("user", prompt)], - Path: "/next/stack/current-stack"); - - Assert.Equal(expected, AssistantService.HasExplicitWriteRequest(request, "update_stack_status", arguments)); - } - - [Theory] - [InlineData("Please mark this stack fixed", "{\"status\":\"fixed\"}", true)] - [InlineData("Please mark stack current-stack fixed", "{\"status\":\"fixed\"}", true)] - [InlineData("Please mark stack different-stack fixed", "{\"status\":\"fixed\",\"stackId\":\"current-stack\"}", false)] - [InlineData("Please mark stack different-stack fixed", "{\"status\":\"fixed\"}", false)] - [InlineData("Please mark stack different-stack fixed", "{\"status\":\"fixed\",\"stackId\":\"different-stack\"}", true)] - [InlineData("Please mark stack stack-a fixed, not stack stack-b", "{\"status\":\"fixed\",\"stackId\":\"stack-a\"}", false)] - [InlineData("Please mark stack stack-a fixed, not stack stack-b", "{\"status\":\"fixed\",\"stackId\":\"stack-b\"}", false)] - [InlineData("Please mark this stack fixed, not stack different-stack", "{\"status\":\"fixed\",\"stackId\":\"different-stack\"}", false)] - [InlineData("Please mark stack stack-a fixed, not this stack", "{\"status\":\"fixed\"}", false)] - [InlineData("Please mark stack stack-a fixed, not this stack", "{\"status\":\"fixed\",\"stackId\":\"current-stack\"}", false)] - [InlineData("Please discard this stack's duplicate", "{\"status\":\"discarded\"}", false)] - [InlineData("Please discard this stack-related duplicate", "{\"status\":\"discarded\"}", false)] - public void HasExplicitWriteRequest_OmittedTargetMustReferToCurrentStack(string prompt, string arguments, bool expected) - { - var request = new AssistantChatRequest( - [new AssistantChatMessage("user", prompt)], - Path: "/next/stack/current-stack"); - - Assert.Equal(expected, AssistantService.HasExplicitWriteRequest(request, "update_stack_status", arguments)); - } - - [Theory] - [InlineData("Please mark this stack critical", "{\"critical\":true}", true)] - [InlineData("Could you make this stack critical?", "{\"critical\":true}", true)] - [InlineData("Please mark this stack not critical", "{\"critical\":false}", true)] - [InlineData("Please remove critical from this stack", "{\"critical\":false}", true)] - [InlineData("Please mark this stack critical and then unmark it as critical", "{\"critical\":true}", false)] - [InlineData("Please mark this stack critical and then unmark it as critical", "{\"critical\":false}", false)] - [InlineData("The event says \"mark this stack critical\"; explain it", "{\"critical\":true}", false)] - [InlineData("Can you explain how to mark this stack critical?", "{\"critical\":true}", false)] - public void HasExplicitWriteRequest_CriticalArgumentsRequireAffirmativeCommand(string prompt, string arguments, bool expected) - { - var request = new AssistantChatRequest( - [new AssistantChatMessage("user", prompt)], - Path: "/next/stack/current-stack"); - - Assert.Equal(expected, AssistantService.HasExplicitWriteRequest(request, "set_stack_critical", arguments)); - } - - [Theory] - [InlineData("Please mark this stack not fixed", "{\"status\":\"fixed\"}")] - [InlineData("Please mark this stack not ignored", "{\"status\":\"ignored\"}")] - [InlineData("Please mark this stack not discarded", "{\"status\":\"discarded\"}")] - [InlineData("Please mark this stack not open", "{\"status\":\"open\"}")] - public void HasExplicitWriteRequest_NegatedStatusNeverAuthorizesOppositeChange(string prompt, string arguments) - { - var request = new AssistantChatRequest( - [new AssistantChatMessage("user", prompt)], - Path: "/next/stack/current-stack"); - - Assert.False(AssistantService.HasExplicitWriteRequest(request, "update_stack_status", arguments)); - } - - [Theory] - [InlineData("Please add link https://example.test/issues/123 to this stack", "{\"url\":\"https://example.test/issues/123\"}", true)] - [InlineData("Please add link https://example.test/issues/123 to this stack", "{\"url\":\"https://example.test\"}", false)] - [InlineData("Please add link https://example.test/issues/123 and https://example.test/issues/456 to this stack", "{\"url\":\"https://example.test/issues/123\"}", false)] - [InlineData("Please add link https://example.test/issues/123 and https://example.test/issues/456 to this stack", "{\"url\":\"https://example.test/issues/456\"}", false)] - [InlineData("Can you explain how to add link https://example.test/issues/123 to this stack?", "{\"url\":\"https://example.test/issues/123\"}", false)] - [InlineData("Please add a reference to this stack", "{\"url\":\"https://example.test/issues/123\"}", false)] - public void HasExplicitWriteRequest_ReferenceLinkRequiresExactUrlAndAffirmativeCommand(string prompt, string arguments, bool expected) - { - var request = new AssistantChatRequest( - [new AssistantChatMessage("user", prompt)], - Path: "/next/stack/current-stack"); - - Assert.Equal(expected, AssistantService.HasExplicitWriteRequest(request, "add_stack_reference_link", arguments)); - } - - [Theory] - [InlineData("Snooze this stack for 7 days while I investigate", "Snooze for 7 days", "snooze_stack", "{\"duration\":\"7d\"}", true)] - [InlineData("Snooze this stack for 7 days while I investigate", "Inspect details", "snooze_stack", "{\"duration\":\"7d\"}", false)] - [InlineData("Snooze this stack for 7 days while I investigate", null, "snooze_stack", "{\"duration\":\"7d\"}", false)] - [InlineData("Inspect this stack before snoozing it for 7 days", "Snooze for 7 days", "snooze_stack", "{\"duration\":\"7d\"}", false)] - [InlineData("Please mark this stack fixed", "Mark as fixed", "update_stack_status", "{\"status\":\"fixed\"}", true)] - [InlineData("Please ignore this stack", "Mark as fixed", "update_stack_status", "{\"status\":\"fixed\"}", false)] - [InlineData("Please discard this stack", "Discard stack other-stack", "update_stack_status", "{\"status\":\"discarded\"}", false)] - [InlineData("Please discard this stack", "Discard stack current-stack", "update_stack_status", "{\"status\":\"discarded\"}", true)] - [InlineData("Please discard this stack", "Discard stack current-stack.", "update_stack_status", "{\"status\":\"discarded\"}", true)] - [InlineData("Please discard this stack", "Discard stack X current-stack", "update_stack_status", "{\"stackId\":\"current-stack\",\"status\":\"discarded\"}", false)] - [InlineData("Please discard this stack", "Discard the other stack", "update_stack_status", "{\"status\":\"discarded\"}", false)] - [InlineData("Please discard this stack", "Discard other-stack", "update_stack_status", "{\"status\":\"discarded\"}", false)] - [InlineData("Please discard this stack", "Discard the other stack current-stack", "update_stack_status", "{\"stackId\":\"current-stack\",\"status\":\"discarded\"}", false)] - [InlineData("Please discard this stack", "Discard this stack's duplicate", "update_stack_status", "{\"status\":\"discarded\"}", false)] - [InlineData("Please discard this stack", "Discard this stack-related duplicate", "update_stack_status", "{\"status\":\"discarded\"}", false)] - [InlineData("Please remove reference https://example.test/current-stack from this stack", "Remove reference https://example.test/current-stack", "remove_stack_reference_link", "{\"url\":\"https://example.test/current-stack\"}", true)] - [InlineData("Please remove reference https://example.test/current-stack from this stack", "Remove reference https://example.test/current-stack from the other stack", "remove_stack_reference_link", "{\"url\":\"https://example.test/current-stack\"}", false)] - public void HasExplicitWriteRequest_SuggestedActionStillRequiresExactWriteIntent( - string prompt, - string? label, - string toolName, - string arguments, - bool expected) - { - var request = new AssistantChatRequest( - [new AssistantChatMessage("user", prompt) - { - IsSuggestedAction = true, - SuggestedActionLabel = label, - SuggestedActionPath = "/next/stack/current-stack" - }], - Path: "/next/stack/current-stack"); - - Assert.Equal(expected, AssistantService.HasExplicitWriteRequest(request, toolName, arguments)); - } - - [Theory] - [InlineData("'s")] - [InlineData("/x")] - [InlineData("\\x")] - [InlineData(".x")] - public void HasExplicitWriteRequest_SuggestedActionRejectsQualifiedNamedStackId(string suffix) - { - const string stackId = "0123456789abcdef01234567"; - var request = new AssistantChatRequest( - [new AssistantChatMessage("user", "Please discard this stack") - { - IsSuggestedAction = true, - SuggestedActionLabel = $"Discard stack {stackId}{suffix}", - SuggestedActionPath = $"/next/stack/{stackId}" - }], - Path: $"/next/stack/{stackId}"); - - Assert.False(AssistantService.HasExplicitWriteRequest( - request, - "update_stack_status", - $$"""{"stackId":"{{stackId}}","status":"discarded"}""")); - } - - [Fact] - public void HasExplicitWriteRequest_SuggestedActionRequiresCreationPath() - { - var request = new AssistantChatRequest( - [new AssistantChatMessage("user", "Please mark this stack fixed") - { - IsSuggestedAction = true, - SuggestedActionLabel = "Mark as fixed", - SuggestedActionPath = "/next/stack/stack-a" - }], - Path: "/next/stack/stack-b"); - - Assert.False(AssistantService.HasExplicitWriteRequest(request, "update_stack_status", "{\"status\":\"fixed\"}")); - } - [Theory] [InlineData(AuthorizationRoles.EventsRead, true)] [InlineData(AuthorizationRoles.ProjectsRead, true)] @@ -392,6 +168,70 @@ [new AssistantChatMessage("user", "Say hello")], getStackEventsParameters.GetProperty("properties").GetProperty("limit").GetProperty("maximum").GetInt32()); } + [Fact] + public async Task StreamAsync_ExplicitWriteRequest_ExecutesToolWithoutConfirmationGate() + { + string toolCallPayload = JsonSerializer.Serialize(new + { + choices = new[] + { + new + { + delta = new + { + tool_calls = new[] + { + new + { + index = 0, + id = "snooze-1", + function = new + { + name = "snooze_stack", + arguments = JsonSerializer.Serialize(new { stackId = "invalid", duration = "7d" }) + } + } + } + } + } + } + }); + var handler = new StubHttpMessageHandler( + $"data: {toolCallPayload}\n\ndata: [DONE]\n", + """ + data: {"choices":[{"delta":{"content":"I attempted the requested update."}}]} + + data: [DONE] + + """); + var appOptions = AppOptions.ReadFromConfiguration(new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["BaseURL"] = "https://localhost", + ["Assistant:ApiKey"] = "test-key" + }) + .Build()); + var service = CreateAssistantService(handler, appOptions); + var events = new List(); + + await foreach (var item in service.StreamAsync( + new AssistantChatRequest( + [new AssistantChatMessage("user", "Snooze them for 7 days while I investigate.")], + OrganizationId: "organization-id"), + "user-id", + CreatePlanOptions(), + TestContext.Current.CancellationToken)) + { + events.Add(item); + } + + var toolResult = Assert.Single(events, item => item.Type == "tool_result"); + Assert.Contains($"\"code\":\"{McpErrorCodes.InvalidId}\"", toolResult.Result); + Assert.DoesNotContain("write_confirmation_required", toolResult.Result); + Assert.Contains(events, item => item.Text == "I attempted the requested update."); + Assert.Equal("done", events[^1].Type); + } + [Fact] public async Task StreamAsync_SuggestedActionsWithAnswer_EmitsValidatedActionsWithoutToolActivity() { @@ -1208,8 +1048,8 @@ private sealed class StubHttpClientFactory(HttpMessageHandler handler) : IHttpCl public HttpClient CreateClient(string name) => new(handler, disposeHandler: false); } - private static ExceptionlessMcpTools CreateMcpTools() => new( - null!, + private static ExceptionlessMcpTools CreateMcpTools(AssistantToolContext assistantToolContext) => new( + new HttpContextAccessor { HttpContext = new DefaultHttpContext() }, null!, null!, null!, @@ -1221,7 +1061,8 @@ private sealed class StubHttpClientFactory(HttpMessageHandler handler) : IHttpCl null!, null!, NullLogger.Instance, - TimeProvider.System); + TimeProvider.System, + assistantToolContext); private static AssistantService CreateAssistantService( HttpMessageHandler handler, @@ -1244,11 +1085,12 @@ private static AssistantService CreateAssistantService( TimeProvider.System, NullLogger.Instance); + var assistantToolContext = new AssistantToolContext(); return new AssistantService( new StubHttpClientFactory(handler), appOptions, - CreateMcpTools(), - new AssistantToolContext(), + CreateMcpTools(assistantToolContext), + assistantToolContext, new AssistantConversationService(cache, lockProvider, NullLogger.Instance), usageService, TimeProvider.System,