Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
03a370f445 | ||
|
|
e8bef94474 | ||
|
|
0f400a58a1 | ||
|
|
e852fde4f4 | ||
|
|
e421c17f2a |
No files matched your search
+12
-1
@@ -6,7 +6,8 @@ endif()
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
|
||||
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.cpp resources/files.rc)
|
||||
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.cpp
|
||||
src/files_mcp.cpp resources/files.rc)
|
||||
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
|
||||
@@ -185,6 +186,16 @@ if(NOT MSVC)
|
||||
target_link_options(KSwitcherFilesModalTests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME files-modal-dialog COMMAND KSwitcherFilesModalTests)
|
||||
add_executable(KSwitcherFilesMcpTests tests/files_mcp.cpp src/files_mcp.cpp)
|
||||
target_include_directories(KSwitcherFilesMcpTests PRIVATE src)
|
||||
target_link_libraries(KSwitcherFilesMcpTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
set_property(TARGET KSwitcherFilesMcpTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
target_link_options(KSwitcherFilesMcpTests PRIVATE -static)
|
||||
endif()
|
||||
add_test(NAME files-mcp COMMAND KSwitcherFilesMcpTests)
|
||||
set_tests_properties(files-mcp PROPERTIES TIMEOUT 30)
|
||||
add_executable(KSwitcherLanTests tests/lan.cpp)
|
||||
target_link_libraries(KSwitcherLanTests PRIVATE kscore)
|
||||
if(MSVC)
|
||||
|
||||
+3
-1
@@ -635,7 +635,7 @@ Warning і початковий фокус на No.
|
||||
розміру, а список має однаковий внутрішній відступ зліва і справа.
|
||||
- Тайм-аут запиту дисків відображається як Connection timed out. Якщо
|
||||
ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий
|
||||
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows.
|
||||
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows. Commands → Files log відкриває до 200 останніх записів поточного або попереднього журналу. Refresh оновлює список. Copy selected або Ctrl+C копіює дату й безпечний опис вибраного запису. Довільні текстові деталі приховано.
|
||||
|
||||
- Застосовані налаштування Files одразу підхоплюють інші відкриті вікна.
|
||||
Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно
|
||||
@@ -741,6 +741,8 @@ Warning і початковий фокус на No.
|
||||
|
||||
- При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання.
|
||||
- Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку.
|
||||
- Commands → Files MCP за замовчуванням зупинений. Start запускає MCP Streamable HTTP на `127.0.0.1` з випадковим портом. Клієнту потрібні Endpoint і `Authorization: Bearer <session token>`. Show token показує токен, Copy token копіює його. Stop і вихід із програми Files відкликають токен. Закриття діалогу залишає сервер активним, і меню показує Files MCP (running). Кожен старт створює новий токен.
|
||||
- MCP має три інструменти для читання. `get_panels` повертає стан поточних локальних панелей, курсор і сторінку записів. `search_files` фільтрує назви або відносні шляхи поточного списку чи наявних результатів Find. `get_file_metadata` повертає кешовані атрибути, тип, розмір і час зміни для вже показаного елемента. Для продовження списку клієнт передає `nextOffset` як `offset`. Вміст файлів, віддалені панелі, архіви й операції запису не входять до цього API. Запити з браузерним Origin відхиляються.
|
||||
- F1 відкриває вбудовану офлайн-довідку для панелі, вибраного пункту меню чи поточного діалогу. Пошук фільтрує теми за назвою й текстом. Esc закриває довідку та повертає фокус. У командному рядку з назвою команди F1 зберігає перехід до її довідки Windows. Загальна довідка також доступна через Commands → Help.
|
||||
- Options → Import JSON / Export JSON переносить вибрані групи збережених параметрів Files. Окремо доступні кольори панелей і порівняння разом зі стилями файлів, режими й компонування панелей та іменовані схеми клавіш. Перед заміною відмінних схем з однаковою назвою Files запитує підтвердження. Імпорт спочатку оновлює чернетку Options. Apply або OK зберігає зміни, Cancel відкидає їх. Формат містить лише ці параметри. Невідомі поля і групи пропускаються.
|
||||
- Commands → Keyboard shortcuts відкриває іменовані схеми для команд файлових панелей та історії команд. У схемі можна задати кілька клавіш, вибрати основну, вилучити прив’язку, скопіювати схему під новим іменем, перемкнути чи скинути її. OK зберігає активну схему. Меню показує всі прив’язки, нижній ряд і текстові підказки відображають основну. Діалог відхиляє дублікати в контекстах, що перетинаються, і клавіші, зайняті навігацією. Попередні прив’язки історії та порівняння завантажуються як схема Previous settings.
|
||||
|
||||
@@ -214,6 +214,37 @@ BEGIN
|
||||
DEFPUSHBUTTON "&Close", IDOK, 403, 216, 56, 16
|
||||
END
|
||||
|
||||
619 DIALOGEX 0, 0, 435, 211
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Files log"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "&Log", -1, 9, 12, 40, 11
|
||||
COMBOBOX 680, 51, 9, 115, 70, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
LTEXT "", 681, 9, 31, 415, 28
|
||||
LISTBOX 682, 9, 62, 417, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP
|
||||
PUSHBUTTON "&Copy selected", 683, 9, 187, 90, 15
|
||||
PUSHBUTTON "&Refresh", 684, 107, 187, 66, 15
|
||||
DEFPUSHBUTTON "Close", IDOK, 370, 187, 56, 15
|
||||
END
|
||||
|
||||
620 DIALOGEX 0, 0, 395, 152
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Files MCP"
|
||||
FONT 9, "Segoe UI"
|
||||
BEGIN
|
||||
LTEXT "", 690, 9, 9, 376, 12
|
||||
LTEXT "Read-only access to local panes, Find results and file metadata.", -1, 9, 26, 376, 13
|
||||
LTEXT "&Endpoint", -1, 9, 49, 72, 12
|
||||
EDITTEXT 691, 83, 46, 302, 15, ES_READONLY | ES_AUTOHSCROLL
|
||||
LTEXT "Session &token", -1, 9, 72, 72, 12
|
||||
EDITTEXT 692, 83, 69, 302, 15, ES_READONLY | ES_AUTOHSCROLL
|
||||
AUTOCHECKBOX "Sho&w token", 694, 83, 94, 81, 13
|
||||
PUSHBUTTON "&Copy token", 695, 169, 91, 72, 16
|
||||
PUSHBUTTON "&Start", 693, 9, 126, 64, 16
|
||||
DEFPUSHBUTTON "Close", IDOK, 329, 126, 56, 16
|
||||
END
|
||||
|
||||
101 DIALOGEX 0, 0, 397, 310
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN
|
||||
CAPTION "KSwitcher Files Options"
|
||||
|
||||
+1
-1
@@ -8,6 +8,6 @@ inline constexpr UINT filesHelpRequest=WM_APP+273;
|
||||
enum class FilesHelpTopic
|
||||
{
|
||||
panels, menus, navigation, find, transfer, deleteFiles, archive, space, properties, connections,
|
||||
terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, count
|
||||
terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, log, mcp, count
|
||||
};
|
||||
}
|
||||
+11
-1
@@ -69,7 +69,13 @@ constexpr struct
|
||||
L"Viewer and Editor can use System (Windows). Assign either a stock or named palette to each Windows mode under Appearance → System themes."},
|
||||
{L"Import and export settings",L"json portable backup restore transfer option groups",
|
||||
L"Select the saved settings groups to include in an export. The supported groups cover colors and file styles, panel layout and keyboard schemes.\r\n\r\n"
|
||||
L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."}
|
||||
L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."},
|
||||
{L"Files log",L"diagnostic journal error logging rotate copy record",
|
||||
L"Open Files log from Commands to see recent entries. Switch between the current and previous rotated log, or use Refresh to read newer entries.\r\n\r\n"
|
||||
L"Select an entry to copy its timestamp and summary. The viewer shows only supported diagnostic details."},
|
||||
{L"Files MCP",L"local loopback bearer authorization model context protocol read only search token",
|
||||
L"Open Commands → Files MCP and select Start. Configure the client with the displayed loopback endpoint and use the session token as the bearer credential.\r\n\r\n"
|
||||
L"The client can read current local panes, search their displayed entries and read cached file metadata. Stop revokes the session token."}
|
||||
};
|
||||
static_assert(std::size(filesHelpTopics)==static_cast<size_t>(FilesHelpTopic::count));
|
||||
|
||||
@@ -185,6 +191,8 @@ FilesHelpTopic filesMenuHelpTopic()
|
||||
case 19: return FilesHelpTopic::terminal;
|
||||
case 20: return FilesHelpTopic::keys;
|
||||
case 21: return FilesHelpTopic::appearance;
|
||||
case 23: return FilesHelpTopic::log;
|
||||
case 24: return FilesHelpTopic::mcp;
|
||||
default: return FilesHelpTopic::menus;
|
||||
}
|
||||
}
|
||||
@@ -229,6 +237,8 @@ std::optional<FilesHelpTopic> filesHelpForWindow(HWND root,HWND target)
|
||||
case 608: return FilesHelpTopic::appearance;
|
||||
case 615: case 616: return FilesHelpTopic::keys;
|
||||
case 617: return FilesHelpTopic::portability;
|
||||
case 619: return FilesHelpTopic::log;
|
||||
case 620: return FilesHelpTopic::mcp;
|
||||
case 604: case 607:
|
||||
if(const auto owner=GetWindow(root,GW_OWNER);owner && owner!=root)
|
||||
return filesHelpForWindow(owner,owner);
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
constexpr int filesLogSource=680,filesLogStatus=681,filesLogEntries=682,filesLogCopy=683,filesLogRefresh=684;
|
||||
constexpr size_t filesLogEntryLimit=200,filesLogReadLimit=256*1024;
|
||||
|
||||
std::optional<unsigned> filesLogError(std::string_view message,std::string_view marker)
|
||||
{
|
||||
const auto last=message.rfind(marker);
|
||||
if(last==message.npos) return {};
|
||||
const auto value=message.substr(last+marker.size());
|
||||
unsigned error{};
|
||||
const auto parsed=std::from_chars(value.data(),value.data()+value.size(),error);
|
||||
if(parsed.ec!=std::errc{} || parsed.ptr!=value.data()+value.size()) return {};
|
||||
return error;
|
||||
}
|
||||
|
||||
std::wstring safeFilesLogEntry(std::string_view line)
|
||||
{
|
||||
if(line.ends_with('\r')) line.remove_suffix(1);
|
||||
std::wstring stamp;
|
||||
constexpr std::string_view format="0000-00-00 00:00:00 ";
|
||||
if(line.size()>=format.size())
|
||||
{
|
||||
bool valid=true;
|
||||
for(size_t i=0;i<format.size();++i)
|
||||
valid&=format[i]=='0'?(line[i]>='0' && line[i]<='9'):line[i]==format[i];
|
||||
if(valid)
|
||||
{
|
||||
stamp=ks::wide(std::string(line.substr(0,format.size()-1)))+L" · ";
|
||||
line.remove_prefix(format.size());
|
||||
}
|
||||
}
|
||||
|
||||
// Only fixed descriptions and numeric Windows result codes cross into the UI or clipboard.
|
||||
std::wstring text;
|
||||
std::optional<unsigned> error;
|
||||
if(line=="LAN Files peer lookup failed: local KSwitcher window not found")
|
||||
text=L"LAN peer lookup failed. KSwitcher is unavailable.";
|
||||
else if(line.starts_with("LAN Files peer lookup failed: delivered="))
|
||||
{
|
||||
text=L"LAN peer lookup failed";
|
||||
error=filesLogError(line,", Windows error=");
|
||||
}
|
||||
else if(line=="LAN Files drive query failed: unexpected error")
|
||||
text=L"LAN drive query failed. Unexpected error.";
|
||||
else if(line.starts_with("LAN Files drive query for "))
|
||||
{
|
||||
text=L"LAN drive query failed";
|
||||
error=filesLogError(line,") failed: Windows error ");
|
||||
if(error==WSAETIMEDOUT) text=L"LAN drive query timed out";
|
||||
}
|
||||
else text=L"Diagnostic entry · details hidden";
|
||||
if(error && *error) text+=L" (Windows error "+std::to_wstring(*error)+L")";
|
||||
return stamp+text;
|
||||
}
|
||||
|
||||
std::vector<std::wstring> recentFilesLogEntries(const ks::Bytes &bytes)
|
||||
{
|
||||
std::vector<std::wstring> entries;
|
||||
if(bytes.empty()) return entries;
|
||||
const std::string_view text(reinterpret_cast<const char*>(bytes.data()),bytes.size());
|
||||
auto end=text.size();
|
||||
while(end && entries.size()<filesLogEntryLimit)
|
||||
{
|
||||
if(text[end-1]=='\n') --end;
|
||||
const auto split=end?text.rfind('\n',end-1):text.npos;
|
||||
const auto begin=split==text.npos?0:split+1;
|
||||
const auto row=text.substr(begin,end-begin);
|
||||
if(!row.empty() && row!="\r") entries.push_back(safeFilesLogEntry(row));
|
||||
end=begin;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
struct FilesLogDraft
|
||||
{
|
||||
std::vector<std::wstring> entries;
|
||||
};
|
||||
|
||||
void refreshFilesLog(HWND dialog,FilesLogDraft &draft)
|
||||
{
|
||||
const bool previous=SendDlgItemMessageW(dialog,filesLogSource,CB_GETCURSEL,0,0)==1;
|
||||
const auto list=GetDlgItem(dialog,filesLogEntries);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
SendMessageW(list,LB_SETHORIZONTALEXTENT,0,0);
|
||||
draft.entries.clear();
|
||||
try
|
||||
{
|
||||
if(const auto data=ks::readActiveLogTail(previous,filesLogReadLimit))
|
||||
{
|
||||
draft.entries=recentFilesLogEntries(*data);
|
||||
SetDlgItemTextW(dialog,filesLogStatus,draft.entries.empty()?L"The Files log has no entries.":
|
||||
L"Most recent first. Select an entry to copy its timestamp and description.");
|
||||
}
|
||||
else SetDlgItemTextW(dialog,filesLogStatus,previous?L"No previous Files log is available yet.":
|
||||
L"No Files log yet. Entries appear when Write log is enabled and Files records a problem.");
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
SetDlgItemTextW(dialog,filesLogStatus,L"Could not read the Files log. Use Refresh to try again.");
|
||||
}
|
||||
int width=0;
|
||||
const auto dc=GetDC(list);
|
||||
const auto font=reinterpret_cast<HFONT>(SendMessageW(list,WM_GETFONT,0,0));
|
||||
const auto oldFont=dc && font?SelectObject(dc,font):nullptr;
|
||||
for(const auto &entry:draft.entries)
|
||||
{
|
||||
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(entry.c_str()));
|
||||
if(dc)
|
||||
{
|
||||
SIZE extent{};
|
||||
GetTextExtentPoint32W(dc,entry.c_str(),static_cast<int>(entry.size()),&extent);
|
||||
width=std::max(width,static_cast<int>(extent.cx)+12);
|
||||
}
|
||||
}
|
||||
if(oldFont) SelectObject(dc,oldFont);
|
||||
if(dc) ReleaseDC(list,dc);
|
||||
if(width) SendMessageW(list,LB_SETHORIZONTALEXTENT,width,0);
|
||||
if(!draft.entries.empty()) SendMessageW(list,LB_SETCURSEL,0,0);
|
||||
EnableWindow(GetDlgItem(dialog,filesLogCopy),!draft.entries.empty());
|
||||
}
|
||||
|
||||
LRESULT CALLBACK filesLogListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||||
{
|
||||
if(message==WM_KEYDOWN && wp=='C' && (GetKeyState(VK_CONTROL)&0x8000) &&
|
||||
!((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
|
||||
{
|
||||
if(!(lp&(1LL<<30))) SendMessageW(GetParent(list),WM_COMMAND,MAKEWPARAM(filesLogCopy,BN_CLICKED),0);
|
||||
return 0;
|
||||
}
|
||||
return DefSubclassProc(list,message,wp,lp);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK filesLogDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &draft=*reinterpret_cast<FilesLogDraft*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
for(const auto name:{L"Current",L"Previous"})
|
||||
SendDlgItemMessageW(dialog,filesLogSource,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
|
||||
SendDlgItemMessageW(dialog,filesLogSource,CB_SETCURSEL,0,0);
|
||||
SetWindowSubclass(GetDlgItem(dialog,filesLogEntries),filesLogListKeys,1,0);
|
||||
refreshFilesLog(dialog,draft);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
auto &draft=*reinterpret_cast<FilesLogDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(LOWORD(wp)==filesLogRefresh || (LOWORD(wp)==filesLogSource && HIWORD(wp)==CBN_SELCHANGE))
|
||||
{
|
||||
refreshFilesLog(dialog,draft);
|
||||
return TRUE;
|
||||
}
|
||||
if(LOWORD(wp)==filesLogCopy)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,filesLogEntries,LB_GETCURSEL,0,0);
|
||||
if(row>=0 && static_cast<size_t>(row)<draft.entries.size())
|
||||
{
|
||||
if(copyFilesText(dialog,draft.entries[row],L"Could not copy the Files log entry."))
|
||||
SetDlgItemTextW(dialog,filesLogStatus,L"Entry copied.");
|
||||
else SetDlgItemTextW(dialog,filesLogStatus,L"Could not copy the Files log entry.");
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void showFilesLog(HWND owner)
|
||||
{
|
||||
FilesLogDraft draft;
|
||||
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(619),owner,filesLogDialog,
|
||||
reinterpret_cast<LPARAM>(&draft),false,false);
|
||||
dialog.runModal();
|
||||
}
|
||||
+15
-2
@@ -16,6 +16,7 @@
|
||||
#include <numbers>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <charconv>
|
||||
#include <atomic>
|
||||
#include <deque>
|
||||
#include <filesystem>
|
||||
@@ -50,6 +51,7 @@
|
||||
#include "files_text_preferences.h"
|
||||
#include "files_appearance.h"
|
||||
#include "files_help.h"
|
||||
#include "files_mcp.h"
|
||||
#include "files_menu_paint.h"
|
||||
#include "files_dropdown_paint.h"
|
||||
#include "files_scrollbar.h"
|
||||
@@ -3940,6 +3942,8 @@ bool gitChangesAvailable(const Panel &panel);
|
||||
void openGitChanges(HWND owner,const Panel &panel);
|
||||
void showEnvironmentPanel(HWND owner);
|
||||
void showFilesHelp(HWND owner,ks::files::FilesHelpTopic topic);
|
||||
void showFilesLog(HWND owner);
|
||||
void showFilesMcp(HWND owner);
|
||||
void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending=nullptr);
|
||||
void showCommandHistory(HWND owner);
|
||||
|
||||
@@ -3997,6 +4001,8 @@ void selectDrive()
|
||||
else if(menuIndex==2 && row==20) editFilesKeySchemes(owner,FilesKey::Refresh);
|
||||
else if(menuIndex==2 && row==21) editFilesAppearance(owner,terminalVisible?AppearanceArea::terminal:AppearanceArea::panels);
|
||||
else if(menuIndex==2 && row==22) showFilesHelp(owner,terminalVisible?ks::files::FilesHelpTopic::terminal:ks::files::FilesHelpTopic::panels);
|
||||
else if(menuIndex==2 && row==23) showFilesLog(owner);
|
||||
else if(menuIndex==2 && row==24) showFilesMcp(owner);
|
||||
else if(menuIndex==1 && row==4) createArchive(owner,panels[active]);
|
||||
else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]);
|
||||
else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]);
|
||||
@@ -8289,6 +8295,7 @@ struct OptionsWriteLock
|
||||
#include "files_panel_columns_dialog.inl"
|
||||
#include "files_space_analyzer.inl"
|
||||
#include "files_environment.inl"
|
||||
#include "files_mcp_ui.inl"
|
||||
|
||||
void openMenu(HWND window, int index)
|
||||
{
|
||||
@@ -8346,7 +8353,8 @@ void openMenu(HWND window, int index)
|
||||
filesKeyMenuLabel(FilesKey::FullPath),L"Space Analyzer",filesKeyMenuLabel(FilesKey::HexView),
|
||||
L"Viewer bookmarks…",L"Processes…",L"Git Changes…",L"Environment Variables…",filesKeyMenuLabel(FilesKey::Swap),
|
||||
filesKeyMenuLabel(FilesKey::History),L"Keyboard shortcuts…",
|
||||
terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1"};
|
||||
terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1",L"Files log…",
|
||||
filesMcp.port()?L"Files MCP (running)…":L"Files MCP…"};
|
||||
}
|
||||
const auto &panel=panels[active];
|
||||
const bool remoteResults=remoteSearchResults(panel);
|
||||
@@ -8393,7 +8401,7 @@ void openMenu(HWND window, int index)
|
||||
}
|
||||
if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10);
|
||||
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
|
||||
commandActions.insert(commandActions.end(),{-1,19,20,21,22});
|
||||
commandActions.insert(commandActions.end(),{-1,19,20,21,23,24,22});
|
||||
}
|
||||
else
|
||||
for(size_t i=0;i<rows.size();++i) commandActions.push_back(static_cast<int>(i));
|
||||
@@ -8625,6 +8633,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
switch (message)
|
||||
{
|
||||
case ks::files::filesMcpQueryMessage:
|
||||
filesMcp.answer(readFilesMcpTool);
|
||||
return 0;
|
||||
case WM_SETFOCUS:
|
||||
restoreCommandFocus();
|
||||
return 0;
|
||||
@@ -9433,6 +9444,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
DestroyWindow(window);
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
filesMcp.stop();
|
||||
pendingPanelDrop.reset();
|
||||
closeGitChanges(window,false);
|
||||
for(auto &panel:panels)
|
||||
@@ -9461,6 +9473,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
return DefWindowProcW(window, message, wp, lp);
|
||||
}
|
||||
|
||||
#include "files_log_view.inl"
|
||||
#include "files_help.inl"
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
#include "lan_network.h"
|
||||
#include "files_mcp.h"
|
||||
#include "lan_pairing.h"
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using Json=FilesMcpServer::Json;
|
||||
using Clock=std::chrono::steady_clock;
|
||||
using namespace std::chrono_literals;
|
||||
constexpr size_t maxHeaders=8192,maxRequest=16*1024,maxResponse=512*1024;
|
||||
constexpr std::string_view latestProtocol="2025-11-25";
|
||||
|
||||
bool supportedProtocol(std::string_view version)
|
||||
{
|
||||
return version==latestProtocol || version=="2025-06-18" || version=="2025-03-26";
|
||||
}
|
||||
|
||||
bool readySocket(SOCKET socket,bool write,std::stop_token stop,Clock::time_point deadline)
|
||||
{
|
||||
while(!stop.stop_requested() && Clock::now()<deadline)
|
||||
{
|
||||
fd_set ready;
|
||||
FD_ZERO(&ready);
|
||||
FD_SET(socket,&ready);
|
||||
timeval wait{0,50000};
|
||||
const auto result=select(0,write?nullptr:&ready,write?&ready:nullptr,nullptr,&wait);
|
||||
if(result) return result>0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool appendSocket(SOCKET socket,std::string &data,std::stop_token stop,Clock::time_point deadline)
|
||||
{
|
||||
char buffer[4096];
|
||||
if(!readySocket(socket,false,stop,deadline)) return false;
|
||||
const auto count=recv(socket,buffer,sizeof(buffer),0);
|
||||
if(count<=0) return false;
|
||||
data.append(buffer,count);
|
||||
return true;
|
||||
}
|
||||
|
||||
void sendSocket(SOCKET socket,std::string_view bytes,std::stop_token stop)
|
||||
{
|
||||
const auto deadline=Clock::now()+2s;
|
||||
while(!bytes.empty() && readySocket(socket,true,stop,deadline))
|
||||
{
|
||||
const auto count=send(socket,bytes.data(),static_cast<int>(bytes.size()),0);
|
||||
if(count<=0) return;
|
||||
bytes.remove_prefix(count);
|
||||
}
|
||||
}
|
||||
|
||||
std::string lowerAscii(std::string_view text)
|
||||
{
|
||||
std::string result(text);
|
||||
for(auto &ch:result)
|
||||
if(ch>='A' && ch<='Z') ch=static_cast<char>(ch-'A'+'a');
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string_view trimHeader(std::string_view text)
|
||||
{
|
||||
const auto first=text.find_first_not_of(" \t");
|
||||
return first==text.npos?std::string_view{}:text.substr(first,text.find_last_not_of(" \t")-first+1);
|
||||
}
|
||||
|
||||
struct HttpRequest
|
||||
{
|
||||
std::string_view method,path;
|
||||
std::map<std::string,std::string_view,std::less<>> headers;
|
||||
|
||||
std::string_view header(std::string_view field) const
|
||||
{
|
||||
const auto found=headers.find(field);
|
||||
return found==headers.end()?std::string_view{}:found->second;
|
||||
}
|
||||
};
|
||||
|
||||
std::optional<HttpRequest> parseHeaders(std::string_view data)
|
||||
{
|
||||
HttpRequest request;
|
||||
auto end=data.find("\r\n");
|
||||
const auto line=data.substr(0,end);
|
||||
const auto first=line.find(' '),second=first==line.npos?line.npos:line.find(' ',first+1);
|
||||
if(end==data.npos || !first || second==line.npos || line.substr(second+1)!="HTTP/1.1") return {};
|
||||
request.method=line.substr(0,first);
|
||||
request.path=line.substr(first+1,second-first-1);
|
||||
data.remove_prefix(end+2);
|
||||
while(!data.empty())
|
||||
{
|
||||
end=data.find("\r\n");
|
||||
const auto header=data.substr(0,end);
|
||||
const auto colon=header.find(':');
|
||||
if(!colon || colon==header.npos) return {};
|
||||
const auto name=lowerAscii(header.substr(0,colon));
|
||||
const auto value=trimHeader(header.substr(colon+1));
|
||||
if(!std::ranges::all_of(name,[](char ch)
|
||||
{return (ch>='a' && ch<='z') || (ch>='0' && ch<='9') || ch=='-' || ch=='_';}) ||
|
||||
!std::ranges::all_of(value,[](unsigned char ch){return ch=='\t' || (ch>=32 && ch<127);}) ||
|
||||
!request.headers.emplace(name,value).second)
|
||||
return {};
|
||||
if(end==data.npos) break;
|
||||
data.remove_prefix(end+2);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
bool hasSessionToken(std::string_view authorization,std::string_view token)
|
||||
{
|
||||
if(authorization.size()!=token.size()+7 || lowerAscii(authorization.substr(0,7))!="bearer ") return false;
|
||||
unsigned difference=0;
|
||||
for(size_t i=0;i<token.size();++i)
|
||||
difference|=static_cast<unsigned char>(authorization[i+7]^token[i]);
|
||||
return difference==0;
|
||||
}
|
||||
|
||||
struct HttpReply
|
||||
{
|
||||
const char *status;
|
||||
std::string body;
|
||||
const char *headers="";
|
||||
};
|
||||
|
||||
HttpReply jsonReply(const char *status,Json body)
|
||||
{
|
||||
return {status,body.dump(-1,' ',false,Json::error_handler_t::replace)};
|
||||
}
|
||||
|
||||
HttpReply rpcError(const char *status,const Json &id,int code,const char *message)
|
||||
{
|
||||
return jsonReply(status,{{"jsonrpc","2.0"},{"id",id},{"error",{{"code",code},{"message",message}}}});
|
||||
}
|
||||
|
||||
const Json &mcpTools()
|
||||
{
|
||||
static const auto tools=Json::parse(R"({"tools":[
|
||||
{"name":"get_panels","description":"Read the two Files panes and their current local listings, selections and Find state.",
|
||||
"inputSchema":{"type":"object","properties":{"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"additionalProperties":false},
|
||||
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}},
|
||||
{"name":"search_files","description":"Search the current local listing or existing Find results by name or relative path.",
|
||||
"inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"query":{"type":"string","minLength":1,"maxLength":128},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"required":["query"],"additionalProperties":false},
|
||||
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}},
|
||||
{"name":"get_file_metadata","description":"Read cached metadata for a relative path already listed in a current local pane.",
|
||||
"inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"path":{"type":"string","minLength":1,"maxLength":2048}},"required":["path"],"additionalProperties":false},
|
||||
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}}
|
||||
]})");
|
||||
return tools;
|
||||
}
|
||||
|
||||
Json toolResult(const Json &data,bool error=false)
|
||||
{
|
||||
const auto text=error?data.get<std::string>():data.dump(-1,' ',false,Json::error_handler_t::replace);
|
||||
Json result{{"content",Json::array({{{"type","text"},{"text",text}}})},{"isError",error}};
|
||||
if(!error) result["structuredContent"]=data;
|
||||
return result;
|
||||
}
|
||||
|
||||
template<class Read>
|
||||
HttpReply handleRpc(std::string_view body,const Read &read)
|
||||
{
|
||||
Json message,id;
|
||||
try
|
||||
{
|
||||
message=Json::parse(body,[](int depth,Json::parse_event_t,Json &)
|
||||
{
|
||||
if(depth>24) throw std::runtime_error("Request nesting limit");
|
||||
return true;
|
||||
});
|
||||
}
|
||||
catch(const std::exception &) {return rpcError("400 Bad Request",nullptr,-32700,"Invalid JSON");}
|
||||
if(!message.is_object() || message.value("jsonrpc",Json())!="2.0" ||
|
||||
!message.contains("method") || !message["method"].is_string())
|
||||
return rpcError("400 Bad Request",nullptr,-32600,"Invalid request");
|
||||
const auto &method=message["method"].get_ref<const std::string &>();
|
||||
if(!message.contains("id"))
|
||||
{
|
||||
if(method=="notifications/initialized" || method=="notifications/cancelled") return {"202 Accepted",{}};
|
||||
return rpcError("400 Bad Request",nullptr,-32600,"Unsupported notification");
|
||||
}
|
||||
id=message["id"];
|
||||
if(!id.is_number_integer() && (!id.is_string() || id.get_ref<const std::string &>().size()>256))
|
||||
return rpcError("400 Bad Request",nullptr,-32600,"Invalid request id");
|
||||
auto params=message.value("params",Json::object());
|
||||
if(!params.is_object()) return rpcError("200 OK",id,-32602,"Invalid parameters");
|
||||
Json result;
|
||||
if(method=="initialize")
|
||||
{
|
||||
if(!params.contains("protocolVersion") || !params["protocolVersion"].is_string())
|
||||
return rpcError("200 OK",id,-32602,"Protocol version is required");
|
||||
const auto version=params["protocolVersion"].get<std::string>();
|
||||
result={{"protocolVersion",supportedProtocol(version)?version:std::string(latestProtocol)},
|
||||
{"capabilities",{{"tools",Json::object()}}},
|
||||
{"serverInfo",{{"name","kswitcher-files"},{"version","1.0.0"}}},
|
||||
{"instructions","Inspect the current local listings and cached metadata. Search uses the Files panels' current results."}};
|
||||
}
|
||||
else if(method=="ping") result=Json::object();
|
||||
else if(method=="tools/list") result=mcpTools();
|
||||
else if(method=="tools/call")
|
||||
{
|
||||
if(!params.contains("name") || !params["name"].is_string())
|
||||
return rpcError("200 OK",id,-32602,"Tool name is required");
|
||||
const auto &name=params["name"].get_ref<const std::string &>();
|
||||
const auto args=params.value("arguments",Json::object());
|
||||
if(!args.is_object() || !std::ranges::any_of(mcpTools()["tools"],[&](const auto &tool)
|
||||
{return tool["name"]==name;}))
|
||||
return rpcError("200 OK",id,-32602,"Unknown tool or invalid arguments");
|
||||
auto data=read(name,args);
|
||||
const auto failed=data.contains("error");
|
||||
result=failed?toolResult(data.at("error"),true):toolResult(data);
|
||||
}
|
||||
else return rpcError("200 OK",id,-32601,"Method not found");
|
||||
auto answer=jsonReply("200 OK",{{"jsonrpc","2.0"},{"id",id},{"result",std::move(result)}});
|
||||
return answer.body.size()<=maxResponse?std::move(answer):rpcError("200 OK",id,-32603,"Response is too large");
|
||||
}
|
||||
|
||||
template<class Read>
|
||||
HttpReply handleHttp(SOCKET socket,unsigned port,std::string_view token,std::stop_token stop,const Read &read)
|
||||
{
|
||||
std::string bytes;
|
||||
const auto deadline=Clock::now()+2s;
|
||||
size_t end{};
|
||||
while((end=bytes.find("\r\n\r\n"))==bytes.npos)
|
||||
{
|
||||
if(bytes.size()>=maxHeaders) return {"431 Request Header Fields Too Large",{}};
|
||||
if(!appendSocket(socket,bytes,stop,deadline)) return {"408 Request Timeout",{}};
|
||||
}
|
||||
if(end+4>maxHeaders) return {"431 Request Header Fields Too Large",{}};
|
||||
// Header fields refer into bytes. Parse before appending any further data.
|
||||
const auto request=parseHeaders(std::string_view(bytes).substr(0,end+2));
|
||||
if(!request) return {"400 Bad Request",{}};
|
||||
if(request->headers.contains("origin") || request->header("host")!="127.0.0.1:"+std::to_string(port))
|
||||
return {"403 Forbidden",{}};
|
||||
if(!hasSessionToken(request->header("authorization"),token))
|
||||
return {"401 Unauthorized",{},"WWW-Authenticate: Bearer\r\n"};
|
||||
if(request->path!="/mcp") return {"404 Not Found",{}};
|
||||
if(request->method!="POST") return {"405 Method Not Allowed",{},"Allow: POST\r\n"};
|
||||
if(request->headers.contains("transfer-encoding") ||
|
||||
(request->headers.contains("mcp-protocol-version") && !supportedProtocol(request->header("mcp-protocol-version"))))
|
||||
return {"400 Bad Request",{}};
|
||||
const auto type=request->header("content-type");
|
||||
if(lowerAscii(trimHeader(type.substr(0,type.find(';'))))!="application/json") return {"415 Unsupported Media Type",{}};
|
||||
const auto length=request->header("content-length");
|
||||
size_t count{};
|
||||
if(length.empty()) return {"411 Length Required",{}};
|
||||
const auto converted=std::from_chars(length.data(),length.data()+length.size(),count);
|
||||
if(converted.ec!=std::errc{} || converted.ptr!=length.data()+length.size()) return {"400 Bad Request",{}};
|
||||
if(count>maxRequest) return {"413 Content Too Large",{}};
|
||||
const auto start=end+4;
|
||||
while(bytes.size()-start<count)
|
||||
if(!appendSocket(socket,bytes,stop,deadline)) return {"408 Request Timeout",{}};
|
||||
if(bytes.size()-start!=count) return {"400 Bad Request",{}};
|
||||
return handleRpc(std::string_view(bytes).substr(start,count),read);
|
||||
}
|
||||
}
|
||||
|
||||
struct FilesMcpServer::Session
|
||||
{
|
||||
struct Query
|
||||
{
|
||||
std::string name;
|
||||
Json arguments;
|
||||
std::promise<Json> result;
|
||||
std::atomic_bool cancelled{};
|
||||
};
|
||||
|
||||
lan::Network network;
|
||||
lan::WinSocket listener;
|
||||
unsigned port{};
|
||||
std::string token=lan::randomHex(32);
|
||||
HWND owner{};
|
||||
std::mutex gate;
|
||||
std::shared_ptr<Query> pending;
|
||||
std::jthread worker;
|
||||
|
||||
explicit Session(HWND window):owner(window)
|
||||
{
|
||||
listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
|
||||
BOOL exclusive=TRUE;
|
||||
u_long nonblocking=1;
|
||||
sockaddr_in address{};
|
||||
address.sin_family=AF_INET;
|
||||
address.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
|
||||
int size=sizeof(address);
|
||||
if(listener.value==INVALID_SOCKET || setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,
|
||||
reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
|
||||
ioctlsocket(listener.value,FIONBIO,&nonblocking) ||
|
||||
bind(listener.value,reinterpret_cast<const sockaddr *>(&address),sizeof(address)) ||
|
||||
listen(listener.value,4) || getsockname(listener.value,reinterpret_cast<sockaddr *>(&address),&size))
|
||||
lan::socketError();
|
||||
port=ntohs(address.sin_port);
|
||||
worker=std::jthread([this](std::stop_token stop){run(stop);});
|
||||
}
|
||||
|
||||
~Session()
|
||||
{
|
||||
worker.request_stop();
|
||||
if(worker.joinable()) worker.join();
|
||||
SecureZeroMemory(token.data(),token.size());
|
||||
}
|
||||
|
||||
Json requestUi(std::string_view name,const Json &arguments,std::stop_token stop)
|
||||
{
|
||||
auto query=std::make_shared<Query>();
|
||||
query->name=name;
|
||||
query->arguments=arguments;
|
||||
auto result=query->result.get_future();
|
||||
{
|
||||
std::lock_guard lock(gate);
|
||||
pending=query;
|
||||
}
|
||||
const auto deadline=Clock::now()+2s;
|
||||
if(PostMessageW(owner,filesMcpQueryMessage,0,0))
|
||||
while(!stop.stop_requested() && Clock::now()<deadline)
|
||||
if(result.wait_for(25ms)==std::future_status::ready) return result.get();
|
||||
query->cancelled=true;
|
||||
std::lock_guard lock(gate);
|
||||
if(pending==query) pending.reset();
|
||||
return {{"error","Files did not answer in time."}};
|
||||
}
|
||||
|
||||
void run(std::stop_token stop)
|
||||
{
|
||||
while(!stop.stop_requested())
|
||||
{
|
||||
if(!readySocket(listener.value,false,stop,Clock::now()+100ms)) continue;
|
||||
sockaddr_in peer{};
|
||||
int peerSize=sizeof(peer);
|
||||
lan::WinSocket client;
|
||||
client.value=accept(listener.value,reinterpret_cast<sockaddr *>(&peer),&peerSize);
|
||||
u_long nonblocking=1;
|
||||
if(client.value==INVALID_SOCKET || peer.sin_family!=AF_INET ||
|
||||
peer.sin_addr.s_addr!=htonl(INADDR_LOOPBACK) || ioctlsocket(client.value,FIONBIO,&nonblocking))
|
||||
continue;
|
||||
HttpReply reply{"500 Internal Server Error",{}};
|
||||
try
|
||||
{
|
||||
reply=handleHttp(client.value,port,token,stop,[&](std::string_view name,const Json ¶ms)
|
||||
{return requestUi(name,params,stop);});
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
const auto header=std::string("HTTP/1.1 ")+reply.status+"\r\nConnection: close\r\n"
|
||||
"Cache-Control: no-store\r\nContent-Type: application/json\r\n"+reply.headers+
|
||||
"Content-Length: "+std::to_string(reply.body.size())+"\r\n\r\n";
|
||||
sendSocket(client.value,header+reply.body,stop);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
FilesMcpServer::FilesMcpServer()=default;
|
||||
FilesMcpServer::~FilesMcpServer()=default;
|
||||
|
||||
void FilesMcpServer::start(HWND owner)
|
||||
{
|
||||
if(!session) session=std::make_unique<Session>(owner);
|
||||
}
|
||||
|
||||
void FilesMcpServer::stop() {session.reset();}
|
||||
unsigned FilesMcpServer::port() const {return session?session->port:0;}
|
||||
std::string_view FilesMcpServer::token() const {return session?std::string_view(session->token):std::string_view{};}
|
||||
|
||||
void FilesMcpServer::answer(const ReadTool &read)
|
||||
{
|
||||
if(!session) return;
|
||||
std::shared_ptr<Session::Query> query;
|
||||
{
|
||||
std::lock_guard lock(session->gate);
|
||||
query=std::exchange(session->pending,{});
|
||||
}
|
||||
if(!query || query->cancelled) return;
|
||||
try {query->result.set_value(read(query->name,query->arguments));}
|
||||
catch(const std::exception &) {query->result.set_value({{"error","Files could not read the requested state."}});}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include "../vendor/json.hpp"
|
||||
#include <windows.h>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline constexpr UINT filesMcpQueryMessage=WM_APP+274;
|
||||
|
||||
class FilesMcpServer
|
||||
{
|
||||
public:
|
||||
using Json=nlohmann::json;
|
||||
using ReadTool=std::function<Json(std::string_view,const Json &)>;
|
||||
FilesMcpServer();
|
||||
~FilesMcpServer();
|
||||
FilesMcpServer(const FilesMcpServer &)=delete;
|
||||
FilesMcpServer &operator=(const FilesMcpServer &)=delete;
|
||||
|
||||
void start(HWND owner);
|
||||
void stop();
|
||||
unsigned port() const;
|
||||
std::string_view token() const;
|
||||
void answer(const ReadTool &read);
|
||||
|
||||
private:
|
||||
struct Session;
|
||||
std::unique_ptr<Session> session;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
ks::files::FilesMcpServer filesMcp;
|
||||
constexpr int filesMcpStatus=690,filesMcpEndpoint=691,filesMcpToken=692,filesMcpToggle=693,
|
||||
filesMcpShowToken=694,filesMcpCopyToken=695;
|
||||
constexpr size_t maxMcpRows=50,maxMcpSearchScan=10000;
|
||||
|
||||
std::string mcpSide(int side) {return side==0?"left":"right";}
|
||||
|
||||
bool mcpLocalPanel(const Panel &panel)
|
||||
{
|
||||
return !panel.peer && !panel.ftp && !panel.archive && ks::files::isLocalDocumentPath(panel.directory);
|
||||
}
|
||||
|
||||
std::optional<std::wstring> mcpRelativePath(const Panel &panel,size_t row)
|
||||
{
|
||||
if(row>=panel.rows.size() || row>=panel.sizes.size() || panel.sizes[row]==L"Up") return {};
|
||||
const auto relative=panel.rows[row].lexically_relative(panel.directory);
|
||||
if(relative.empty() || relative.has_root_path()) return {};
|
||||
for(const auto &part:relative)
|
||||
if(!ks::files::validWindowsFileName(part.native())) return {};
|
||||
const auto path=relative.generic_wstring();
|
||||
if(path.size()>2048) return {};
|
||||
return path;
|
||||
}
|
||||
|
||||
Json mcpFileItem(const Panel &panel,size_t row,const std::wstring &relative)
|
||||
{
|
||||
Json item{{"path",ks::utf8(relative)},{"marked",row<panel.marked.size() && panel.marked[row]}};
|
||||
const auto found=panel.metadata.find(panel.rows[row]);
|
||||
if(found==panel.metadata.end())
|
||||
{
|
||||
item["metadataAvailable"]=false;
|
||||
return item;
|
||||
}
|
||||
const auto &info=found->second;
|
||||
const bool directory=(info.attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
|
||||
item["metadataAvailable"]=true;
|
||||
item["kind"]=directory?"directory":"file";
|
||||
item["attributes"]=info.attributes;
|
||||
item["reparsePoint"]=(info.attributes&FILE_ATTRIBUTE_REPARSE_POINT)!=0;
|
||||
if(!directory) item["sizeBytes"]=info.size;
|
||||
if(info.modified)
|
||||
{
|
||||
const FILETIME time{static_cast<DWORD>(info.modified),static_cast<DWORD>(info.modified>>32)};
|
||||
SYSTEMTIME utc{};
|
||||
if(FileTimeToSystemTime(&time,&utc))
|
||||
{
|
||||
wchar_t date[32]{};
|
||||
swprintf_s(date,L"%04u-%02u-%02uT%02u:%02u:%02uZ",utc.wYear,utc.wMonth,utc.wDay,
|
||||
utc.wHour,utc.wMinute,utc.wSecond);
|
||||
item["modifiedUtc"]=ks::utf8(date);
|
||||
}
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
std::optional<size_t> mcpPageValue(const Json &args,const char *key,size_t fallback,size_t maximum)
|
||||
{
|
||||
if(!args.contains(key)) return fallback;
|
||||
const auto &value=args.at(key);
|
||||
if(!value.is_number_unsigned() || value>maximum) return {};
|
||||
return value.get<size_t>();
|
||||
}
|
||||
|
||||
bool mcpArgumentNames(const Json &arguments,std::initializer_list<std::string_view> accepted)
|
||||
{
|
||||
for(auto field=arguments.begin();field!=arguments.end();++field)
|
||||
if(std::ranges::find(accepted,std::string_view(field.key()))==accepted.end()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<int> mcpArgumentSide(const Json &arguments)
|
||||
{
|
||||
if(!arguments.contains("side") || arguments.at("side")=="active") return active;
|
||||
if(arguments.at("side")=="left") return 0;
|
||||
if(arguments.at("side")=="right") return 1;
|
||||
return {};
|
||||
}
|
||||
|
||||
Json mcpPanelPage(const Panel &panel,size_t offset,size_t limit,std::wstring_view query={})
|
||||
{
|
||||
Json entries=Json::array();
|
||||
size_t row=std::min(offset,panel.rows.size());
|
||||
const auto scannedEnd=row+std::min(maxMcpSearchScan,panel.rows.size()-row);
|
||||
for(;row<scannedEnd && entries.size()<limit;++row)
|
||||
if(const auto relative=mcpRelativePath(panel,row))
|
||||
if(query.empty() || ks::lower(*relative).find(query)!=std::wstring::npos)
|
||||
entries.push_back(mcpFileItem(panel,row,*relative));
|
||||
return {{"entries",std::move(entries)},{"nextOffset",row<panel.rows.size()?Json(row):Json(nullptr)}};
|
||||
}
|
||||
|
||||
Json mcpPanelState(int side,size_t offset,size_t limit)
|
||||
{
|
||||
const auto &panel=panels[side];
|
||||
Json result{{"side",mcpSide(side)},{"available",mcpLocalPanel(panel)},
|
||||
{"visible",IsWindowVisible(panel.list)!=FALSE}};
|
||||
if(!result.at("available").get<bool>()) return result;
|
||||
result["directory"]=ks::utf8(panel.directory.native());
|
||||
result["mode"]=ks::utf8(panelModeNames[static_cast<size_t>(panel.mode)]);
|
||||
result["scanning"]=panel.scanRequest.has_value();
|
||||
const auto selected=currentPanelRow(panel);
|
||||
if(selected!=LB_ERR)
|
||||
if(const auto path=mcpRelativePath(panel,static_cast<size_t>(selected))) result["cursor"]=ks::utf8(*path);
|
||||
const auto *pending=panel.scanRequest && panel.scanRequest->find?&*panel.scanRequest->find:nullptr;
|
||||
if(pending || panel.findOrigin)
|
||||
{
|
||||
const auto &find=pending?*pending:panel.findOrigin->options;
|
||||
result["find"]={{"mask",ks::utf8(find.mask)},{"includeHidden",find.includeHidden},
|
||||
{"running",pending!=nullptr},{"error",pending?0:panel.findOrigin->error}};
|
||||
}
|
||||
result.update(mcpPanelPage(panel,offset,limit));
|
||||
return result;
|
||||
}
|
||||
|
||||
Json readFilesMcpTool(std::string_view tool,const Json &arguments)
|
||||
{
|
||||
const auto offset=mcpPageValue(arguments,"offset",0,2147483647);
|
||||
const auto limit=mcpPageValue(arguments,"limit",25,maxMcpRows);
|
||||
if(!offset || !limit || !*limit) return {{"error","Invalid page offset or limit."}};
|
||||
if(tool=="get_panels")
|
||||
{
|
||||
if(!mcpArgumentNames(arguments,{"offset","limit"})) return {{"error","Unknown pane argument."}};
|
||||
return {{"active",mcpSide(active)},{"panels",Json::array(
|
||||
{mcpPanelState(0,*offset,*limit),mcpPanelState(1,*offset,*limit)})}};
|
||||
}
|
||||
const auto side=mcpArgumentSide(arguments);
|
||||
if(!side) return {{"error","Choose an active, left or right pane."}};
|
||||
const auto &panel=panels[*side];
|
||||
if(!mcpLocalPanel(panel)) return {{"error","This pane is not a local filesystem listing."}};
|
||||
if(tool=="search_files")
|
||||
{
|
||||
if(!mcpArgumentNames(arguments,{"side","query","offset","limit"}) || !arguments.contains("query") ||
|
||||
!arguments["query"].is_string() || arguments["query"].get_ref<const std::string &>().size()>512)
|
||||
return {{"error","Enter a search query of 1 to 128 characters."}};
|
||||
auto query=ks::wide(arguments["query"].get_ref<const std::string &>());
|
||||
if(query.empty() || query.size()>128 || query.find_first_of(L"\r\n")!=query.npos ||
|
||||
query.find(L'\0')!=query.npos) return {{"error","Enter a search query of 1 to 128 characters."}};
|
||||
auto result=mcpPanelPage(panel,*offset,*limit,ks::lower(std::move(query)));
|
||||
result["side"]=mcpSide(*side);
|
||||
result["scope"]=panel.findOrigin?"find-results":"current-listing";
|
||||
return result;
|
||||
}
|
||||
if(tool!="get_file_metadata" || !mcpArgumentNames(arguments,{"side","path"}) ||
|
||||
!arguments.contains("path") || !arguments["path"].is_string() ||
|
||||
arguments["path"].get_ref<const std::string &>().size()>8192)
|
||||
return {{"error","Choose a relative path from the current pane."}};
|
||||
auto relative=fs::path(ks::wide(arguments["path"].get_ref<const std::string &>()));
|
||||
if(relative.empty() || relative.has_root_path() || relative.native().size()>2048)
|
||||
return {{"error","Choose a relative path from the current pane."}};
|
||||
for(const auto &part:relative)
|
||||
if(!ks::files::validWindowsFileName(part.native()))
|
||||
return {{"error","Choose a relative path from the current pane."}};
|
||||
relative.make_preferred();
|
||||
const auto path=panel.directory/relative;
|
||||
const auto found=std::ranges::find(panel.rows,path);
|
||||
if(found==panel.rows.end()) return {{"error","The file is not in the current pane."}};
|
||||
const auto row=static_cast<size_t>(found-panel.rows.begin());
|
||||
const auto listed=mcpRelativePath(panel,row);
|
||||
if(!listed) return {{"error","The file is not in the current pane."}};
|
||||
return mcpFileItem(panel,row,*listed);
|
||||
}
|
||||
|
||||
void updateFilesMcpDialog(HWND dialog)
|
||||
{
|
||||
const auto port=filesMcp.port();
|
||||
const auto endpoint=port?L"http://127.0.0.1:"+std::to_wstring(port)+L"/mcp":L"";
|
||||
SetDlgItemTextW(dialog,filesMcpEndpoint,endpoint.c_str());
|
||||
SetDlgItemTextW(dialog,filesMcpToggle,port?L"&Stop":L"&Start");
|
||||
EnableWindow(GetDlgItem(dialog,filesMcpShowToken),port!=0);
|
||||
EnableWindow(GetDlgItem(dialog,filesMcpCopyToken),port!=0);
|
||||
if(!port) CheckDlgButton(dialog,filesMcpShowToken,BST_UNCHECKED);
|
||||
const auto token=port && IsDlgButtonChecked(dialog,filesMcpShowToken)==BST_CHECKED?
|
||||
ks::wide(std::string(filesMcp.token())):L"";
|
||||
SetDlgItemTextW(dialog,filesMcpToken,token.c_str());
|
||||
SetDlgItemTextW(dialog,filesMcpStatus,port?
|
||||
L"Running on this computer. Stop to revoke the session token.":L"Stopped.");
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK filesMcpDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
updateFilesMcpDialog(dialog);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
|
||||
{
|
||||
SetDlgItemTextW(dialog,filesMcpToken,L"");
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message!=WM_COMMAND) return FALSE;
|
||||
switch(LOWORD(wp))
|
||||
{
|
||||
case filesMcpToggle:
|
||||
try
|
||||
{
|
||||
if(filesMcp.port()) filesMcp.stop();
|
||||
else filesMcp.start(reinterpret_cast<HWND>(GetWindowLongPtrW(dialog,DWLP_USER)));
|
||||
updateFilesMcpDialog(dialog);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
SetDlgItemTextW(dialog,filesMcpStatus,L"Could not start the local MCP listener.");
|
||||
}
|
||||
return TRUE;
|
||||
case filesMcpShowToken:
|
||||
updateFilesMcpDialog(dialog);
|
||||
return TRUE;
|
||||
case filesMcpCopyToken:
|
||||
if(filesMcp.port() && copyFilesText(dialog,ks::wide(std::string(filesMcp.token())),L"Could not copy the token."))
|
||||
SetDlgItemTextW(dialog,filesMcpStatus,L"Session token copied.");
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
void showFilesMcp(HWND owner)
|
||||
{
|
||||
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(620),owner,filesMcpDialog,
|
||||
reinterpret_cast<LPARAM>(owner),false,false);
|
||||
dialog.runModal();
|
||||
}
|
||||
@@ -899,6 +899,41 @@ void setLoggingEnabled(bool enabled)
|
||||
if (!enabled)
|
||||
diagnosticBuffer.clear();
|
||||
}
|
||||
std::optional<Bytes> readActiveLogTail(bool previous,size_t byteLimit)
|
||||
{
|
||||
std::lock_guard lock(logGate);
|
||||
auto path=logDirectory()/logFilename;
|
||||
if(previous) path+=L".1";
|
||||
const auto raw=CreateFileW(path.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(raw==INVALID_HANDLE_VALUE)
|
||||
{
|
||||
const auto error=GetLastError();
|
||||
if(error==ERROR_FILE_NOT_FOUND || error==ERROR_PATH_NOT_FOUND) return {};
|
||||
throw std::runtime_error("Cannot open the diagnostic log");
|
||||
}
|
||||
const std::unique_ptr<void,decltype(&CloseHandle)> file(raw,CloseHandle);
|
||||
LARGE_INTEGER size{};
|
||||
if(!GetFileSizeEx(raw,&size) || size.QuadPart<0) throw std::runtime_error("Cannot measure the diagnostic log");
|
||||
const auto limit=std::min<uint64_t>(byteLimit,2*1024*1024);
|
||||
if(!limit || !size.QuadPart) return Bytes{};
|
||||
const auto offset=std::max<int64_t>(0,size.QuadPart-static_cast<int64_t>(limit));
|
||||
LARGE_INTEGER position{};
|
||||
position.QuadPart=offset?offset-1:0;
|
||||
if(!SetFilePointerEx(raw,position,nullptr,FILE_BEGIN)) throw std::runtime_error("Cannot seek in the diagnostic log");
|
||||
Bytes contents(static_cast<size_t>(size.QuadPart-position.QuadPart));
|
||||
DWORD read{};
|
||||
if(!ReadFile(raw,contents.data(),static_cast<DWORD>(contents.size()),&read,nullptr))
|
||||
throw std::runtime_error("Cannot read the diagnostic log");
|
||||
contents.resize(read);
|
||||
if(offset && !contents.empty())
|
||||
{
|
||||
const auto newline=std::find(contents.begin(),contents.end(),'\n');
|
||||
contents.erase(contents.begin(),newline==contents.end()?newline:std::next(newline));
|
||||
}
|
||||
return contents;
|
||||
}
|
||||
|
||||
std::wstring readDiagnosticLog(bool previous)
|
||||
{
|
||||
std::lock_guard lock(logGate);
|
||||
|
||||
@@ -107,5 +107,6 @@ void expireDiagnostics(ULONGLONG now);
|
||||
void diagnosticEvent(const std::wstring &message, bool problem = false);
|
||||
void diagnosticOperation(const std::string &json);
|
||||
std::wstring readDiagnosticLog(bool previous);
|
||||
std::optional<Bytes> readActiveLogTail(bool previous,size_t byteLimit);
|
||||
void clearDiagnosticLog(bool previous);
|
||||
} // namespace ks
|
||||
@@ -0,0 +1,144 @@
|
||||
#include "lan_network.h"
|
||||
#include "files_mcp.h"
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace
|
||||
{
|
||||
using Server=ks::files::FilesMcpServer;
|
||||
using Json=Server::Json;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
void expect(bool condition,const char *message)
|
||||
{
|
||||
if(!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
bool connectLoopback(SOCKET socket,unsigned port)
|
||||
{
|
||||
sockaddr_in address{};
|
||||
address.sin_family=AF_INET;
|
||||
address.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
|
||||
address.sin_port=htons(static_cast<u_short>(port));
|
||||
return connect(socket,reinterpret_cast<const sockaddr*>(&address),sizeof(address))==0;
|
||||
}
|
||||
|
||||
std::string post(unsigned port,const std::string &token,const Json &message,
|
||||
std::string_view extra={},std::string_view host={})
|
||||
{
|
||||
ks::lan::WinSocket client;
|
||||
client.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
|
||||
const DWORD timeout=4000;
|
||||
expect(client.value!=INVALID_SOCKET &&
|
||||
!setsockopt(client.value,SOL_SOCKET,SO_RCVTIMEO,reinterpret_cast<const char*>(&timeout),sizeof(timeout)) &&
|
||||
connectLoopback(client.value,port),"Could not connect to fixture listener");
|
||||
const auto body=message.dump();
|
||||
const auto authority=host.empty()?"127.0.0.1:"+std::to_string(port):std::string(host);
|
||||
const auto bytes="POST /mcp HTTP/1.1\r\nHost: "+authority+"\r\nContent-Type: application/json\r\n"
|
||||
"Accept: application/json, text/event-stream\r\n"+
|
||||
(token.empty()?std::string{}:"Authorization: Bearer "+token+"\r\n")+
|
||||
std::string(extra)+"Content-Length: "+std::to_string(body.size())+"\r\n\r\n"+body;
|
||||
expect(send(client.value,bytes.data(),static_cast<int>(bytes.size()),0)==static_cast<int>(bytes.size()),
|
||||
"Could not send fixture request");
|
||||
std::string response;
|
||||
char buffer[4096];
|
||||
for(;;)
|
||||
{
|
||||
const int count=recv(client.value,buffer,sizeof(buffer),0);
|
||||
expect(count>=0,"Fixture request timed out");
|
||||
if(!count) break;
|
||||
response.append(buffer,count);
|
||||
expect(response.size()<1024*1024,"Oversized fixture response");
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
Json content(const std::string &response)
|
||||
{
|
||||
const auto end=response.find("\r\n\r\n");
|
||||
expect(end!=response.npos,"No HTTP headers");
|
||||
return Json::parse(response.substr(end+4));
|
||||
}
|
||||
|
||||
Json request(std::string_view method,Json params=Json::object())
|
||||
{
|
||||
return {{"jsonrpc","2.0"},{"id",4},{"method",method},{"params",std::move(params)}};
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try
|
||||
{
|
||||
ks::lan::Network network;
|
||||
const auto owner=CreateWindowExW(0,L"STATIC",L"Files MCP fixture",0,0,0,0,0,
|
||||
HWND_MESSAGE,nullptr,GetModuleHandleW(nullptr),nullptr);
|
||||
expect(owner!=nullptr,"Could not create fixture owner window");
|
||||
Server server;
|
||||
expect(!server.port() && server.token().empty(),"The listener is enabled by default");
|
||||
server.start(owner);
|
||||
const auto port=server.port();
|
||||
const auto token=std::string(server.token());
|
||||
expect(port && token.size()==64,"The session does not have a listener and token");
|
||||
const auto ping=request("ping");
|
||||
expect(post(port,{},ping).starts_with("HTTP/1.1 401"),"An unauthenticated request was accepted");
|
||||
expect(post(port,std::string(64,'0'),ping).starts_with("HTTP/1.1 401"),"A wrong token was accepted");
|
||||
expect(post(port,token,ping,"Origin: https://example.invalid\r\n").starts_with("HTTP/1.1 403"),
|
||||
"A browser origin was accepted");
|
||||
expect(post(port,token,ping,{},"other.invalid").starts_with("HTTP/1.1 403"),
|
||||
"An unexpected Host was accepted");
|
||||
expect(post(port,token,ping,"Content-Length: 1\r\n").starts_with("HTTP/1.1 400"),
|
||||
"An ambiguous message length was accepted");
|
||||
const auto initialized=content(post(port,token,request("initialize",{{"protocolVersion","2025-11-25"}})));
|
||||
expect(initialized.at("result").at("protocolVersion")=="2025-11-25","Wrong protocol version");
|
||||
const Json notification{{"jsonrpc","2.0"},{"method","notifications/initialized"}};
|
||||
expect(post(port,token,notification).starts_with("HTTP/1.1 202"),"Initialization notification did not succeed");
|
||||
const auto listed=content(post(port,token,request("tools/list")));
|
||||
const auto &tools=listed.at("result").at("tools");
|
||||
expect(tools.size()==3,"The listener advertised unexpected capabilities");
|
||||
for(const auto &tool:tools) expect(tool.at("annotations").at("readOnlyHint")==true,"A tool is not read-only");
|
||||
const auto unknown=content(post(port,token,request("tools/call",{{"name","write_file"}})));
|
||||
expect(unknown.at("error").at("code")==-32602,"An unlisted tool was accepted");
|
||||
|
||||
auto pending=std::async(std::launch::async,[&]
|
||||
{
|
||||
return content(post(port,token,request("tools/call",
|
||||
{{"name","get_panels"},{"arguments",{{"limit",3}}}})));
|
||||
});
|
||||
const auto deadline=std::chrono::steady_clock::now()+3s;
|
||||
while(pending.wait_for(1ms)!=std::future_status::ready && std::chrono::steady_clock::now()<deadline)
|
||||
{
|
||||
MSG message{};
|
||||
if(PeekMessageW(&message,owner,ks::files::filesMcpQueryMessage,ks::files::filesMcpQueryMessage,PM_REMOVE))
|
||||
server.answer([](std::string_view name,const Json &arguments)
|
||||
{
|
||||
if(name!="get_panels" || arguments.at("limit")!=3) return Json{{"error","Wrong query"}};
|
||||
return Json{{"active","left"}};
|
||||
});
|
||||
}
|
||||
expect(pending.get().at("result").at("structuredContent").at("active")=="left",
|
||||
"The server did not return the UI snapshot");
|
||||
|
||||
ks::lan::WinSocket idle;
|
||||
idle.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
|
||||
expect(idle.value!=INVALID_SOCKET && connectLoopback(idle.value,port),"Could not open idle connection");
|
||||
const auto start=std::chrono::steady_clock::now();
|
||||
server.stop();
|
||||
expect(std::chrono::steady_clock::now()-start<1s && !server.port() && server.token().empty(),
|
||||
"Stopping did not cancel the listener or detach the token");
|
||||
server.start(owner);
|
||||
expect(server.token()!=token,"A restarted listener reused a token");
|
||||
expect(post(server.port(),token,ping).starts_with("HTTP/1.1 401"),"A revoked token still works");
|
||||
expect(post(server.port(),std::string(server.token()),ping).starts_with("HTTP/1.1 200"),"The new token failed");
|
||||
server.stop();
|
||||
DestroyWindow(owner);
|
||||
return 0;
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
std::cerr<<error.what()<<'\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user