AnyEvent-MCP

 view release on metacpan or  search on metacpan

t/e11_permission_ui.t  view on Meta::CPAN

use common::sense;
use JSON::XS ();
open my $fh, "<", $ENV{PERL_ANYEVENT_MCP_TEST_UI_QUEUE} or die $!;
local $/;
my $queue = JSON::XS::decode_json <$fh>;
close $fh;
my $response = shift @$queue or die "Unexpected YAD invocation";
open $fh, ">", $ENV{PERL_ANYEVENT_MCP_TEST_UI_QUEUE} or die $!;
print {$fh} JSON::XS::encode_json $queue;
close $fh;
open $fh, ">>", $ENV{PERL_ANYEVENT_MCP_TEST_UI_LOG} or die $!;
print {$fh} JSON::XS::encode_json (\@ARGV), "\n";
close $fh;
if (grep $_ eq "--text-info", @ARGV) {
   my ($filename) = map { /\A--filename=(.*)\z/ ? $1 : () } @ARGV;
   die "Viewer needs existing file\n" unless defined $filename && -f $filename;
   open my $viewer, "<", $filename or die $!;
   binmode $viewer;
   local $/;
   my $contents = <$viewer>;
   close $viewer;
   open my $viewlog, ">>", $ENV{PERL_ANYEVENT_MCP_TEST_VIEW_LOG} or die $!;
   print {$viewlog} JSON::XS::encode_json ({
      contents_hex => unpack ("H*", $contents),
      mode => ((stat $filename)[2] & 0777),
   }), "\n";
   close $viewlog;
}
if ($response->{click_view}) {
   require Text::ParseWords;
   my ($index) = grep $ARGV[$_] eq "--field=$response->{click_view}...:FBTN", 0 .. $#ARGV;
   die "No View stdin form button\n" unless defined $index;
   my $command = $ARGV[$index + 1];
   die "No View stdin action\n" unless defined $command;
   my @cmd = Text::ParseWords::shellwords ($command);
   die "Invalid viewer command\n" unless @cmd && $cmd[0] eq "yad";
   system { $cmd[0] } @cmd;
   die "Viewer did not complete\n" if $?;
}
if (grep $_ eq "--form", @ARGV) {
   for my $i (0 .. $#ARGV) {
      print "\x1f" if $ARGV[$i] =~ /\A--field=.*:(?:LBL|FBTN)\z/;
   }
}
print $response->{output};
exit $response->{status};
};
chmod 0700, "$dir/yad" or die $!;

local %ENV = (
   %ENV, PATH => "$dir:$ENV{PATH}", DISPLAY => ":test", WAYLAND_DISPLAY => "",
   PERL_ANYEVENT_MCP_TEST_UI_QUEUE => "$dir/queue",
   PERL_ANYEVENT_MCP_TEST_UI_LOG => "$dir/log",
   PERL_ANYEVENT_MCP_TEST_VIEW_LOG => "$dir/view_log",
);
my @prompt_options;
sub prompt {
   my ($request, @responses) = @_;
   write_file "$dir/queue", $json->encode (\@responses);
   my ($output, $error);
   my $input = AnyEvent::MCP::utf8enc ($json->encode ($request));
   my $status = AnyEvent::Util::run_cmd (
      [$^X, "-Ilib", "-MPOSIX", "-e",
         'defined POSIX::setsid () or die $!; do shift @ARGV; die $@ if $@;',
         "./bin/anyevent-mcp-askpermission", @prompt_options],
      "<" => \$input, ">" => \$output, "2>" => \$error,
   )->recv;
   is $status, 0, "helper returns a decision successfully";
   my $decision = eval { JSON::XS::decode_json $output };
   my $decode_error = $@;
   diag "permission helper status=", (defined $status ? $status : "undef"),
      " stderr=", $json->encode ($error), " stdout=", $json->encode ($output),
      " decode error=", $decode_error
      if !defined $status || $status != 0 || $decode_error;
   die $decode_error if $decode_error;
   $decision
}

is +(AnyEvent::MCP::Server::Permissions->new)->{ask}, "helper", "approval defaults to a local helper";
my $decision = prompt $request, { status => 4, output => "Do it, wrong file\x1f\n" };
is_deeply $decision, { decision => "allow-once", sandbox_grants => ["write"] },
   "allow-once uses requested grants and discards denial reason";
{
   open my $log, "<", "$dir/log" or die $!;
   my $args = $json->decode (scalar <$log>);
   close $log;
   my @labels = grep /\A--field=.*:LBL\z/, @$args;
   is_deeply \@labels, ["--field=Action: write:LBL", "--field=Reason: Change the file:LBL",
      "--field=File: \"/one/file\":LBL"], "request context is read-only labels";
   ok !(grep /\A--field=.*:CHK\z/, @$args) && !(grep /\A--field=.*:CB\z/, @$args),
      "initial YAD dialog has no grant or rule-scope selectors";
   ok +(grep $_ eq "--field=Denial reason (optional)", @$args),
      "denial reason appears in form above decision buttons";
   is_deeply [grep /\A--button=/, @$args], [
      "--button=Deny once:0", "--button=Deny always...:6",
      "--button=Allow always...:8", "--button=Allow once:4",
   ], "one-time decisions are at the outside edges";
   ok +(grep /\A--text=Required grants: write\z/, @$args),
      "requested grants appear as a read-only compact line";
   ok +(grep $_ eq "--focus-field=4", @$args),
      "initial focus is in optional message field";
}

my $multiline = { %$request, reason => "Execute in Vim\n\necho 'hello'\x1b" };
like AnyEvent::MCP::Permissions::Ask::message ($multiline),
   qr/Reason: Execute in Vim\n\necho 'hello'\\u\{1B\}/,
   "MCP and terminal reasons preserve newlines and escape terminal controls";
prompt $multiline, { status => 0, output => "\x1f\n" };
{
   open my $log, "<", "$dir/log" or die $!;
   my $line;
   $line = $_ while <$log>;
   close $log;
   my $args = $json->decode ($line);
   ok +(grep $_ eq "--field=Reason: Execute in Vim\n\necho 'hello'\\\\u{1B}:LBL", @$args),
      "YAD reason preserves line breaks and protects escaped controls from YAD decoding";
}

# Display-only input can be viewed without dismissing the approval form.
# The fake YAD "clicks" View stdin, launches the separate text-info viewer,
# then continues the original approval.
my $source = "\x{03c0}\nprint \"ok\";\0\x1b"; # Unicode plus controls
my $preview = {
   %$request,
   details => { "View stdin" => $source },
};
my $viewed = prompt $preview,
   { status => 4, output => "Approved after viewing\x1f\n", click_view => "View stdin" },
   { status => 0, output => "" };
is_deeply $viewed, { decision => "allow-once", sandbox_grants => ["write"] },
   "separate viewer leaves original approval decision unchanged";
{
   open my $log, "<", "$dir/log" or die $!;
   my @entries = map $json->decode ($_), <$log>;
   close $log;
   my $form = $entries[-2];
   my $popup = $entries[-1];
   ok +(grep $_ eq "--field=View stdin...:FBTN", @$form),
      "approval dialog has an inline View stdin button";
   is_deeply [grep /\A--button=/, @$form], [
      "--button=Deny once:0", "--button=Deny always...:6",
      "--button=Allow always...:8", "--button=Allow once:4",
   ], "viewer never shifts or replaces any approval decision buttons";
   ok +(grep $_ eq "--text-info", @$popup),
      "click opens a YAD text-info dialog";
   ok +(grep $_ eq "--fontname=Monospace 11", @$popup),
      "popup uses a monospace source viewer";
   ok +(grep /--field=View stdin: .* characters, .* UTF-8 bytes:LBL/, @$form),
      "approval dialog identifies stdin without embedding its source";
   unlike $json->encode ($form), qr/print \\"ok\\"/,
      "source is not interpolated into the main dialog command line";
   open my $fh, "<", "$dir/view_log" or die $!;
   my $details = $json->decode (scalar <$fh>);
   close $fh;
   is $details->{mode}, 0600, "popup reads a private mode-0600 file";
   my $visible = pack "H*", $details->{contents_hex};
   is AnyEvent::MCP::utf8dec ($visible),
      AnyEvent::MCP::Permissions::Ask::detail_text ("View stdin", $source),
      "popup shows Unicode source and visibly escapes control characters";
}
my $truncated = prompt {
   %$preview, details => { "View stdin" => "first chunk" . ("x" x 65536) },
}, { status => 0, output => "\x1f\n", click_view => "View stdin" },
   { status => 0, output => "" };
is $truncated->{decision}, "deny-once", "viewing incomplete input does not force approval";
{
   open my $fh, "<", "$dir/view_log" or die $!;
   my $line;
   $line = $_ while <$fh>;
   close $fh;
   my $info = $json->decode ($line);
   like AnyEvent::MCP::utf8dec (pack "H*", $info->{contents_hex}),
      qr/65547 characters.*WARNING: INCOMPLETE PREVIEW.*first chunk/s,
      "UI bounds complete detail text and conspicuously warns about the incomplete preview";
}

my $patch_details = {
   %$request,
   details => {
      "View patch" => "File: /one/file\n\n@@ -1 @@\n-old\n+new\n",
      "More: context" => "second detail\n",
   },
};
my $patch_decision = prompt $patch_details,
   { status => 0, output => "Wrong change\x1f\n", click_view => "View patch" },
   { status => 0, output => "" };
is_deeply $patch_decision, { decision => "deny-once", message => "Wrong change" },
   "multiple generic details preserve denial reason and decision";
{
   open my $log, "<", "$dir/log" or die $!;
   my @entries = map $json->decode ($_), <$log>;
   close $log;
   is_deeply [grep /:FBTN\z/, @{$entries[-2]}],
      ["--field=More\\\\u{3A} context...:FBTN", "--field=View patch...:FBTN"],
      "generic labels are sorted, protect YAD syntax and receive UI ellipses";
}
like AnyEvent::MCP::Permissions::Ask::message ($patch_details),
   qr/View patch: .*File: \/one\/file.*-old\n\+new\n/s,
   "native MCP and terminal messages include the generic patch preview";
like AnyEvent::MCP::Permissions::Ask::detail_text ("Long", "x" x 65537),
   qr/65537 characters.*INCOMPLETE PREVIEW.*(?:x{16384}){4}\z/s,
   "shared detail formatter bounds the visible preview";
my $invalid = eval {
   AnyEvent::MCP::Server::Permissions->new->check ({
      action => "read", sandbox_grants => [], reason => "invalid detail",
      details => { Broken => [] },
   });
   1
};
ok !$invalid && $@ =~ /detail must be text/, "permission boundary rejects non-text details";

my $path_request = {
   %$request, dimensions => {}, paths => ["/one/file", "/two/file"],
};
$decision = prompt $path_request, { status => 0, output => "Use a different file\x1f\n" };
is_deeply $decision, { decision => "deny-once", message => "Use a different file" },
   "denial immediately returns optional human message";
my $configured_path = "/projects/../projects/code";
my $scoped_description = {
   %$path_request, sandbox_grants => ["write"],
   sandbox_grant_descriptions => {
      read => "Read files in selected workdir \"$configured_path\"",
      write => "Change files in selected workdir \"$configured_path\"",
   },
};
my $shared_message = AnyEvent::MCP::Permissions::Ask::message ($scoped_description);
like $shared_message, qr/\APermission request\nRequested sandbox grants: write\n/,
   "MCP and TTY display requested grants near top of prompt";

my $elicitation_schema = AnyEvent::MCP::Permissions::Ask::schema ($scoped_description);
ok $elicitation_schema->{properties}{message}
   && !exists $elicitation_schema->{properties}{sandbox_grants}



( run in 1.416 second using v1.01-cache-2.11-cpan-234fa220139 )