diff --git a/src/VelaShell.PluginSdk.Testing/FakeTerminal.cs b/src/VelaShell.PluginSdk.Testing/FakeTerminal.cs index 23d3741..7100377 100644 --- a/src/VelaShell.PluginSdk.Testing/FakeTerminal.cs +++ b/src/VelaShell.PluginSdk.Testing/FakeTerminal.cs @@ -57,4 +57,44 @@ public Task WriteAsync(string sessionId, string input, CancellationToken cancell Writes.Add((sessionId, input)); return Task.CompletedTask; } + + private readonly Dictionary _blockActions = [with(StringComparer.Ordinal)]; + + /// 为 false 时模拟旧宿主: 抛 。默认 true。 + public bool CommandBlockActionsSupported { get; set; } = true; + + /// + public bool SupportsCommandBlockActions => CommandBlockActionsSupported; + + /// 当前登记着的命令块动作(按 id)。 + public IReadOnlyDictionary BlockActions => _blockActions; + + /// + /// 替身不核对 id 前缀(它不知道插件 id);宿主会核对,见接口说明。 + public IDisposable RegisterCommandBlockAction(CommandBlockActionDescriptor action) + { + ArgumentNullException.ThrowIfNull(action); + if (!CommandBlockActionsSupported) + { + throw new NotSupportedException("This host does not support terminal command block actions."); + } + _blockActions[action.Id] = action; + return new BlockActionRegistration(this, action); + } + + /// 模拟用户在侧栏右键一条命令块、点了 。动作没登记时抛 。 + public Task ClickCommandBlockActionAsync(string actionId, TerminalCommandBlock block, CancellationToken cancellationToken = default) => + _blockActions[actionId].ExecuteAsync(block, cancellationToken); + + private sealed class BlockActionRegistration(FakeTerminal owner, CommandBlockActionDescriptor action) : IDisposable + { + public void Dispose() + { + // 同 id 已被后来的登记替换时不误删那一份。 + if (owner._blockActions.TryGetValue(action.Id, out CommandBlockActionDescriptor? current) && ReferenceEquals(current, action)) + { + owner._blockActions.Remove(action.Id); + } + } + } } diff --git a/src/VelaShell.PluginSdk/Rpc/PluginRpc.cs b/src/VelaShell.PluginSdk/Rpc/PluginRpc.cs index 9cd55a7..9673c02 100644 --- a/src/VelaShell.PluginSdk/Rpc/PluginRpc.cs +++ b/src/VelaShell.PluginSdk/Rpc/PluginRpc.cs @@ -212,6 +212,16 @@ public static class PluginRpc /// 终端:回写输入(需用户授权;拒绝时应答 permission-denied)。 public const string TerminalWrite = "terminal/write"; + /// + /// 登记命令块动作(,载荷 ); + /// 回调留在插件进程,用户点了之后宿主发 通知。 + /// 握手未宣告 时 PluginHost 不发这条。可用版本:TBD(发版时替换)。 + /// + public const string TerminalBlockActionRegister = "terminal/blockAction/register"; + + /// 撤下命令块动作(载荷 ,Id 为动作 id)。可用版本:TBD(发版时替换)。 + public const string TerminalBlockActionUnregister = "terminal/blockAction/unregister"; + /// 面板数变化通知(插件 → 宿主):驱动"无打开面板"的空闲回收条件。 public const string UiSurfaces = "ui/surfaces"; @@ -245,6 +255,11 @@ public static class PluginRpc /// 命令被用户触发(通知)。 public const string CommandExecute = "command/execute"; + /// + /// 用户点了插件登记的命令块动作(通知,载荷 )。可用版本:TBD(发版时替换)。 + /// + public const string TerminalBlockActionInvoke = "terminal/blockAction/invoke"; + /// 宿主事件通知:kind = sessionConnected / sessionDisconnected / themeChanged / localeChanged。 public const string HostEvent = "host/event"; @@ -313,6 +328,12 @@ public sealed record HandshakeResponse(int ApiLevel, string HostVersion, string /// 。缺席即旧宿主,不会应答这个错误码。可用版本:TBD(发版时替换)。 /// public bool SupportsSecretsLocked { get; init; } + + /// + /// 支持命令块动作( / ); + /// PluginHost 据此给出 。缺席即旧宿主,不支持。可用版本:TBD(发版时替换)。 + /// + public bool SupportsCommandBlockActions { get; init; } } /// 会话查询参数。 @@ -515,6 +536,51 @@ public sealed record TerminalMatchDto(int Line, string Text); /// 终端回写载荷。 public sealed record TerminalWriteRequest(string SessionId, string Input); +/// 命令块动作登记参数(回调留在插件进程)。可用版本:TBD(发版时替换)。 +/// 动作 id(插件id. 开头)。 +/// 菜单文字。 +/// 块已知失败时的菜单文字; = 一律用 。 +public sealed record CommandBlockActionRegistration(string Id, string Title, string? FailedTitle); + +/// 命令块动作被点了(宿主 → 插件通知)。字段与 一一对应。可用版本:TBD(发版时替换)。 +/// 被点的动作 id。 +/// 见 。 +/// 见 。 +/// 见 。 +/// 见 。 +/// 见 。 +/// 见 。 +/// 见 。 +/// 见 。 +public sealed record TerminalCommandBlockInvocation( + string ActionId, + string SessionId, + string? Command, + string Output, + int? ExitCode, + int OmittedLines, + bool HadHiddenText, + string? WorkingDirectory, + string? Host) +{ + /// 由快照构造线协载荷。 + public static TerminalCommandBlockInvocation From(string actionId, Terminal.TerminalCommandBlock block) + { + ArgumentNullException.ThrowIfNull(block); + return new(actionId, block.SessionId, block.Command, block.Output, block.ExitCode, + block.OmittedLines, block.HadHiddenText, block.WorkingDirectory, block.Host); + } + + /// 还原成交给插件回调的快照。 + public Terminal.TerminalCommandBlock ToBlock() => new(SessionId, Command, Output, ExitCode) + { + OmittedLines = OmittedLines, + HadHiddenText = HadHiddenText, + WorkingDirectory = WorkingDirectory, + Host = Host + }; +} + /// 面板数变化通知载荷。 public sealed record UiSurfacesNotification(int Count); diff --git a/src/VelaShell.PluginSdk/Terminal/CommandBlockActions.cs b/src/VelaShell.PluginSdk/Terminal/CommandBlockActions.cs new file mode 100644 index 0000000..119aa73 --- /dev/null +++ b/src/VelaShell.PluginSdk/Terminal/CommandBlockActions.cs @@ -0,0 +1,59 @@ +namespace VelaShell.PluginSdk.Terminal; + +/// +/// 用户在终端侧栏右键一条 OSC 133 命令块、点了插件登记的动作时,宿主交给插件的那一块的快照。 +/// +/// +/// +/// 只在用户点了之后才交出去:插件拿不到用户没点过的块,也不能自己枚举命令块。 +/// 宿主在菜单弹出那一刻切好快照,插件拿到的就是用户此刻在菜单里点的那一块。 +/// +/// +/// 输出已经清洗过:控制字符与 SGR 8 隐藏的字(屏幕上看不见)由宿主剔掉,只留块尾若干行 +/// (上限由宿主定,丢掉的行数见 )。隐藏的字是往下游(比如模型)夹带指令的通道, +/// 剔过没有见 。命令里夹着隐藏内容的块(多半是输出里伪造的标记)宿主根本不给点。 +/// +/// 可用版本:TBD(发版时替换)。 +/// +/// 块所在会话的 id(与 同一套)。 +/// 用户敲的命令;对端 shell 集成不报命令起点(OSC 133 的 B)时为 。 +/// 块尾的输出;逻辑行之间用 \n,没有输出时为空串。 +/// 退出码;对端没报时为 —— 未知,不等于成功。 +public sealed record TerminalCommandBlock(string SessionId, string? Command, string Output, int? ExitCode) +{ + /// 宿主从输出前面丢掉的逻辑行数;0 = 一行没丢。 + public int OmittedLines { get; init; } + + /// 输出里有被剔掉的隐藏内容(SGR 8 的字、控制字符)。 + public bool HadHiddenText { get; init; } + + /// shell 上报的工作目录(OSC 7 等);没报时为 。 + public string? WorkingDirectory { get; init; } + + /// + /// 给人或模型读的主机描述:SSH 会话是 用户@主机(端口不是 22 时带上),本地终端是 local: shell 名; + /// 说不清时为 。只作展示,不要拿它去连接。 + /// + public string? Host { get; init; } + + /// 已知失败(退出码非 0)。 + public bool Failed => ExitCode is not null and not 0; +} + +/// 插件往终端侧栏的命令块右键菜单里登记的一个动作()。 +/// 可用版本:TBD(发版时替换)。 +/// 动作 id,必须以 插件id. 开头(与命令同一条命名空间规则)。 +/// 菜单文字。语言切换时按同 id 重新登记即可替换。 +/// +/// 用户点了之后调用。在后台线程调用;异常由宿主捕获并记入插件日志,不会崩溃宿主。 +/// +public sealed record CommandBlockActionDescriptor( + string Id, + string Title, + Func ExecuteAsync) +{ + /// + /// 块已知失败(退出码非 0)时改用的菜单文字(如「让 AI 看看为什么失败」); = 一律用 。 + /// + public string? FailedTitle { get; init; } +} diff --git a/src/VelaShell.PluginSdk/Terminal/ITerminalApi.cs b/src/VelaShell.PluginSdk/Terminal/ITerminalApi.cs index 7e12033..65e959a 100644 --- a/src/VelaShell.PluginSdk/Terminal/ITerminalApi.cs +++ b/src/VelaShell.PluginSdk/Terminal/ITerminalApi.cs @@ -28,4 +28,28 @@ Task> SearchOutputAsync(string sessionId, string pa /// "始终允许"按插件持久化;被拒绝抛 。 /// Task WriteAsync(string sessionId, string input, CancellationToken cancellationToken = default); + + /// + /// 宿主支持命令块动作()。旧宿主为 , + /// 此时调用 抛 。 + /// 可用版本:TBD(发版时替换)。 + /// + bool SupportsCommandBlockActions => false; + + /// + /// 往终端侧栏的 OSC 133 命令块右键菜单里登记一个动作:用户右键一条命令块、点了它,宿主把那一块的快照 + /// ()交给 。 + /// 释放返回值即撤下;插件停用时宿主一并撤下。同 id 再登记替换前一份(语言切换时改文字用)。 + /// + /// + /// + /// 动作排在宿主自己的「复制这条命令」「重跑」之后。这条命令还在跑、或命令里夹着屏幕上看不见的字时宿主把它灰掉; + /// 切不出命令(对端不报 B)但有输出时照样能点,快照里 为 。 + /// + /// 可用版本:TBD(发版时替换)。 + /// + /// 不以 插件id. 开头。 + /// 宿主不支持( 为 )。 + IDisposable RegisterCommandBlockAction(CommandBlockActionDescriptor action) => + throw new NotSupportedException("This host does not support terminal command block actions."); } diff --git a/tests/VelaShell.PluginSdk.Tests/CommandBlockActionContractTests.cs b/tests/VelaShell.PluginSdk.Tests/CommandBlockActionContractTests.cs new file mode 100644 index 0000000..071c035 --- /dev/null +++ b/tests/VelaShell.PluginSdk.Tests/CommandBlockActionContractTests.cs @@ -0,0 +1,121 @@ +using System.Text.Json; +using VelaShell.PluginSdk.Rpc; +using VelaShell.PluginSdk.Terminal; +using VelaShell.PluginSdk.Testing; + +namespace VelaShell.PluginSdk.Tests; + +/// +/// 终端命令块动作:插件往侧栏命令块右键菜单里登记一项,用户点了之后宿主把那一块的快照交给插件。 +/// 旧宿主如实不宣告;线协载荷与快照一一对应;替身能模拟点击。 +/// +[TestClass] +public sealed class CommandBlockActionContractTests +{ + /// 只实现三个必需方法的旧宿主。 + private sealed class LegacyTerminal : ITerminalApi + { + public Task GetOutputAsync(string sessionId, int maxLines = 1000, CancellationToken cancellationToken = default) => + Task.FromResult(""); + + public Task> SearchOutputAsync(string sessionId, string pattern, bool isRegex = false, + int maxMatches = 100, CancellationToken cancellationToken = default) => + Task.FromResult>([]); + + public Task WriteAsync(string sessionId, string input, CancellationToken cancellationToken = default) => Task.CompletedTask; + } + + private static readonly TerminalCommandBlock Block = new("s1", "git push", "rejected", 1) + { + OmittedLines = 12, + HadHiddenText = true, + WorkingDirectory = "/srv/app", + Host = "root@web-1" + }; + + [TestMethod] + public void LegacyHost_DoesNotAnnounce_AndRefusesRegistration() + { + ITerminalApi legacy = new LegacyTerminal(); + Assert.IsFalse(legacy.SupportsCommandBlockActions); + Assert.ThrowsExactly(() => + legacy.RegisterCommandBlockAction(new("p.ask", "Ask", (_, _) => Task.CompletedTask))); + } + + [TestMethod] + public void Block_UnknownExitCodeIsNotFailure() + { + Assert.IsTrue(Block.Failed); + Assert.IsFalse((Block with { ExitCode = 0 }).Failed); + Assert.IsFalse((Block with { ExitCode = null }).Failed, "对端没报退出码 = 未知,不能当失败也不能当成功"); + } + + [TestMethod] + public void Invocation_RoundTripsTheWholeSnapshot() + { + TerminalCommandBlockInvocation wire = TerminalCommandBlockInvocation.From("p.ask", Block); + TerminalCommandBlockInvocation back = JsonSerializer.Deserialize(JsonSerializer.Serialize(wire))!; + + Assert.AreEqual(wire, back); + Assert.AreEqual("p.ask", back.ActionId); + Assert.AreEqual(Block, back.ToBlock(), "线协载荷的字段与快照一一对应,一个都不能丢"); + Assert.HasCount( + typeof(TerminalCommandBlock).GetProperties().Count(p => p.Name != nameof(TerminalCommandBlock.Failed)) + 1, + typeof(TerminalCommandBlockInvocation).GetMethod("Deconstruct")!.GetParameters(), + "快照加了字段,线协载荷要跟着加(多出来的一个是 ActionId)"); + } + + [TestMethod] + public void Registration_CarriesTheFailedTitle() + { + var registration = new CommandBlockActionRegistration("p.ask", "Ask AI", "Ask AI why this failed"); + Assert.AreEqual(registration, + JsonSerializer.Deserialize(JsonSerializer.Serialize(registration))); + } + + [TestMethod] + public void WireNames_AreStable() + { + Assert.AreEqual("terminal/blockAction/register", PluginRpc.TerminalBlockActionRegister); + Assert.AreEqual("terminal/blockAction/unregister", PluginRpc.TerminalBlockActionUnregister); + Assert.AreEqual("terminal/blockAction/invoke", PluginRpc.TerminalBlockActionInvoke); + } + + [TestMethod] + public void Handshake_MissingFieldMeansLegacyHost() + { + HandshakeResponse legacy = JsonSerializer.Deserialize( + """{"ApiLevel":2,"HostVersion":"1","Locale":"en","Theme":"dark","SupportsSecretsLocked":true}""")!; + Assert.IsFalse(legacy.SupportsCommandBlockActions, "旧宿主不宣告就是不支持"); + HandshakeResponse modern = legacy with { SupportsCommandBlockActions = true }; + Assert.AreEqual(modern, JsonSerializer.Deserialize(JsonSerializer.Serialize(modern))); + } + + [TestMethod] + public async Task Fake_RecordsRegistration_SimulatesClicks_AndUnregisters() + { + var terminal = new FakeTerminal(); + Assert.IsTrue(terminal.SupportsCommandBlockActions); + var received = new List(); + + IDisposable first = terminal.RegisterCommandBlockAction(new("p.ask", "Ask", (b, _) => + { + received.Add(b); + return Task.CompletedTask; + })); + await terminal.ClickCommandBlockActionAsync("p.ask", Block); + Assert.AreSequenceEqual([Block], received); + + // 语言切换:同 id 重新登记替换前一份,释放旧的那份不误删新的。 + IDisposable second = terminal.RegisterCommandBlockAction(new("p.ask", "询问", (_, _) => Task.CompletedTask) { FailedTitle = "为什么失败" }); + first.Dispose(); + Assert.AreEqual("询问", terminal.BlockActions["p.ask"].Title); + second.Dispose(); + Assert.IsEmpty(terminal.BlockActions); + + terminal.CommandBlockActionsSupported = false; + Assert.IsFalse(terminal.SupportsCommandBlockActions); + Assert.ThrowsExactly(() => + terminal.RegisterCommandBlockAction(new("p.ask", "Ask", (_, _) => Task.CompletedTask))); + } +}