diff --git a/CHANGELOG.md b/CHANGELOG.md index c0d42233..4ba4f543 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,15 @@ Nightly builds of `master` are on second period, so the readable 500 opencode answers handler defects with reads "… Check server logs for details." instead of ending in "..". +### 📚 Documentation + +- HQ's redesigned board and session screens show named asks, edit previews, rendered Markdown and + coloured diffs, with Changes and Terminal tabs and an SDK calls dock remembered across reloads. + Permission asks offer Deny, Allow always and Allow once; questions can be submitted or dismissed, + and a running turn can be stopped. Session titles follow later renames, and untitled rows stay + clickable. A session's asks are listed again when its page opens and when one of its turns ends, + so an ask a stopped turn dropped no longer stays on the board. + ## [2.0.1] - 2026-11-22 **`2.0.1` pins opencode `2.3.2`.** It is a patch that moves the protocol pin, so generated types diff --git a/Directory.Packages.props b/Directory.Packages.props index fad73d13..46279aac 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,6 +1,7 @@ + diff --git a/playground/hq/OpenCode.Playground.Hq/Components/App.razor b/playground/hq/OpenCode.Playground.Hq/Components/App.razor index ad13aba4..3b83230d 100644 --- a/playground/hq/OpenCode.Playground.Hq/Components/App.razor +++ b/playground/hq/OpenCode.Playground.Hq/Components/App.razor @@ -2,6 +2,7 @@ + diff --git a/playground/hq/OpenCode.Playground.Hq/Components/MainLayout.razor b/playground/hq/OpenCode.Playground.Hq/Components/MainLayout.razor index 7a9affb0..aa8b4224 100644 --- a/playground/hq/OpenCode.Playground.Hq/Components/MainLayout.razor +++ b/playground/hq/OpenCode.Playground.Hq/Components/MainLayout.razor @@ -1,9 +1,15 @@ @inherits LayoutComponentBase @inject SessionBoard Board +@inject PanelState Panel +@inject Microsoft.JSInterop.IJSRuntime JS +@inject ILogger Logger +
-
OpenCode HQ
-
@(Board.Connected ? "connected" : "not connected")
- New session + OpenCode HQ + @(Board.Connected ? "Connected" : "Not connected") + + New session
@Body +
diff --git a/playground/hq/OpenCode.Playground.Hq/Components/MainLayout.razor.cs b/playground/hq/OpenCode.Playground.Hq/Components/MainLayout.razor.cs index 410af694..062863b9 100644 --- a/playground/hq/OpenCode.Playground.Hq/Components/MainLayout.razor.cs +++ b/playground/hq/OpenCode.Playground.Hq/Components/MainLayout.razor.cs @@ -1,13 +1,62 @@ +using Microsoft.JSInterop; + namespace OpenCode.Playground.Hq.Components; /// Every screen's header: the connection and a way to start a session. public sealed partial class MainLayout : IDisposable { /// - public void Dispose() => Board.Changed -= OnChanged; + public void Dispose() + { + Board.Changed -= OnChanged; + Panel.Changed -= OnPanelChanged; + } + + /// + protected override void OnInitialized() + { + Board.Changed += OnChanged; + Panel.Changed += OnPanelChanged; + } /// - protected override void OnInitialized() => Board.Changed += OnChanged; + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) + { + return; + } + + try + { + var stored = await JS.InvokeAsync("localStorage.getItem", "hq.sdk-calls.open"); + if (stored == "true" && !Panel.Open) + { + Panel.Toggle(); + } + } + catch (JSException exception) + { + Logger.LogWarning(exception, "Could not read the SDK calls dock preference."); + } + } + + private void OnPanelChanged(object? sender, EventArgs args) + { + // The renderer owns this work and reports render faults; storage failures are logged here. + _ = InvokeAsync(async () => + { + StateHasChanged(); + try + { + await JS.InvokeVoidAsync("localStorage.setItem", "hq.sdk-calls.open", Panel.Open ? "true" : "false"); + } + catch (JSException exception) + { + Logger.LogWarning(exception, "Could not remember the SDK calls dock preference."); + } + }); + } private void OnChanged(object? sender, EventArgs args) { diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionConversation.cs b/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionConversation.cs index 1e20a31f..8964eb42 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionConversation.cs +++ b/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionConversation.cs @@ -21,6 +21,21 @@ internal sealed class SessionConversation(OpenCodeClient client, ILoggerSubscribes before loading history, then follows the session until cancelled. public async Task FollowAsync(string sessionId, CancellationToken cancellationToken) { diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionScreen.razor b/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionScreen.razor index e02e8418..06cdef0a 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionScreen.razor +++ b/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionScreen.razor @@ -3,61 +3,103 @@ @inject SessionBoard Board @inject ILogger Logger -Session -
-
-

Back to HQ

- -@if (Conversation.LastError is { } error) -{ -

@error

-} -@if (Board.LastError is { } boardError) -{ -

@boardError

-} -@if (_followLost) -{ -

Lost the connection to HQ's server. Reload the page to follow this session again.

-} - - @foreach (var line in Conversation.Lines) - { -
@line.Author@line.Text
- } - @if (Conversation.Running) - { -

Working...

- } - - @foreach (var item in Board.NeedsYou.Where(item => item.SessionId == SessionId)) - { - @if (item.Form is not null) +@Title +
+
+

@Title

+

+ @if (Board.Find(SessionId)?.Location.Directory is { } directory) + { + @SessionsScreen.FolderName(directory) + } + @switch (Board.StatusOf(SessionId)) + { + case "waiting for you": + Waiting for you + break; + case "running": + Running + break; + default: + Idle + break; + } +

+
+
+ @if (Conversation.LastError is { } error) { - +

@error

} - else + @if (Board.LastError is { } boardError) { -
-
Permission
@item.Title
- - -
+

@boardError

} - } - -
- - -
- + @if (_followLost) + { +

Lost the connection to HQ's server. Reload the page to follow this session again.

+ } +
+ @foreach (var line in Conversation.Lines) + { + @if (line.Author == "you") + { +
You: @line.Text
+ } + else + { +
Agent:
@Rendered(line.Text)
+ } + } +
+ @if (Conversation.Running) + { +

Working

+ } + @if (Board.NeedsYou.Any(item => item.SessionId == SessionId)) + { +
+

Needs you

+ @foreach (var item in Board.NeedsYou.Where(item => item.SessionId == SessionId)) + { + @if (item.Form is not null) + { + + } + else + { + + } + } +
+ } +
+ + + @if (Conversation.Running) + { + + } + else + { + + } +
+
+
-
-@if (Conversation.Ready) -{ - -} - -
-
diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionScreen.razor.cs b/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionScreen.razor.cs index bbbea72e..56f8f02c 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionScreen.razor.cs +++ b/playground/hq/OpenCode.Playground.Hq/Features/Conversation/SessionScreen.razor.cs @@ -1,15 +1,19 @@ +using Markdig; using Microsoft.AspNetCore.Components; -using OpenCode.Playground.Hq.Features.Sessions; -using OpenCode.Sdk.Models; namespace OpenCode.Playground.Hq.Features.Conversation; /// One session's conversation, asks, prompt box and changed files. public sealed partial class SessionScreen : IDisposable { + private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder().DisableHtml().Build(); + internal static MarkupString Rendered(string text) => new(Markdown.ToHtml(text, Pipeline)); private readonly CancellationTokenSource _lifetime = new(); private string _prompt = ""; private bool _followLost; + private bool _terminalTab; + private int _changeCount; + private string Title => Board.Find(SessionId)?.Title is { Length: > 0 } title ? title : "Untitled session"; /// Gets or sets the session shown. [Parameter] @@ -32,8 +36,14 @@ protected override void OnInitialized() // The screen owns this follow: it ends with _lifetime, and its faults reach FollowFaulted. _ = Conversation.FollowAsync(SessionId, _lifetime.Token).ContinueWith( FollowFaulted, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); + // As upstream's session page does when it opens, the asks shown are the ones the server still lists. + _ = Board.ResyncAsync(SessionId, _lifetime.Token).ContinueWith( + ResyncFaulted, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); } + private void ResyncFaulted(Task resync) => + Logger.LogWarning(resync.Exception, "Could not list the asks of session {SessionId}.", SessionId); + private void OnChanged(object? sender, EventArgs args) { // The renderer owns this work: a render failure reaches its own error handling, which logs it. @@ -58,5 +68,5 @@ private async Task SendAsync() } } - private Task AnswerAsync(NeedsYouItem item, PermissionReply decision) => Board.AnswerAsync(item, decision, _lifetime.Token); + private Task StopAsync() => Conversation.StopAsync(_lifetime.Token); } diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Files/ChangedFiles.razor b/playground/hq/OpenCode.Playground.Hq/Features/Files/ChangedFiles.razor index fd9c4e77..9e9b64b7 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Files/ChangedFiles.razor +++ b/playground/hq/OpenCode.Playground.Hq/Features/Files/ChangedFiles.razor @@ -5,15 +5,19 @@ {

Changed files are unavailable: @error

} -else if (_loaded) +else if (_diffs.Count == 0) +{ +

Nothing changed in the last turn.

+} +else {
-

Changed in the last turn (@_diffs.Count)

+

Changed in the last turn

@foreach (var diff in _diffs) { -
- @diff.File +@diff.Additions -@diff.Deletions -
@diff.Patch
+
+ @diff.File+@diff.Additions−@diff.Deletions +
}
@@ -38,6 +42,10 @@ else if (_loaded) [Parameter] public bool Running { get; set; } + /// Gets or sets the callback for the Changes tab's count. + [Parameter] + public EventCallback CountChanged { get; set; } + /// protected override async Task OnParametersSetAsync() { @@ -55,6 +63,7 @@ else if (_loaded) _diffs = (await Client.Sessions.GetSessionClient(SessionId).GetDiffAsync()).Diffs; #endregion _error = null; + await CountChanged.InvokeAsync(_diffs.Count); } catch (OpenCodeException exception) { diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Files/DiffView.razor b/playground/hq/OpenCode.Playground.Hq/Features/Files/DiffView.razor new file mode 100644 index 00000000..690ec855 --- /dev/null +++ b/playground/hq/OpenCode.Playground.Hq/Features/Files/DiffView.razor @@ -0,0 +1,25 @@ +@{ var inHunk = false; } +
@foreach (var line in Patch.ReplaceLineEndings("\n").TrimEnd('\n').Split('\n')) + { + var hunk = line.StartsWith("@@", StringComparison.Ordinal); + inHunk |= hunk; + var kind = line switch + { + _ when hunk => "hunk", + _ when !inHunk => "meta", + _ when line.StartsWith('+') => "add", + _ when line.StartsWith('-') => "del", + _ => null, + }; +
@line
+ }
+ +@code { + /// Gets or sets the patch to display. + [Parameter] + public string Patch { get; set; } = ""; + + /// Gets or sets the accessible name of the patch. + [Parameter] + public string Label { get; set; } = ""; +} diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormCard.razor b/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormCard.razor index c3eeb7f7..fb60c5f7 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormCard.razor +++ b/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormCard.razor @@ -1,10 +1,20 @@ @inject SessionBoard Board -
-
-
Question
-
@_draft.Form.Title
-
+
+
+ @if (ShowSession) + { +

@(Board.Find(Form.SessionId)?.Title is { Length: > 0 } title ? title : "Untitled session")

+ } + else + { +

@Form.Title

+ } +

@Form.Title@if (Board.Find(Form.SessionId)?.Location.Directory is { } directory) + { + in @SessionsScreen.FolderName(directory) + }

+
@if (!_draft.Answerable) {

Answer this form in opencode: HQ answers text and choice questions only.

@@ -16,29 +26,64 @@ @switch (field) { case FormStringField text: -
- @(text.Title ?? text.Key) - @foreach (var option in text.Options ?? []) +
+ @if (text.Options is { Count: > 0 }) { - + @(text.Title ?? text.Key) } + @if (text.Description is { } description) + { +

@description

+ } +
+ @foreach (var option in text.Options ?? []) + { + + } +
@if (FormDraft.ShowsTextBox(text)) { - + } -
+ break; case FormMultiselectField multi: -
- @(multi.Title ?? multi.Key) - @foreach (var option in multi.Options) +
+ @(multi.Title ?? multi.Key) + @if (multi.Description is { } multiDescription) { - +

@multiDescription

} -
+
+ @foreach (var option in multi.Options) + { + + } +
+ break; } } - } -
+
+ @if (_draft.Answerable) + { + + } + +
+ diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormCard.razor.cs b/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormCard.razor.cs index bb12a5d2..bf5e8d45 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormCard.razor.cs +++ b/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormCard.razor.cs @@ -15,6 +15,10 @@ public sealed partial class FormCard : IDisposable [Parameter] public FormInfo Form { get; set; } = null!; + /// Gets or sets whether the heading links to the session. + [Parameter] + public bool ShowSession { get; set; } + /// public void Dispose() { @@ -26,4 +30,5 @@ public void Dispose() protected override void OnParametersSet() => _draft ??= new FormDraft(Form); private Task AnswerAsync() => Board.AnswerFormAsync(Form, _draft.ToReply(), _lifetime.Token); + private Task DismissAsync() => Board.DismissFormAsync(Form, _lifetime.Token); } diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormDraft.cs b/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormDraft.cs index 147030a7..babcc4a5 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormDraft.cs +++ b/playground/hq/OpenCode.Playground.Hq/Features/Forms/FormDraft.cs @@ -12,7 +12,9 @@ internal sealed class FormDraft(FormInfo form) public bool Answerable => form.Fields.All(static item => item is FormStringField or FormMultiselectField); public static bool ShowsTextBox(FormStringField field) => field.Options is null or { Count: 0 } || field.Custom == true; public string TextOf(string key) => _texts.GetValueOrDefault(key, string.Empty); - public string TextClass(string key, string value) => TextOf(key) == value ? "chosen" : string.Empty; + public bool IsText(string key, string value) => TextOf(key) == value; + public string CustomTextOf(FormStringField field) => + field.Options?.Any(option => IsText(field.Key, option.Value)) == true ? string.Empty : TextOf(field.Key); public bool IsChosen(string key, string value) => _choices.TryGetValue(key, out var chosen) && chosen.Contains(value); public void SetText(string key, string? text) => _texts[key] = text ?? string.Empty; diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Panel/PanelEntry.cs b/playground/hq/OpenCode.Playground.Hq/Features/Panel/PanelEntry.cs index 509296cd..a20c9e54 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Panel/PanelEntry.cs +++ b/playground/hq/OpenCode.Playground.Hq/Features/Panel/PanelEntry.cs @@ -1,6 +1,6 @@ namespace OpenCode.Playground.Hq.Features.Panel; -/// One item of the "How this screen works" panel. +/// One item of the SDK calls dock. /// What the code shows. /// The file, under the project. /// The marked region in that file. @@ -13,6 +13,7 @@ public sealed record PanelEntry(string Title, string File, string Region) new("\"Needs you\" is a typed event", "Features/Sessions/SessionBoard.cs", "asks"), new("Answering a permission", "Features/Sessions/SessionBoard.cs", "reply"), new("Answering a question", "Features/Sessions/SessionBoard.cs", "form-reply"), + new("Dismissing a question", "Features/Sessions/SessionBoard.cs", "form-dismiss"), ]; /// Gets the session screen's panel. @@ -20,6 +21,10 @@ public sealed record PanelEntry(string Title, string File, string Region) [ new("History, then the live answer", "Features/Conversation/SessionConversation.cs", "follow"), new("Sending a prompt", "Features/Conversation/SessionConversation.cs", "prompt"), + new("Stopping a turn", "Features/Conversation/SessionConversation.cs", "stop"), + new("Answering a permission", "Features/Sessions/SessionBoard.cs", "reply"), + new("Answering a question", "Features/Sessions/SessionBoard.cs", "form-reply"), + new("Dismissing a question", "Features/Sessions/SessionBoard.cs", "form-dismiss"), new("Changed files", "Features/Files/ChangedFiles.razor", "diff"), new("A terminal in the session's folder", "Features/Terminal/SessionTerminal.cs", "terminal"), ]; diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Panel/PanelState.cs b/playground/hq/OpenCode.Playground.Hq/Features/Panel/PanelState.cs new file mode 100644 index 00000000..7deee84b --- /dev/null +++ b/playground/hq/OpenCode.Playground.Hq/Features/Panel/PanelState.cs @@ -0,0 +1,14 @@ +namespace OpenCode.Playground.Hq.Features.Panel; + +/// One circuit's choice to show the SDK calls dock. +internal sealed class PanelState +{ + public event EventHandler? Changed; + public bool Open { get; private set; } + + public void Toggle() + { + Open = !Open; + Changed?.Invoke(this, EventArgs.Empty); + } +} diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Panel/SdkPanel.razor b/playground/hq/OpenCode.Playground.Hq/Features/Panel/SdkPanel.razor index 51aa5957..9d8a7ab1 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Panel/SdkPanel.razor +++ b/playground/hq/OpenCode.Playground.Hq/Features/Panel/SdkPanel.razor @@ -1,27 +1,37 @@ @inject SourceSnippets Source +@inject PanelState Panel +@implements IDisposable - +@if (Panel.Open) +{ + +} @code { - private bool _hidden; - private readonly List<(PanelEntry Entry, string Code)> _items = []; + private readonly List<(PanelEntry Entry, SourceSnippets.Snippet Snippet)> _items = []; /// Gets or sets the code this screen shows. [Parameter] @@ -34,9 +44,19 @@ /// protected override async Task OnInitializedAsync() { + Panel.Changed += OnChanged; foreach (var entry in Entries) { _items.Add((entry, await Source.ReadAsync(entry.File, entry.Region))); } } + + /// + public void Dispose() => Panel.Changed -= OnChanged; + + private void OnChanged(object? sender, EventArgs args) + { + // The renderer owns this work and reports render failures. + _ = InvokeAsync(StateHasChanged); + } } diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Panel/SourceSnippets.cs b/playground/hq/OpenCode.Playground.Hq/Features/Panel/SourceSnippets.cs index 726417f7..f0ad3781 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Panel/SourceSnippets.cs +++ b/playground/hq/OpenCode.Playground.Hq/Features/Panel/SourceSnippets.cs @@ -9,7 +9,7 @@ internal sealed class SourceSnippets public static Uri Link(string file) => new(RepositoryFolder + file); /// Reads one region without its markers or common indentation. - public async Task ReadAsync(string file, string region) + public async Task ReadAsync(string file, string region) { var name = _assembly.GetManifestResourceNames().SingleOrDefault(name => name.Replace('\\', '/') == "hq/" + file) ?? throw new InvalidOperationException($"{file} is not embedded."); @@ -26,6 +26,8 @@ public async Task ReadAsync(string file, string region) var body = lines[(start + 1)..end]; var indent = body.Where(static line => line.Trim().Length > 0).Min(static line => line.Length - line.TrimStart().Length); - return string.Join('\n', body.Select(line => line.Length >= indent ? line[indent..] : line.TrimStart())); + return new Snippet(string.Join('\n', body.Select(line => line.Length >= indent ? line[indent..] : line.TrimStart())), start + 2); } + + internal sealed record Snippet(string Code, int FirstLine); } diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/NeedsYouItem.cs b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/NeedsYouItem.cs index 846b2da2..82241000 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/NeedsYouItem.cs +++ b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/NeedsYouItem.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using OpenCode.Sdk.Models; namespace OpenCode.Playground.Hq.Features.Sessions; @@ -7,13 +8,70 @@ namespace OpenCode.Playground.Hq.Features.Sessions; /// The session that asks. /// What it asks. /// The form, when this is one. -internal sealed record NeedsYouItem(string Id, string SessionId, string Title, FormInfo? Form = null) +public sealed record NeedsYouItem(string Id, string SessionId, string Title, FormInfo? Form = null) { - public static NeedsYouItem FromPermission(PermissionRequest ask) => - new(ask.Id, ask.SessionId, $"{ask.Action}: {string.Join(", ", ask.Resources)}"); + /// Gets the permission action as sent by the server. + public string? Action { get; init; } + /// Gets the resources awaiting approval. + public IReadOnlyList Resources { get; init; } = []; + /// Gets the server's explanation. + public string? Message { get; init; } + /// Gets the tool input and any proposed edit metadata. + public IReadOnlyDictionary? Metadata { get; init; } + /// Gets proposed edits whose metadata includes both a file and a patch. + public IReadOnlyList> PreviewFiles + { + get + { + if (Metadata?.TryGetValue("files", out var files) != true || files.ValueKind != JsonValueKind.Array) + { + return []; + } - public static NeedsYouItem FromAsked(PermissionAskedData ask) => - new(ask.Id, ask.SessionId, $"{ask.Action}: {string.Join(", ", ask.Resources)}"); + return [.. files.EnumerateArray() + .Where(static entry => entry.ValueKind == JsonValueKind.Object + && entry.TryGetProperty("file", out var file) && file.ValueKind == JsonValueKind.String + && entry.TryGetProperty("patch", out var patch) && patch.ValueKind == JsonValueKind.String) + // The filter admits string properties only, so GetString cannot return null. + .Select(static entry => KeyValuePair.Create(entry.GetProperty("file").GetString()!, entry.GetProperty("patch").GetString()!))]; + } + } + internal static string? KindFor(string action) => action switch + { + "read" => "Reading a file (matches the file path)", + "edit" => "Modify files, including edits, writes, and patches", + "glob" => "Match files using glob patterns", + "grep" => "Search file contents using regular expressions", + "list" => "List files within a directory", + "bash" => "Run shell commands", + "task" => "Launch sub-agents", + "skill" => "Load a skill by name", + "lsp" => "Run language server queries", + "todowrite" => "Update the todo list", + "webfetch" => "Fetch content from a URL", + "websearch" => "Search the web", + "external_directory" => "Access files outside the project directory", + "doom_loop" => "Detect repeated tool calls with identical input", + _ => null, + }; - public static NeedsYouItem FromForm(FormInfo form) => new(form.Id, form.SessionId, form.Title, form); + internal static NeedsYouItem FromPermission(PermissionRequest ask) => + new(ask.Id, ask.SessionId, $"{ask.Action}: {string.Join(", ", ask.Resources)}") + { + Action = ask.Action, + Resources = ask.Resources, + Message = ask.Message, + Metadata = ask.Metadata, + }; + + internal static NeedsYouItem FromAsked(PermissionAskedData ask) => + new(ask.Id, ask.SessionId, $"{ask.Action}: {string.Join(", ", ask.Resources)}") + { + Action = ask.Action, + Resources = ask.Resources, + Message = ask.Message, + Metadata = ask.Metadata, + }; + + internal static NeedsYouItem FromForm(FormInfo form) => new(form.Id, form.SessionId, form.Title, form); } diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/NewSession.razor b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/NewSession.razor index 9d629c82..10d99c4f 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/NewSession.razor +++ b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/NewSession.razor @@ -3,7 +3,8 @@ @inject NavigationManager Navigation New session -

All sessions

+
+

New session

The session runs in the directory you choose: the agent loads that folder's instructions and @@ -16,10 +17,13 @@

@error

} -
- - + + + +

The full path of a folder on the machine that runs HQ.

+
+
@code { private string _directory = ""; diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/PermissionAsk.razor b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/PermissionAsk.razor new file mode 100644 index 00000000..fc4e45ab --- /dev/null +++ b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/PermissionAsk.razor @@ -0,0 +1,75 @@ +@implements IDisposable +@inject SessionBoard Board + +
+
+ @if (ShowSession) + { +

@(Board.Find(Item.SessionId)?.Title is { Length: > 0 } title ? title : "Untitled session")

+ } + else + { +

Permission required

+ } +

+ @if (NeedsYouItem.KindFor(Item.Action ?? "") is { } kind) + { + @kind + } + else + { + @Item.Action + } + @if (Board.Find(Item.SessionId)?.Location.Directory is { } directory) + { + in @SessionsScreen.FolderName(directory) + } +

+
+ @if (Item.Message is { Length: > 0 } message) + { +

@message

+ } + @if (Item.Metadata?.TryGetValue("input", out var input) == true && input.ValueKind == System.Text.Json.JsonValueKind.Object) + { + @foreach (var property in input.EnumerateObject()) + { +
@property.Name: @(property.Value.ValueKind == System.Text.Json.JsonValueKind.String ? property.Value.GetString() : property.Value.GetRawText())
+ } + } + @foreach (var resource in Item.Resources) + { +
@resource
+ } + @foreach (var file in Item.PreviewFiles) + { + + } +
+ + + +
+
+ +@code { + private readonly CancellationTokenSource _lifetime = new(); + + /// Gets or sets the permission awaiting a decision. + /// The parent supplies Item before rendering. + [Parameter, EditorRequired] + public NeedsYouItem Item { get; set; } = null!; + + /// Gets or sets whether the heading links to the session. + [Parameter] + public bool ShowSession { get; set; } + + /// + public void Dispose() + { + _lifetime.Cancel(); + _lifetime.Dispose(); + } + + private Task AnswerAsync(PermissionReply decision) => Board.AnswerAsync(Item, decision, _lifetime.Token); +} diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionBoard.cs b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionBoard.cs index 08e61341..1955bb0b 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionBoard.cs +++ b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionBoard.cs @@ -33,6 +33,44 @@ .. _sessions.Values.OrderByDescending(static session => session.Time.Updated) .Select(session => new SessionRow(session, StatusOf(session.Id))), ]; public IReadOnlyList NeedsYou => [.. _needsYou.Values.OrderBy(static item => item.Id, StringComparer.Ordinal)]; + public SessionInfo? Find(string sessionId) => _sessions.GetValueOrDefault(sessionId); + + public Task DismissFormAsync(FormInfo form, CancellationToken cancellationToken) => SettleFormAsync(form, null, cancellationToken); + + /// Replaces one session's asks with the ones the server still lists as pending. + /// The session whose asks are listed. + /// Ends the listing. + /// A task that completes once the board holds the server's list. + public async Task ResyncAsync(string sessionId, CancellationToken cancellationToken) + { + // Asks that arrive by event while the lists are read are not in the snapshot, so they stay. + var known = _needsYou.Values.Where(item => item.SessionId == sessionId).Select(static item => item.Id).ToArray(); + NeedsYouItem[] pending; + try + { + var session = client.Sessions.GetSessionClient(sessionId); + var asks = await session.ListRequestsAsync(cancellationToken: cancellationToken); + var forms = await session.ListFormsAsync(cancellationToken: cancellationToken); + pending = [.. asks.Requests.Select(NeedsYouItem.FromPermission), .. forms.Forms.Select(NeedsYouItem.FromForm)]; + } + catch (OpenCodeException exception) + { + logger.LogWarning(exception, "Could not list the asks of session {SessionId}.", sessionId); + return; + } + + foreach (var id in known.Except(pending.Select(static item => item.Id), StringComparer.Ordinal)) + { + _ = _needsYou.TryRemove(id, out _); + } + + foreach (var item in pending) + { + _needsYou[item.Id] = item; + } + + Changed?.Invoke(this, EventArgs.Empty); + } public async Task AnswerAsync(NeedsYouItem item, PermissionReply decision, CancellationToken cancellationToken) { @@ -40,6 +78,7 @@ public async Task AnswerAsync(NeedsYouItem item, PermissionReply decision, Cance try { #region panel: reply + // The card supplies PermissionReply.Reject, PermissionReply.Always, or PermissionReply.Once. _ = await client.Sessions.GetSessionClient(item.SessionId).ReplyToPermissionAsync( item.Id, new SessionPermissionReplyRequest { Decision = decision }, cancellationToken: cancellationToken); #endregion @@ -58,14 +97,26 @@ public async Task AnswerAsync(NeedsYouItem item, PermissionReply decision, Cance Changed?.Invoke(this, EventArgs.Empty); } - public async Task AnswerFormAsync(FormInfo form, SessionFormReplyRequest reply, CancellationToken cancellationToken) + public Task AnswerFormAsync(FormInfo form, SessionFormReplyRequest reply, CancellationToken cancellationToken) => + SettleFormAsync(form, reply, cancellationToken); + + private async Task SettleFormAsync(FormInfo form, SessionFormReplyRequest? reply, CancellationToken cancellationToken) { LastError = null; try { - #region panel: form-reply - _ = await client.Sessions.GetSessionClient(form.SessionId).ReplyToFormAsync(form.Id, reply, cancellationToken: cancellationToken); - #endregion + if (reply is null) + { + #region panel: form-dismiss + _ = await client.Sessions.GetSessionClient(form.SessionId).CancelFormAsync(form.Id, cancellationToken: cancellationToken); + #endregion + } + else + { + #region panel: form-reply + _ = await client.Sessions.GetSessionClient(form.SessionId).ReplyToFormAsync(form.Id, reply, cancellationToken: cancellationToken); + #endregion + } _ = _needsYou.TryRemove(form.Id, out _); } catch (OpenCodeApiException exception) when (exception.Error is FormNotFoundError or FormAlreadySettledError) @@ -154,7 +205,7 @@ private async Task WatchConnectionAsync(CancellationToken cancellationToken) } } - private string StatusOf(string sessionId) + public string StatusOf(string sessionId) { if (_needsYou.Values.Any(item => item.SessionId == sessionId)) { @@ -230,11 +281,22 @@ private async Task ApplyAsync(IEvent item, CancellationToken cancellationToken) var read = await client.Sessions.GetSessionClient(created.Data.SessionId).GetAsync(cancellationToken: cancellationToken); _sessions[read.Session.Id] = read.Session; break; + case SessionRenamed renamed when _sessions.TryGetValue(renamed.Data.SessionId, out var session): + _sessions[session.Id] = session with { Title = renamed.Data.Title }; + break; case SessionExecutionStarted started: _running[started.Data.SessionId] = 0; break; case SessionExecutionSucceeded or SessionExecutionFailed or SessionExecutionInterrupted: - _ = _running.TryRemove(((ISessionScopedEvent)item).SessionId, out _); + var ended = ((ISessionScopedEvent)item).SessionId; + _ = _running.TryRemove(ended, out _); + // A turn that ends drops its pending asks without an event, so the board re-lists them (README, Architecture). + // A shutdown interruption is skipped, as upstream's client skips it. + if (item is not SessionExecutionInterrupted interrupted || interrupted.Data.Reason != SessionExecutionInterruptedDataReason.Shutdown) + { + await ResyncAsync(ended, cancellationToken); + } + break; #region panel: asks case PermissionAsked asked: diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionsScreen.razor b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionsScreen.razor index a5d2de13..062caf73 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionsScreen.razor +++ b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionsScreen.razor @@ -2,55 +2,72 @@ @inject SessionBoard Board OpenCode HQ - -
-
-@if (Board.LastError is { } error) -{ -

@error

-} +
@if (!Board.Connected) { -

Not connected to HQ's opencode server. Waiting to reconnect.

+

Not connected to HQ's opencode server. HQ keeps trying, and the board fills again when the connection is back.@(Board.LastError is { } e ? $" Last error: {e}" : null)

} else { -
-

Needs you · @Board.NeedsYou.Count

- @foreach (var item in Board.NeedsYou) + @if (Board.LastError is { } error) { - @if (item.Form is not null) +

@error

+ } +
+

Needs you@Board.NeedsYou.Count

+ @foreach (var item in Board.NeedsYou) { - + @if (item.Form is not null) + { + + } + else + { + + } } - else + @if (Board.NeedsYou.Count == 0) { -
-
Permission
@item.Title
- - +

Nothing needs you. When an agent asks for permission or asks a question, the ask waits here until you answer it.

+ } +
+
+

Sessions

+ @if (Board.Sessions.Count == 0) + { +
+

No sessions yet. Start one: pick a project folder, then send the agent a prompt. Its status shows here while it works.

+ New session
} - } -
- -
-

Sessions

- - - - @foreach (var row in Board.Sessions) + else { - - - - - +
SessionFolderStatus
@row.Session.Title@row.Session.Location.Directory@row.Status
+ + + @foreach (var row in Board.Sessions) + { + + + + + + } + +
SessionFolderStatus
@(string.IsNullOrEmpty(row.Session.Title) ? "Untitled session" : row.Session.Title)@FolderName(row.Session.Location.Directory)@switch (row.Status) + { + case "waiting for you": + Waiting for you + break; + case "running": + Running + break; + default: + Idle + break; + }
} - - -
+
}
-
diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionsScreen.razor.cs b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionsScreen.razor.cs index 9fe5e0f5..62a3be12 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionsScreen.razor.cs +++ b/playground/hq/OpenCode.Playground.Hq/Features/Sessions/SessionsScreen.razor.cs @@ -1,18 +1,17 @@ -using OpenCode.Sdk.Models; - namespace OpenCode.Playground.Hq.Features.Sessions; /// The first screen: what needs a person, then every session. public sealed partial class SessionsScreen : IDisposable { - private readonly CancellationTokenSource _lifetime = new(); - + internal static string FolderName(string directory) + { + var path = directory.TrimEnd('\\', '/'); + return path[(Math.Max(path.LastIndexOf('\\', StringComparison.Ordinal), path.LastIndexOf('/', StringComparison.Ordinal)) + 1)..]; + } /// public void Dispose() { Board.Changed -= OnChanged; - _lifetime.Cancel(); - _lifetime.Dispose(); } /// @@ -24,5 +23,4 @@ private void OnChanged(object? sender, EventArgs args) _ = InvokeAsync(StateHasChanged); } - private Task AnswerAsync(NeedsYouItem item, PermissionReply decision) => Board.AnswerAsync(item, decision, _lifetime.Token); } diff --git a/playground/hq/OpenCode.Playground.Hq/Features/Terminal/TerminalPanel.razor b/playground/hq/OpenCode.Playground.Hq/Features/Terminal/TerminalPanel.razor index 08e02e1c..ccd3c593 100644 --- a/playground/hq/OpenCode.Playground.Hq/Features/Terminal/TerminalPanel.razor +++ b/playground/hq/OpenCode.Playground.Hq/Features/Terminal/TerminalPanel.razor @@ -1,20 +1,22 @@ @inject SessionTerminal Terminal +@inject SessionBoard Board
-

Terminal

+

A shell in @SessionsScreen.FolderName(Board.Find(SessionId)?.Location.Directory ?? ""), on the machine that runs opencode. Leaving this page closes it.

@if (Terminal.LastError is { } error) {

@error

} @if (!Terminal.IsOpen) { - +
} else { -
@Terminal.Output
-
- +
@Terminal.Output
+ + +
} diff --git a/playground/hq/OpenCode.Playground.Hq/OpenCode.Playground.Hq.csproj b/playground/hq/OpenCode.Playground.Hq/OpenCode.Playground.Hq.csproj index 2eae8a6e..3eb07a5f 100644 --- a/playground/hq/OpenCode.Playground.Hq/OpenCode.Playground.Hq.csproj +++ b/playground/hq/OpenCode.Playground.Hq/OpenCode.Playground.Hq.csproj @@ -10,6 +10,7 @@ + diff --git a/playground/hq/OpenCode.Playground.Hq/Program.cs b/playground/hq/OpenCode.Playground.Hq/Program.cs index 3e845c8e..fba869ac 100644 --- a/playground/hq/OpenCode.Playground.Hq/Program.cs +++ b/playground/hq/OpenCode.Playground.Hq/Program.cs @@ -13,6 +13,7 @@ builder.Services.AddSingleton(static services => OpenCodeConnection.Connect(services.GetRequiredService())); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddScoped(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddHostedService(static services => services.GetRequiredService()); diff --git a/playground/hq/OpenCode.Playground.Hq/wwwroot/app.css b/playground/hq/OpenCode.Playground.Hq/wwwroot/app.css index f8439f56..f056790d 100644 --- a/playground/hq/OpenCode.Playground.Hq/wwwroot/app.css +++ b/playground/hq/OpenCode.Playground.Hq/wwwroot/app.css @@ -1,42 +1,204 @@ -:root { color-scheme: dark; } -body { margin: 0; background: #101417; color: #E8ECEF; font: 15px/1.45 system-ui, sans-serif; } -a { color: #7CC0FF; } -a:hover { color: #B5DCFF; } -pre, code, .mono { font-family: ui-monospace, Consolas, monospace; font-size: 13px; } -header.top { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; padding: 14px 28px; border-bottom: 1px solid #2A3138; } -header.top .title { font-weight: 600; font-size: 18px; } -header.top .status { flex-grow: 1; color: #A3AEB8; } -.screen { display: flex; flex-wrap: wrap; } -.screen > main { flex: 999 1 520px; min-width: 0; padding: 24px 28px; display: flex; flex-direction: column; gap: 24px; } -.screen > .side { flex: 1 1 340px; padding: 24px; border-left: 1px solid #2A3138; min-width: 0; } -h1, h2 { margin: 0; font-size: 20px; font-weight: 600; } -h3 { margin: 0; font-size: 14px; font-weight: 500; } -button { min-height: 44px; padding: 0 16px; background: #1E252B; color: #E8ECEF; border: 1px solid #3A434C; border-radius: 6px; font: inherit; cursor: pointer; } -button.primary { background: #7CC0FF; color: #0B1116; border: 0; font-weight: 600; } -button.chosen { border-color: #F0B429; } +:root { + color-scheme: dark; + /* Named colours */ + --ink: #101417; /* the page */ + --text: #E8ECEF; /* body text */ + --muted: #A3AEB8; /* secondary text, the idle mark */ + --decide: #F0B429; /* Needs you, and nothing else */ + --live: #7CC0FF; /* links, the running mark, focus, SDK calls in code */ + --add: #6FD08C; /* added lines, the connected mark */ + --remove: #FF8A80; /* removed lines, danger, the not-connected mark */ + /* Derived from them */ + --surface: #171C21; /* inputs, your prompts, the SDK dock */ + --well: #0B0F12; /* code, diffs, terminal output */ + --rule: #2A3138; /* hairlines; decorative */ + --edge: #66727E; /* control borders; 3:1 against the page */ + --decide-tint: #262419; + --add-tint: #1A2723; + --remove-tint: #282022; + --remove-edge: #935551; + /* Type: 13 / 15 / 18 / 24 px, weights 400 and 600 */ + --t-small: 13px; + --t-body: 15px; + --t-title: 18px; + --t-signal: 24px; + --mono: ui-monospace, "Cascadia Mono", Consolas, monospace; + /* Space */ + --s1: 4px; --s2: 8px; --s3: 12px; --s4: 16px; --s5: 24px; --s6: 32px; --s7: 48px; + /* Radii by hierarchy; what is docked to the viewport edge has none */ + --r-chip: 3px; /* inline code */ + --r-control: 6px; /* buttons, inputs, choices, code boxes */ + --r-block: 10px; /* your prompts, notices, diffs, terminal output */ + --header-h: 56px; + --dock-h: 0px; +} + +*, *::before, *::after { box-sizing: border-box; } +body { margin: 0; background: var(--ink); color: var(--text); font: 400 var(--t-body)/22px system-ui, sans-serif; } +h1, h2, h3, p, fieldset, legend { margin: 0; padding: 0; } +fieldset { border: 0; min-width: 0; } +h1, h2 { font-size: var(--t-title); line-height: 24px; font-weight: 600; } +h3, legend { font-size: var(--t-body); line-height: 22px; font-weight: 600; } +a { color: var(--live); text-underline-offset: 3px; } +a:hover { color: var(--text); } +code, pre, .mono { font-family: var(--mono); font-size: var(--t-small); } +.meta { color: var(--muted); font-size: var(--t-small); line-height: 20px; } +.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +:focus-visible { outline: 2px solid var(--live); outline-offset: 2px; } + +/* Controls. Only .decide is filled: it is the answer to an ask. */ +button, a.button { display: inline-flex; align-items: center; justify-content: center; min-height: 40px; padding: 0 var(--s4); background: var(--surface); color: var(--text); border: 1px solid var(--edge); border-radius: var(--r-control); font: inherit; text-decoration: none; white-space: nowrap; cursor: pointer; } +button:hover, a.button:hover { background: var(--rule); color: var(--text); } +button.decide { background: var(--decide); border-color: var(--decide); color: var(--ink); font-weight: 600; } +button.decide:hover { background: var(--decide); filter: brightness(1.1); } +button.danger { background: transparent; border-color: var(--remove-edge); color: var(--remove); } +button.danger:hover { background: var(--remove-tint); color: var(--remove); } button:disabled { opacity: 0.5; cursor: default; } -input, textarea { min-height: 44px; box-sizing: border-box; padding: 8px 12px; background: #171C21; color: #E8ECEF; border: 1px solid #3A434C; border-radius: 6px; font: inherit; } -[role="alert"] { padding: 12px 16px; background: #2A1414; border: 1px solid #6B2A2A; border-radius: 8px; } -.needs-you h1 { color: #F0B429; } -.ask { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding: 16px; background: #1F1B10; border: 1px solid #6B5416; border-radius: 8px; } -.ask-text { flex: 999 1 300px; min-width: 0; } -.ask-kind { font-size: 13px; color: #D9C88F; } -.field { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; flex-basis: 100%; } -table.sessions { width: 100%; border-collapse: collapse; font-size: 14px; } -table.sessions th { text-align: left; color: #A3AEB8; font-size: 13px; font-weight: 500; padding: 10px 16px; } -table.sessions td { padding: 12px 16px; border-top: 1px solid #2A3138; } -.status-running { color: #7CC0FF; } -.status-waiting { color: #F0B429; } -.status-idle { color: #A3AEB8; } -.line { padding: 14px 16px; border-radius: 8px; border: 1px solid #2A3138; white-space: pre-wrap; } -.line.you { background: #171C21; border: 0; } -.line .who { display: block; font-size: 13px; color: #A3AEB8; } -.prompt { display: flex; flex-wrap: wrap; gap: 8px; margin-top: auto; } -.prompt textarea { flex: 999 1 240px; min-width: 0; } -.panel { flex: 1 1 360px; padding: 24px; background: #171C21; border-left: 1px solid #2A3138; display: flex; flex-direction: column; gap: 18px; } -.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; } -.panel pre { margin: 0; padding: 12px; background: #101417; border: 1px solid #2A3138; border-radius: 6px; white-space: pre-wrap; overflow-wrap: anywhere; } -.terminal { display: flex; flex-direction: column; gap: 8px; margin-top: 24px; } -.terminal pre.output { margin: 0; max-height: 360px; overflow: auto; padding: 12px; background: #0B0F12; border: 1px solid #2A3138; border-radius: 6px; white-space: pre-wrap; overflow-wrap: anywhere; } -.panel-item { display: flex; flex-direction: column; gap: 8px; } -details pre { white-space: pre; overflow-x: auto; padding: 12px; background: #171C21; border-radius: 6px; } +input[type="text"], textarea { width: 100%; min-height: 40px; padding: var(--s2) var(--s3); background: var(--surface); color: var(--text); border: 1px solid var(--edge); border-radius: var(--r-control); font: inherit; } +textarea { display: block; resize: vertical; } +::placeholder { color: var(--muted); opacity: 1; } +[role="alert"], .notice { padding: var(--s3) var(--s4); background: var(--remove-tint); border: 1px solid var(--remove-edge); border-radius: var(--r-block); } + +/* Marks: every state has its own shape, so colour is never the only cue. */ +.mark { display: inline-block; flex: none; width: 8px; height: 8px; margin-right: var(--s2); } +.mark.decide { background: var(--decide); border-radius: 1px; transform: rotate(45deg); } +.mark.running { width: 10px; height: 10px; border: 2px solid var(--live); border-right-color: transparent; border-radius: 50%; } +.mark.idle { height: 2px; background: var(--muted); } +.mark.connected { background: var(--add); border-radius: 50%; } +.mark.lost { border: 2px solid var(--remove); border-radius: 50%; } +.status { display: inline-flex; align-items: center; vertical-align: top; white-space: nowrap; } +.status.waiting { color: var(--decide); } +.status.running { color: var(--live); } +.status.idle { color: var(--muted); } + +/* Header */ +header.top { position: sticky; top: 0; z-index: 3; display: flex; align-items: center; gap: var(--s4); height: var(--header-h); padding: 0 var(--s6); background: var(--ink); border-bottom: 1px solid var(--rule); } +.brand { color: var(--text); font-size: var(--t-title); font-weight: 600; text-decoration: none; white-space: nowrap; } +.conn { display: inline-flex; align-items: center; margin-right: auto; color: var(--muted); font-size: var(--t-small); } + +/* Board */ +.board { display: grid; grid-template-columns: minmax(0, 36rem) minmax(0, 1fr); align-items: start; gap: var(--s7); padding: var(--s6); } +.page { display: grid; gap: var(--s5); max-width: 72ch; padding: var(--s6); } +.signal { display: flex; align-items: center; padding-bottom: var(--s3); border-bottom: 2px solid var(--decide); color: var(--decide); font-size: var(--t-signal); line-height: 30px; } +.signal .mark { width: 12px; height: 12px; margin: 0 14px 0 var(--s1); } +.signal .count { margin-left: var(--s3); font-weight: 400; } +.queue.clear .signal { border-bottom-color: var(--rule); color: var(--muted); } +.queue.clear .signal .mark { background: none; border: 2px solid var(--muted); } +.ask { display: grid; gap: var(--s4); padding: var(--s5) 0; border-bottom: 1px solid var(--rule); } +.ask h2 a { color: var(--text); text-decoration-color: var(--edge); } +.ask h2 a:hover { text-decoration-color: var(--text); } +.field { display: grid; gap: var(--s2); } +.choices { display: grid; gap: var(--s2); margin-top: var(--s1); } +.choice { display: grid; grid-template-columns: auto minmax(0, 1fr); column-gap: var(--s3); padding: 10px var(--s3); border: 1px solid var(--edge); border-radius: var(--r-control); cursor: pointer; } +.choice:has(input:checked) { background: var(--decide-tint); border-color: var(--decide); } +.choice input { grid-row: span 2; width: 18px; height: 18px; margin: 2px 0 0; accent-color: var(--decide); } +.choice-note { grid-column: 2; color: var(--muted); font-size: var(--t-small); line-height: 20px; } +.own { display: grid; gap: var(--s1); margin-top: var(--s2); color: var(--muted); font-size: var(--t-small); line-height: 20px; } +.own input { font-size: var(--t-body); } +.command { margin: 0; padding: 10px var(--s3); background: var(--well); border: 1px solid var(--rule); border-radius: var(--r-control); line-height: 20px; white-space: pre; overflow-x: auto; } +.actions { display: flex; flex-wrap: wrap; gap: var(--s2); } +.empty { display: grid; justify-items: start; gap: var(--s3); max-width: 60ch; padding: var(--s5) 0; color: var(--muted); } +.sessions h2 { padding-bottom: var(--s3); border-bottom: 1px solid var(--rule); line-height: 30px; } +.rows { width: 100%; border-collapse: collapse; } +.rows th { padding: var(--s3) var(--s4) var(--s2) 0; color: var(--muted); font-size: var(--t-small); font-weight: 400; text-align: left; } +.rows td { padding: var(--s3) var(--s4) var(--s3) 0; border-top: 1px solid var(--rule); vertical-align: top; } +.rows .name a { color: var(--text); text-decoration-color: var(--edge); } +.rows .name a:hover { text-decoration-color: var(--text); } +.rows .folder { color: var(--muted); } + +/* Session page: the conversation at 72ch, the rail beside it */ +.session { display: grid; grid-template-columns: minmax(0, 72ch) minmax(0, 1fr); grid-template-rows: auto 1fr; column-gap: var(--s7); min-height: calc(100dvh - var(--header-h) - var(--dock-h)); padding: var(--s5) var(--s6) 0; } +.session-head { grid-column: 1 / -1; display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--s1) var(--s4); padding-bottom: var(--s5); } +.session-head .meta { display: flex; gap: var(--s4); } +.talk { display: flex; flex-direction: column; min-width: 0; } +.transcript { display: grid; gap: var(--s5); padding-bottom: var(--s6); } +.turn { min-width: 0; overflow-wrap: break-word; } +.turn.you { padding: var(--s3) var(--s4); background: var(--surface); border-radius: var(--r-block); white-space: pre-wrap; } +.turn.you.pending { opacity: 0.6; } +.md > * + * { margin-top: var(--s3); } +.md h1, .md h2 { font-size: var(--t-title); line-height: 24px; } +.md h3, .md h4, .md h5, .md h6 { margin-bottom: 0; font-size: var(--t-body); line-height: 22px; font-weight: 600; } +.md h3:not(:first-child) { margin-top: var(--s5); } +.md ul, .md ol { margin-bottom: 0; padding-left: var(--s5); } +.md li + li { margin-top: var(--s1); } +.md code { padding: 1px 5px; background: var(--surface); border-radius: var(--r-chip); } +.md pre { margin-bottom: 0; padding: var(--s3); background: var(--well); border-radius: var(--r-control); overflow-x: auto; } +.md pre code { padding: 0; background: none; } +.talk .queue { padding-bottom: var(--s5); } +.talk .queue .ask:last-child { border-bottom: 0; } +.composer { position: sticky; bottom: var(--dock-h); display: flex; align-items: flex-end; gap: var(--s2); margin-top: auto; padding: var(--s3) 0 var(--s4); background: var(--ink); border-top: 1px solid var(--rule); } +.composer textarea { flex: 1; min-height: 62px; } +.rail { position: sticky; top: calc(var(--header-h) + var(--s4)); align-self: start; min-width: 0; max-height: calc(100dvh - var(--header-h) - var(--dock-h) - var(--s6)); padding-bottom: var(--s5); overflow-y: auto; } +.tabs { display: flex; gap: var(--s5); margin-bottom: var(--s4); border-bottom: 1px solid var(--rule); } +.tabs button { min-height: 36px; margin-bottom: -1px; padding: 0 0 var(--s2); background: none; border: 0; border-bottom: 2px solid transparent; border-radius: 0; color: var(--muted); } +.tabs button:hover { background: none; color: var(--text); } +.tabs button[aria-selected="true"] { border-bottom-color: var(--text); color: var(--text); font-weight: 600; } +.tabs .count { margin-left: var(--s2); color: var(--muted); font-weight: 400; } +.tabpanel { display: grid; gap: var(--s3); } +.tabpanel[hidden] { display: none; } +.file summary { padding: var(--s1) 0; cursor: pointer; } +.file .plus { margin-left: var(--s3); color: var(--add); } +.file .minus { margin-left: var(--s2); color: var(--remove); } +.file .diff { margin-top: var(--s2); } + +/* Diffs and code never wrap: the box scrolls sideways, and each line's background runs the full width. */ +.diff, .code { background: var(--well); border: 1px solid var(--rule); font-family: var(--mono); font-size: var(--t-small); overflow-x: auto; } +.diff { padding: var(--s2) 0; border-radius: var(--r-block); line-height: 20px; } +.code { padding: var(--s2) 0; border-radius: var(--r-control); line-height: 21px; tab-size: 4; } +.lines { display: inline-block; min-width: 100%; } +.dl { min-height: 20px; padding: 0 var(--s3); white-space: pre; } +.dl.meta, .dl.hunk { color: var(--muted); } +.dl.add { background: var(--add-tint); color: var(--add); } +.dl.del { background: var(--remove-tint); color: var(--remove); } +.cl { display: flex; min-height: 21px; padding-right: var(--s4); white-space: pre; } +.ln { position: sticky; left: 0; flex: none; width: 6ch; padding-right: 2ch; background: var(--well); color: var(--muted); text-align: right; user-select: none; } +.cl.note .src { color: var(--muted); } +.src b { color: var(--live); font-weight: 600; } + +/* Terminal */ +.terminal { display: grid; gap: var(--s2); } +.terminal pre.output { max-height: 360px; margin: 0; padding: var(--s3); background: var(--well); border: 1px solid var(--rule); border-radius: var(--r-block); line-height: 20px; white-space: pre-wrap; overflow-wrap: anywhere; overflow-y: auto; } +.terminal form { display: flex; gap: var(--s2); } +.terminal form input { flex: 1; min-width: 0; font-family: var(--mono); font-size: var(--t-small); } + +/* The SDK dock: a bottom drawer, because the code is long lines in short blocks. */ +.dock { display: none; } +.sdk-open { --dock-h: min(46dvh, 400px); padding-bottom: var(--dock-h); } +.sdk-open .dock { position: fixed; inset: auto 0 0 0; z-index: 2; display: flex; flex-direction: column; height: var(--dock-h); background: var(--surface); border-top: 1px solid var(--edge); } +.dock-head { display: flex; align-items: center; gap: var(--s4); padding: var(--s2) var(--s6); border-bottom: 1px solid var(--rule); } +.dock-head h2 { margin-right: auto; font-size: var(--t-body); line-height: 22px; } +.dock-head a { font-size: var(--t-small); } +.dock-head button { min-height: 32px; padding: 0 var(--s3); } +.dock-body { display: grid; align-content: start; gap: var(--s3); padding: var(--s4) var(--s6) var(--s5); overflow-y: auto; } +.call { display: grid; grid-template-columns: 20rem minmax(0, 1fr); align-items: start; gap: var(--s5); } +.call-note { display: grid; gap: var(--s1); padding-top: var(--s2); } +.call-note a { overflow-wrap: anywhere; } + +@media (prefers-reduced-motion: no-preference) { + .mark.running { animation: turn 1s linear infinite; } +} +@keyframes turn { to { transform: rotate(360deg); } } + +/* Narrow screens: one column, stacked session rows, a taller dock. Nothing but code scrolls sideways. */ +@media (max-width: 900px) { + header.top { gap: var(--s2); padding: 0 var(--s4); } + .conn-text, .wide { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + button, a.button, input[type="text"], .dock-head button { min-height: 44px; } + header.top button, header.top a.button { padding: 0 var(--s3); } + .conn .mark { margin-right: 0; } + .board { grid-template-columns: minmax(0, 1fr); gap: var(--s6); padding: var(--s5) var(--s4); } + .page { padding: var(--s5) var(--s4); } + .rows thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); } + .rows tr { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px var(--s3); padding: var(--s3) 0; border-top: 1px solid var(--rule); } + .rows tbody tr:first-child { border-top: 0; } + .rows td { display: block; padding: 0; border: 0; } + .rows .name { grid-column: 1 / -1; } + .session { display: block; min-height: 0; padding: var(--s4) var(--s4) 0; } + .session-head { padding-bottom: var(--s4); } + .rail { position: static; max-height: none; margin-top: var(--s5); padding: var(--s4) 0 var(--s6); border-top: 1px solid var(--rule); overflow-y: visible; } + .sdk-open { --dock-h: min(64dvh, 520px); } + .dock-head { padding: var(--s2) var(--s4); } + .dock-body { padding: var(--s4) var(--s4) var(--s5); } + .call { grid-template-columns: minmax(0, 1fr); gap: var(--s2); } + .call-note { padding-top: 0; } +} diff --git a/playground/hq/README.md b/playground/hq/README.md index 1c872918..6574b216 100644 --- a/playground/hq/README.md +++ b/playground/hq/README.md @@ -1,10 +1,11 @@ # OpenCode HQ HQ's first screen lists sessions with live status and a **Needs you** list. Permission asks have -Allow once and Reject buttons; question forms can be answered in place on both screens. HQ answers -text questions (option buttons and custom text) and multiselect questions (checkboxes); other field +an upstream-style Deny, Allow always and Allow once choice; question forms can be submitted or dismissed in place on both screens. HQ answers +text questions (radio options and custom text) and multiselect questions (checkboxes); other field kinds direct you to opencode. A session's page shows -its conversation, streamed answer, prompt box, asks and changed files; New session picks a directory. +its conversation with rendered Markdown, streamed answer, prompt box, asks and changed files; New session picks a directory. +While a turn runs, Stop interrupts it with resumption enabled, as in upstream's app. There is no login, database or settings UI. A session's page can open a **terminal** in the session's folder: one shell, its output as plain @@ -16,8 +17,9 @@ connection times out. A terminal left by HQ being killed outright lives until th > **The terminal is a shell on the machine running opencode, for anyone who can open HQ's page.** HQ > has no login and listens only on `127.0.0.1`, so keep it that way: run it on your own machine only. -Each screen has a hideable **How this screen works** panel: SDK calls for that screen, links to -their source files and a guide. It reads HQ's own source at run time, embedded at build time, so +Open **SDK calls** from the header to see the screen's calls in a bottom dock, with numbered source +lines, links to their source files and a guide. The open state is remembered across pages and reloads +when browser storage is available. It reads HQ's own source at run time, embedded at build time, so snippets cannot drift from the code running. To add an entry, mark the code with a `#region panel: name` block and its `#endregion`, then add a `PanelEntry` with that file and region to the screen's list in `Features/Panel/PanelEntry.cs`. @@ -63,7 +65,13 @@ Aspire AppHost -> plain opencode serve (generated password, own port) The board opens the bus, awaits its first event, seeds the newest **500 sessions**, reads which are running, reads asks for those sessions' directories, then follows events. An unavailable directory is logged and skipped. -A session renamed, deleted or archived elsewhere keeps its old row until the board reconnects or HQ restarts. +A session's title follows rename events. A session deleted or archived elsewhere keeps its old row until the board reconnects or HQ restarts. +Opening a session page re-lists that session's pending permissions and forms from the server, as +upstream's session page does. The board also re-lists a session's asks when one of its turns ends, +except on a shutdown. This goes beyond upstream's app, and it has a reason: when a turn is interrupted, +upstream's server drops a pending ask without publishing an event +([anomalyco/opencode#55678](https://github.com/anomalyco/opencode/issues/55678)), so an +event-driven list alone would keep a card that can no longer be answered. A repeated `server.connected` refreshes the lists because disconnected events are lost. The SDK retries ordinary attempt failures forever and reports them through connection state; the board's owned state watch updates `Connected` and the connection error independently of event consumption. diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionConversationTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionConversationTests.cs index cbcea91a..9c00829d 100644 --- a/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionConversationTests.cs +++ b/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionConversationTests.cs @@ -8,6 +8,22 @@ namespace OpenCode.Playground.Hq.Tests.Features.Conversation; public sealed class SessionConversationTests { + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task StopAsync_Should_Interrupt_With_Resume_And_Ignore_A_Refusal(bool refused) + { + using var scenario = new ConversationScenario(); + await scenario.FollowAsync(Started()); + scenario.MessageCalls.FailInterrupt = refused; + scenario.SessionCalls.RequestedSession = null; + await Assert.That(() => scenario.Conversation.StopAsync(CancellationToken.None)).ThrowsNothing(); + + await Assert.That(scenario.SessionCalls.RequestedSession).IsEqualTo(SessionId); + await Assert.That(scenario.MessageCalls.Interrupt?.Resume).IsTrue(); + await Assert.That(scenario.Conversation.LastError).IsNull(); + } + [Test] public async Task FollowAsync_Should_Replace_Refreshed_Text_With_The_Parts_Authoritative_End() { diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionScreenTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionScreenTests.cs new file mode 100644 index 00000000..e9b189d3 --- /dev/null +++ b/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/SessionScreenTests.cs @@ -0,0 +1,17 @@ +using OpenCode.Playground.Hq.Features.Conversation; + +namespace OpenCode.Playground.Hq.Tests.Features.Conversation; + +public sealed class SessionScreenTests +{ + [Test] + public async Task Rendered_Should_Escape_Raw_Html_And_Render_Markdown() + { + var html = SessionScreen.Rendered("\n\n\n\n### Heading\n\n- item with `code`").Value; + + await Assert.That(html).Contains("<script>alert(1)</script>"); + await Assert.That(html).Contains("<img onerror="alert(2)">"); + await Assert.That(html).Contains("

Heading

"); + await Assert.That(html).Contains("
    \n
  • item with code
  • \n
"); + } +} diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/Support/ConversationScenario.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/Support/ConversationScenario.cs index 4db06229..03d51d06 100644 --- a/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/Support/ConversationScenario.cs +++ b/tests/OpenCode.Playground.Hq.Tests/Features/Conversation/Support/ConversationScenario.cs @@ -137,10 +137,15 @@ public override IAsyncEnumerable SubscribeAsync(EventSubscribeRequest? r internal sealed class ConversationSessions(SessionClient session) : SessionsClient { + public string? RequestedSession { get; set; } public bool Running { get; set; } public TaskCompletionSource ActiveStarted { get; set; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource? ActiveRelease { get; set; } - public override SessionClient GetSessionClient(string sessionId) => session; + public override SessionClient GetSessionClient(string sessionId) + { + RequestedSession = sessionId; + return session; + } public override async Task GetActiveAsync(OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) { ActiveStarted.TrySetResult(); @@ -159,6 +164,16 @@ internal sealed class ConversationSession : SessionClient public ICollection Trace { get; set; } = []; public IReadOnlyList Messages { get; set; } = []; public bool FailPrompt { get; set; } + public bool FailInterrupt { get; set; } + public SessionInterruptRequest? Interrupt { get; private set; } + public override Task InterruptAsync(SessionInterruptRequest? request = null, + OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) + { + Interrupt = request; + return FailInterrupt + ? Task.FromException(new OpenCodeApiException("unauthorized", 401, new UnauthorizedError { Message = "unauthorized" }, null)) + : Task.FromResult(new SessionInterruptResponse { Status = 200, Interrupt = new() { Interrupted = true } }); + } public SessionPromptRequest? Prompt { get; private set; } public TaskCompletionSource MessagesStarted { get; set; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource? MessagesRelease { get; set; } diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Files/DiffViewTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Files/DiffViewTests.cs new file mode 100644 index 00000000..26cc7705 --- /dev/null +++ b/tests/OpenCode.Playground.Hq.Tests/Features/Files/DiffViewTests.cs @@ -0,0 +1,47 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenCode.Playground.Hq.Features.Files; +using TUnit.Assertions.Enums; + +namespace OpenCode.Playground.Hq.Tests.Features.Files; + +public sealed class DiffViewTests +{ + [Test] + public async Task DiffView_Should_Keep_Headers_Meta_And_Colour_Only_Hunk_Lines() + { + var html = await RenderAsync("diff --git a/a b/a\n--- a/a\n+++ b/a\n@@ -1 +1 @@\n+new\n-old\n plain"); + + await Assert.That(LineClasses(html)).IsEquivalentTo(["meta", "meta", "meta", "hunk", "add", "del", ""], CollectionOrdering.Matching); + await Assert.That(html).Contains("aria-label=\"Patch for a\""); + } + + [Test] + public async Task DiffView_Should_Not_Show_The_Patch_Final_Newline_As_A_Line() + { + var html = await RenderAsync("@@ -0,0 +1,1 @@\n+only\n"); + + await Assert.That(LineClasses(html)).IsEquivalentTo(["hunk", "add"], CollectionOrdering.Matching); + } + + private static async Task RenderAsync(string patch) + { + await using var services = new ServiceCollection().AddLogging().BuildServiceProvider(); + await using var renderer = new HtmlRenderer(services, services.GetRequiredService()); + return await renderer.Dispatcher.InvokeAsync(async () => + { + var component = await renderer.RenderComponentAsync(ParameterView.FromDictionary(new Dictionary(StringComparer.Ordinal) + { + [nameof(DiffView.Patch)] = patch, + [nameof(DiffView.Label)] = "Patch for a", + })); + return component.ToHtmlString(); + }); + } + + private static IEnumerable LineClasses(string html) => + html.Split("class=\"dl", StringSplitOptions.None).Skip(1) + .Select(static line => line[..line.IndexOf('"', StringComparison.Ordinal)].Trim()); +} diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Forms/FormDraftTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Forms/FormDraftTests.cs index 957c4399..1f5582bd 100644 --- a/tests/OpenCode.Playground.Hq.Tests/Features/Forms/FormDraftTests.cs +++ b/tests/OpenCode.Playground.Hq.Tests/Features/Forms/FormDraftTests.cs @@ -74,13 +74,27 @@ public async Task ShowsTextBox_Should_Show_It_Without_Options_Or_With_Custom(int } [Test] - public async Task TextClass_Should_Mark_Only_The_Selected_Option() + public async Task IsText_Should_Mark_Only_The_Selected_Option() { var draft = new FormDraft(Form(new FormStringField { Key = "name", Options = [Option("preset")] })); draft.SetText("name", "preset"); - await Assert.That(draft.TextClass("name", "preset")).IsEqualTo("chosen"); - await Assert.That(draft.TextClass("name", "other")).IsEmpty(); + await Assert.That(draft.IsText("name", "preset")).IsTrue(); + await Assert.That(draft.IsText("name", "other")).IsFalse(); + draft.SetText("name", "other"); + await Assert.That(draft.IsText("name", "preset")).IsFalse(); + await Assert.That(draft.IsText("name", "other")).IsTrue(); + } + + [Test] + public async Task CustomTextOf_Should_Clear_The_Text_Box_When_An_Option_Is_Chosen() + { + var field = new FormStringField { Key = "name", Options = [Option("preset")], Custom = true }; + var draft = new FormDraft(Form(field)); + draft.SetText("name", "my name"); + await Assert.That(draft.CustomTextOf(field)).IsEqualTo("my name"); + draft.SetText("name", "preset"); + await Assert.That(draft.CustomTextOf(field)).IsEmpty(); } private static FormOption Option(string value) => new() { Label = value, Value = value }; diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Panel/SdkPanelTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Panel/SdkPanelTests.cs new file mode 100644 index 00000000..a526746d --- /dev/null +++ b/tests/OpenCode.Playground.Hq.Tests/Features/Panel/SdkPanelTests.cs @@ -0,0 +1,36 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using OpenCode.Playground.Hq.Features.Panel; + +namespace OpenCode.Playground.Hq.Tests.Features.Panel; + +public sealed class SdkPanelTests +{ + [Test] + public async Task SdkPanel_Should_Respond_To_The_Circuits_Toggle_With_Numbered_Source() + { + var panel = new PanelState(); + await using var services = new ServiceCollection().AddLogging().AddSingleton(panel).AddSingleton().BuildServiceProvider(); + await using var renderer = new HtmlRenderer(services, services.GetRequiredService()); + await renderer.Dispatcher.InvokeAsync(async () => + { + var component = await renderer.RenderComponentAsync(ParameterView.FromDictionary(new Dictionary(StringComparer.Ordinal) + { + [nameof(SdkPanel.Entries)] = PanelEntry.FirstScreen, + })); + await Assert.That(component.ToHtmlString()).DoesNotContain("sdk-dock"); + panel.Toggle(); + + var html = component.ToHtmlString(); + await Assert.That(html).Contains("id=\"sdk-dock\""); + await Assert.That(html).Contains("Read the streaming guide"); + await Assert.That(html).Contains("#L"); + await Assert.That(html).Contains("class=\"ln\""); + await Assert.That(html).Contains("ReplyToFormAsync"); + panel.Toggle(); + await Assert.That(component.ToHtmlString()).DoesNotContain("sdk-dock"); + }); + } +} diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Panel/SourceSnippetsTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Panel/SourceSnippetsTests.cs index 374e0db9..9f15f5de 100644 --- a/tests/OpenCode.Playground.Hq.Tests/Features/Panel/SourceSnippetsTests.cs +++ b/tests/OpenCode.Playground.Hq.Tests/Features/Panel/SourceSnippetsTests.cs @@ -13,7 +13,7 @@ public sealed class SourceSnippetsTests public async Task ReadAsync_Should_Resolve_Every_Panel_Entry_Without_Markers_Or_Common_Indentation(PanelEntry entry) { ArgumentNullException.ThrowIfNull(entry); - var code = await _source.ReadAsync(entry.File, entry.Region); + var code = (await _source.ReadAsync(entry.File, entry.Region)).Code; await Assert.That(code).IsNotEmpty(); await Assert.That(code).DoesNotContain("#region"); @@ -40,7 +40,7 @@ public async Task ReadAsync_Should_Name_A_Missing_File() [Test] public async Task ReadAsync_Should_Return_The_Exact_Form_Reply_Statement_Unindented() { - var code = await _source.ReadAsync(BoardFile, "form-reply"); + var code = (await _source.ReadAsync(BoardFile, "form-reply")).Code; await Assert.That(code).IsEqualTo("_ = await client.Sessions.GetSessionClient(form.SessionId).ReplyToFormAsync(form.Id, reply, cancellationToken: cancellationToken);"); } @@ -48,8 +48,24 @@ public async Task ReadAsync_Should_Return_The_Exact_Form_Reply_Statement_Uninden [Test] public async Task ReadAsync_Should_Keep_Relative_Indentation_In_A_Multiline_Region() { - var code = await _source.ReadAsync(BoardFile, "reply"); + var code = (await _source.ReadAsync(BoardFile, "reply")).Code; - await Assert.That(code).IsEqualTo("_ = await client.Sessions.GetSessionClient(item.SessionId).ReplyToPermissionAsync(\n item.Id, new SessionPermissionReplyRequest { Decision = decision }, cancellationToken: cancellationToken);"); + await Assert.That(code).IsEqualTo("// The card supplies PermissionReply.Reject, PermissionReply.Always, or PermissionReply.Once.\n_ = await client.Sessions.GetSessionClient(item.SessionId).ReplyToPermissionAsync(\n item.Id, new SessionPermissionReplyRequest { Decision = decision }, cancellationToken: cancellationToken);"); + } + + [Test] + public async Task ReadAsync_Should_Return_The_First_Source_Line_After_The_Region_Marker() + { + var snippet = await _source.ReadAsync(BoardFile, "form-reply"); + var assembly = typeof(PanelEntry).Assembly; + var name = assembly.GetManifestResourceNames().Single(name => name.Replace('\\', '/') == "hq/" + BoardFile); + await using var stream = assembly.GetManifestResourceStream(name) + ?? throw new InvalidOperationException("The board source is not embedded."); + using var reader = new StreamReader(stream); + var lines = (await reader.ReadToEndAsync()).ReplaceLineEndings("\n").Split('\n'); + var marker = Array.FindIndex(lines, static line => line.Trim() == "#region panel: form-reply"); + + await Assert.That(snippet.FirstLine).IsEqualTo(marker + 2); + await Assert.That(lines[snippet.FirstLine - 1].TrimStart()).IsEqualTo(snippet.Code.Split('\n')[0]); } } diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/NeedsYouItemTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/NeedsYouItemTests.cs new file mode 100644 index 00000000..db616dd1 --- /dev/null +++ b/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/NeedsYouItemTests.cs @@ -0,0 +1,51 @@ +using System.Text.Json; +using OpenCode.Playground.Hq.Features.Sessions; +using OpenCode.Sdk.Models; +using TUnit.Assertions.Enums; + +namespace OpenCode.Playground.Hq.Tests.Features.Sessions; + +public sealed class NeedsYouItemTests +{ + [Test] + public async Task PreviewFiles_Should_Keep_The_File_And_Patch_From_Metadata() + { + var files = JsonSerializer.SerializeToElement(new[] { new { file = "a.cs", patch = "@@ -1 +1 @@\n-old\n+new" } }); + var item = NeedsYouItem.FromPermission(new PermissionRequest + { + Id = "ask", + SessionId = "session", + Action = "edit", + Resources = ["a.cs"], + Metadata = new Dictionary(StringComparer.Ordinal) { ["files"] = files }, + }); + + await Assert.That(item.PreviewFiles.Select(static file => file.Key)).IsEquivalentTo(["a.cs"], CollectionOrdering.Matching); + await Assert.That(item.PreviewFiles.Single().Value).IsEqualTo("@@ -1 +1 @@\n-old\n+new"); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task PreviewFiles_Should_Omit_Missing_Patches_And_Missing_Files(bool missingPatch) + { + var item = new NeedsYouItem("ask", "session", "edit") + { + Metadata = missingPatch + ? new Dictionary(StringComparer.Ordinal) + { + ["files"] = JsonSerializer.SerializeToElement(new[] { new { file = "a.cs" } }), + } + : null, + }; + + await Assert.That(item.PreviewFiles).IsEmpty(); + } + + [Test] + public async Task KindFor_Should_Use_The_Upstream_Description_Or_No_Description() + { + await Assert.That(NeedsYouItem.KindFor("edit")).IsEqualTo("Modify files, including edits, writes, and patches"); + await Assert.That(NeedsYouItem.KindFor("shell")).IsNull(); + } +} diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionBoardTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionBoardTests.cs index 279b4266..3be65511 100644 --- a/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionBoardTests.cs +++ b/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionBoardTests.cs @@ -11,6 +11,108 @@ namespace OpenCode.Playground.Hq.Tests.Features.Sessions; public sealed class SessionBoardTests { + [Test] + public async Task AnswerAsync_Should_Send_Always_For_The_Request_And_Session() + { + await using var scenario = new BoardScenario(); + await scenario.StartAsync(); + var item = scenario.Board.NeedsYou.Single(static ask => ask.Id == "ask_first"); + await scenario.Board.AnswerAsync(item, PermissionReply.Always, CancellationToken.None); + + await Assert.That(scenario.SessionCalls.PermissionSession).IsEqualTo("ses_0"); + await Assert.That(scenario.SessionCalls.PermissionId).IsEqualTo("ask_first"); + await Assert.That(scenario.SessionCalls.Decision?.ToString()).IsEqualTo("always"); + await Assert.That(scenario.Board.NeedsYou.Select(static ask => ask.Id)) + .IsEquivalentTo(["ask_gone", "ask_last", "form_first", "form_gone", "form_last"], CollectionOrdering.Matching); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task DismissFormAsync_Should_Cancel_The_Form_Or_Report_The_Refusal(bool refused) + { + await using var scenario = new BoardScenario(); + await scenario.StartAsync(); + scenario.SessionCalls.FormFailure = refused ? Unauthorized() : null; + await scenario.Board.DismissFormAsync(Form(), CancellationToken.None); + + await Assert.That(scenario.SessionCalls.CancelSession).IsEqualTo("ses_0"); + await Assert.That(scenario.SessionCalls.CancelId).IsEqualTo("form_first"); + await Assert.That(scenario.Board.LastError).IsEqualTo(refused ? "Could not answer the question: unauthorized" : null); + var expected = refused ? new[] { "ask_first", "ask_gone", "ask_last", "form_first", "form_gone", "form_last" } + : ["ask_first", "ask_gone", "ask_last", "form_gone", "form_last"]; + await Assert.That(scenario.Board.NeedsYou.Select(static ask => ask.Id)).IsEquivalentTo(expected, CollectionOrdering.Matching); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task SessionBoard_Should_Relist_Asks_When_A_Turn_Ends_Except_On_Shutdown(bool shutdown) + { + await using var scenario = new BoardScenario(); + await scenario.StartAsync(); + scenario.SessionCalls.Pending = ["ask_last"]; + await scenario.SendAsync(new SessionExecutionInterrupted + { + Id = "interrupted", + Created = 2, + Durable = new() { AggregateId = "ses_0", Seq = 2, Version = 1 }, + Data = new() + { + SessionId = "ses_0", + Reason = shutdown ? SessionExecutionInterruptedDataReason.Shutdown : SessionExecutionInterruptedDataReason.User, + }, + }); + + string[] expected = shutdown ? ["ask_first", "ask_gone", "ask_last", "form_first", "form_gone", "form_last"] : ["ask_last"]; + string[] relisted = shutdown ? [] : ["ses_0"]; + await Assert.That(scenario.Board.NeedsYou.Select(static ask => ask.Id)).IsEquivalentTo(expected, CollectionOrdering.Matching); + await Assert.That(scenario.SessionCalls.Relisted).IsEquivalentTo(relisted, CollectionOrdering.Matching); + } + + [Test] + public async Task ResyncAsync_Should_Replace_Only_That_Sessions_Asks_With_The_Servers_List() + { + await using var scenario = new BoardScenario(); + await scenario.StartAsync(); + await scenario.SendAsync(new PermissionAsked + { + Id = "asked", + Created = 2, + Data = new() { Id = "ask_other", SessionId = "ses_1", Action = "edit", Resources = ["other"] }, + }); + scenario.SessionCalls.Pending = ["ask_last"]; + await scenario.Board.ResyncAsync("ses_0", CancellationToken.None); + + await Assert.That(scenario.Board.NeedsYou.Select(static ask => ask.Id)).IsEquivalentTo(["ask_last", "ask_other"], CollectionOrdering.Matching); + await Assert.That(scenario.SessionCalls.Relisted).IsEquivalentTo(["ses_0"], CollectionOrdering.Matching); + } + + [Test] + public async Task SessionBoard_Should_Apply_A_Title_After_An_Untitled_Session_Is_Created() + { + await using var scenario = new BoardScenario(); + await scenario.StartAsync(); + scenario.SessionCalls.Items = [Session(9, "new") with { Title = null }]; + await scenario.SendAsync(new SessionCreated + { + Id = "created", + Created = 1, + Durable = new() { AggregateId = "ses_9", Seq = 1, Version = 1 }, + Data = new() { SessionId = "ses_9", ProjectId = "project", Location = new() { Directory = "new" }, Slug = "new", Version = "2.3.2" }, + }); + await Assert.That(scenario.Board.Sessions.Single(static row => row.Session.Id == "ses_9").Session.Title).IsNull(); + await scenario.SendAsync(new SessionRenamed + { + Id = "renamed", + Created = 2, + Durable = new() { AggregateId = "ses_9", Seq = 2, Version = 1 }, + Data = new() { SessionId = "ses_9", Title = "Later title" }, + }); + + await Assert.That(scenario.Board.Sessions.Single(static row => row.Session.Id == "ses_9").Session.Title).IsEqualTo("Later title"); + } + [Test] public async Task SessionBoard_Should_Report_A_Watch_Fault_Before_Shutdown() { @@ -432,9 +534,16 @@ private sealed class BoardSessions : SessionsClient public IReadOnlySet Active { get; set; } = new HashSet(["ses_0", "ses_1", "ses_2"], StringComparer.Ordinal); public OpenCodeApiException? ReplyFailure { get; set; } public OpenCodeException? FormFailure { get; set; } + public string? CancelSession { get; set; } + public string? CancelId { get; set; } + public string? PermissionSession { get; set; } + public string? PermissionId { get; set; } + public PermissionReply? Decision { get; set; } + public IReadOnlyList Pending { get; set; } = []; + public List Relisted { get; } = []; public TaskCompletionSource ListingStarted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource? ListingRelease { get; set; } - public override SessionClient GetSessionClient(string sessionId) => new BoardSession(this); + public override SessionClient GetSessionClient(string sessionId) => new BoardSession(this, sessionId); public override Task GetActiveAsync(OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) => Task.FromResult(new SessionActiveResponse { Status = 200, Active = Active.ToDictionary(static id => id, static _ => new SessionActive { Type = "running" }, StringComparer.Ordinal) }); public override async Task ListSessionsAsync(SessionListRequest? request = null, @@ -468,8 +577,33 @@ public override async Task ListSessionsAsync(SessionListReq } } - private sealed class BoardSession(BoardSessions owner) : SessionClient + private sealed class BoardSession(BoardSessions owner, string sessionId) : SessionClient { + public override Task CancelFormAsync(string formId, SessionFormCancelRequest? request = null, + OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) + { + owner.CancelSession = sessionId; + owner.CancelId = formId; + return owner.FormFailure is { } failure ? Task.FromException(failure) + : Task.FromResult(new SessionFormCancelResponse { Status = 204 }); + } + + public override Task GetAsync(OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) => + Task.FromResult(new SessionResponse { Status = 200, Session = owner.Items.Single(item => item.Id == sessionId) }); + + public override Task ListRequestsAsync(OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) + { + owner.Relisted.Add(sessionId); + return Task.FromResult(new SessionPermissionListResponse + { + Status = 200, + Requests = [.. owner.Pending.Select(id => new PermissionRequest { Id = id, SessionId = sessionId, Action = "edit", Resources = ["file"] })], + }); + } + + public override Task ListFormsAsync(OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) => + Task.FromResult(new SessionFormListResponse { Status = 200, Forms = [] }); + public override Task ReplyToFormAsync(string formId, SessionFormReplyRequest request, OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) { @@ -479,8 +613,14 @@ public override Task ReplyToFormAsync(string formId, S } public override Task ReplyToPermissionAsync(string requestId, SessionPermissionReplyRequest request, - OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) => - owner.ReplyFailure is { } failure ? Task.FromException(failure) : Task.FromResult(new SessionPermissionReplyResponse { Status = 204 }); + OpenCodeRequestOptions? requestOptions = null, CancellationToken cancellationToken = default) + { + owner.PermissionSession = sessionId; + owner.PermissionId = requestId; + owner.Decision = request.Decision; + return owner.ReplyFailure is { } failure ? Task.FromException(failure) + : Task.FromResult(new SessionPermissionReplyResponse { Status = 204 }); + } } private sealed class BoardPermissions : PermissionsClient diff --git a/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionsScreenTests.cs b/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionsScreenTests.cs new file mode 100644 index 00000000..8c0548b1 --- /dev/null +++ b/tests/OpenCode.Playground.Hq.Tests/Features/Sessions/SessionsScreenTests.cs @@ -0,0 +1,14 @@ +using OpenCode.Playground.Hq.Features.Sessions; + +namespace OpenCode.Playground.Hq.Tests.Features.Sessions; + +public sealed class SessionsScreenTests +{ + [Test] + [Arguments(@"C:\work\project", "project")] + [Arguments("/work/project", "project")] + [Arguments(@"C:\work\project\", "project")] + [Arguments("/work/project/", "project")] + public async Task FolderName_Should_Take_The_Last_Segment_Of_Either_Path_Style(string path, string expected) => + await Assert.That(SessionsScreen.FolderName(path)).IsEqualTo(expected); +}