Feature: query the remote SHA-256 before previewing

When the main connection advertises CLIENT_CAP_FILE_HASH, double-click
sends COMMAND_FILE_HASH first and continues from the async
TOKEN_FILE_HASH response (posted to the UI thread). A matching SHA-256
opens the cached copy without a transfer, including content found under
a different remote path; the new path is added to the index. Too-large
and error responses are handled, and a 5 second timeout falls back to the
P1 size/mtime path.

The response parser is based on FileHashResponseHeader and the echoed
request path; pending state is cleared on close and the hash timer is
killed with the dialog.

Verified with the Debug server and client: a 1 MiB file was hashed,
transferred and cached under its SHA-256; an identical copy at a second
path hit the cache with no new transfer or stream connection.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-12-05 15:43:12 +01:00
1 parent ea5d69d1c0
commit 6cb779ef70
7 files changed
+168 -5

No files matched your search

+126 -5
View File
@@ -27,6 +27,18 @@ static uint64_t FileTimeToUnixMs(const FILETIME& ft)
return (u.QuadPart - kEpochDiff) / 10000ULL; return (u.QuadPart - kEpochDiff) / 10000ULL;
} }
static std::string HexSha256(const BYTE* sha)
{
static const char* hex = "0123456789abcdef";
std::string out;
out.reserve(64);
for (int i = 0; i < 32; ++i) {
out += hex[sha[i] >> 4];
out += hex[sha[i] & 0x0F];
}
return out;
}
#ifdef _DEBUG #ifdef _DEBUG
#define new DEBUG_NEW #define new DEBUG_NEW
#undef THIS_FILE #undef THIS_FILE
@@ -253,6 +265,7 @@ BEGIN_MESSAGE_MAP(CFileManagerDlg, CDialog)
ON_MESSAGE(WM_RECVFILEV2_CHUNK, &CFileManagerDlg::OnRecvFileV2Chunk) ON_MESSAGE(WM_RECVFILEV2_CHUNK, &CFileManagerDlg::OnRecvFileV2Chunk)
ON_MESSAGE(WM_RECVFILEV2_COMPLETE, &CFileManagerDlg::OnRecvFileV2Complete) ON_MESSAGE(WM_RECVFILEV2_COMPLETE, &CFileManagerDlg::OnRecvFileV2Complete)
ON_MESSAGE(WM_PREVIEW_RESULT, &CFileManagerDlg::OnPreviewResult) ON_MESSAGE(WM_PREVIEW_RESULT, &CFileManagerDlg::OnPreviewResult)
ON_MESSAGE(WM_PREVIEW_HASH_RESP, &CFileManagerDlg::OnPreviewHashResult)
#ifdef _DEBUG #ifdef _DEBUG
ON_MESSAGE(WM_APP + 0x123, &CFileManagerDlg::OnPreviewTest) ON_MESSAGE(WM_APP + 0x123, &CFileManagerDlg::OnPreviewTest)
#endif #endif
@@ -908,7 +921,18 @@ BOOL CFileManagerDlg::PreTranslateMessage(MSG* pMsg)
void CFileManagerDlg::OnTimer(UINT_PTR nIDEvent) void CFileManagerDlg::OnTimer(UINT_PTR nIDEvent)
{ {
// TODO: Add your message handler code here and/or call default if (nIDEvent == kPreviewHashTimer) {
KillTimer(kPreviewHashTimer);
if (!m_pendingHash.fullPath.IsEmpty()) {
CString full = m_pendingHash.fullPath;
uint64_t size = m_pendingHash.size;
uint64_t mtime = m_pendingHash.mtimeMs;
m_pendingHash = PendingHashPreview();
Mprintf("[Preview] hash timeout; fallback to metadata\n");
ContinueRemotePreview(full, size, mtime, std::string());
}
return;
}
m_ProgressCtrl->StepIt(); m_ProgressCtrl->StepIt();
__super::OnTimer(nIDEvent); __super::OnTimer(nIDEvent);
} }
@@ -1015,6 +1039,8 @@ void CFileManagerDlg::OnClose()
return; return;
} }
CFilePreviewMgr::Instance().CancelForHwnd(m_hWnd); CFilePreviewMgr::Instance().CancelForHwnd(m_hWnd);
KillTimer(kPreviewHashTimer);
m_pendingHash = PendingHashPreview();
CoUninitialize(); CoUninitialize();
DialogBase::OnClose(); DialogBase::OnClose();
@@ -1043,6 +1069,25 @@ CString CFileManagerDlg::GetParentDirectory(CString strPath)
void CFileManagerDlg::OnReceiveComplete() void CFileManagerDlg::OnReceiveComplete()
{ {
switch (m_ContextObject->m_DeCompressionBuffer.GetBuffer(0)[0]) { switch (m_ContextObject->m_DeCompressionBuffer.GetBuffer(0)[0]) {
case TOKEN_FILE_HASH: { // 远程文件 SHA-256 查询响应(双击预览 P2)
LPBYTE buf = m_ContextObject->m_DeCompressionBuffer.GetBuffer(0);
ULONG len = m_ContextObject->m_DeCompressionBuffer.GetBufferLen();
if (len < sizeof(FileHashResponseHeader)) break;
const FileHashResponseHeader* h = (const FileHashResponseHeader*)buf;
const size_t nameOff = sizeof(FileHashResponseHeader);
size_t nameLen = strnlen((const char*)buf + nameOff, len - nameOff);
FilePreviewHashResult* r = new FilePreviewHashResult();
r->path.assign((const char*)buf + nameOff, nameLen);
r->status = h->status;
r->err = h->err;
r->size = h->size;
r->mtimeMs = h->mtimeMs;
if (h->status == FILE_HASH_OK)
r->sha256 = HexSha256(h->sha256);
if (!PostMessage(WM_PREVIEW_HASH_RESP, 0, (LPARAM)r))
delete r;
break;
}
case TOKEN_FILE_LIST: // 文件列表 case TOKEN_FILE_LIST: // 文件列表
try { try {
FixedRemoteFileList FixedRemoteFileList
@@ -1325,6 +1370,39 @@ void CFileManagerDlg::BeginRemotePreview(const CString& fullPath)
return; return;
} }
// P2:支持哈希查询的客户端先取当前内容的 SHA-256,命中已有缓存即可不传输。
if (mainCtx->SupportsFileHash()) {
if (!m_pendingHash.fullPath.IsEmpty()) {
::MessageBox(m_hWnd, _TR("正在预览另一个文件,请稍候"),
_TR("提示"), MB_OK | MB_ICONINFORMATION);
return;
}
std::string remotePath((LPCSTR)fullPath);
m_pendingHash.fullPath = fullPath;
m_pendingHash.clientID = clientID;
m_pendingHash.size = meta.size;
m_pendingHash.mtimeMs = meta.mtimeMs;
std::vector<BYTE> pkt;
pkt.push_back(COMMAND_FILE_HASH);
uint64_t maxBytes = FILE_PREVIEW_MAX_BYTES;
const BYTE* mb = (const BYTE*)&maxBytes;
pkt.insert(pkt.end(), mb, mb + sizeof(maxBytes));
pkt.insert(pkt.end(), remotePath.begin(), remotePath.end());
pkt.push_back(0);
m_ContextObject->Send2Client(pkt.data(), (DWORD)pkt.size());
SetTimer(kPreviewHashTimer, 5000, NULL);
ShowMessage(_TR("正在获取远程文件信息…"));
return;
}
ContinueRemotePreview(fullPath, meta.size, meta.mtimeMs, std::string());
}
void CFileManagerDlg::ContinueRemotePreview(const CString& fullPath, uint64_t size,
uint64_t mtimeMs, const std::string& sha256)
{
uint64_t clientID = GetClientID();
std::string remotePath((LPCSTR)fullPath); std::string remotePath((LPCSTR)fullPath);
size_t pos = remotePath.find_last_of("\\/"); size_t pos = remotePath.find_last_of("\\/");
std::string basename = (pos == std::string::npos) ? remotePath : remotePath.substr(pos + 1); std::string basename = (pos == std::string::npos) ? remotePath : remotePath.substr(pos + 1);
@@ -1332,12 +1410,13 @@ void CFileManagerDlg::BeginRemotePreview(const CString& fullPath)
std::string outPath, error, cachedSha; std::string outPath, error, cachedSha;
CFilePreviewMgr::PrepareResult pr = CFilePreviewMgr::Instance().Prepare( CFilePreviewMgr::PrepareResult pr = CFilePreviewMgr::Instance().Prepare(
clientID, clientKey, remotePath, basename, meta.size, meta.mtimeMs, clientID, clientKey, remotePath, basename, size, mtimeMs,
std::string(), m_hWnd, outPath, error, &cachedSha); sha256, m_hWnd, outPath, error, &cachedSha);
Mprintf("[Preview] prepare result=%d out=%s err=%s\n", (int)pr, outPath.c_str(), error.c_str()); Mprintf("[Preview] prepare result=%d out=%s err=%s sha=%s\n",
(int)pr, outPath.c_str(), error.c_str(), sha256.c_str());
if (pr == CFilePreviewMgr::PrepareCached) { if (pr == CFilePreviewMgr::PrepareCached) {
CFilePreviewMgr::OpenLocalFile(m_hWnd, outPath, remotePath, meta.size, cachedSha); CFilePreviewMgr::OpenLocalFile(m_hWnd, outPath, remotePath, size, cachedSha);
return; return;
} }
if (pr != CFilePreviewMgr::PrepareTransfer) { if (pr != CFilePreviewMgr::PrepareTransfer) {
@@ -1373,6 +1452,46 @@ LRESULT CFileManagerDlg::OnPreviewResult(WPARAM /*wParam*/, LPARAM lParam)
return 0; return 0;
} }
LRESULT CFileManagerDlg::OnPreviewHashResult(WPARAM /*wParam*/, LPARAM lParam)
{
FilePreviewHashResult* r = (FilePreviewHashResult*)lParam;
if (!r) return 0;
KillTimer(kPreviewHashTimer);
if (!m_pendingHash.fullPath.IsEmpty()) {
std::string expected((LPCSTR)m_pendingHash.fullPath);
if (r->path == expected) {
CString full = m_pendingHash.fullPath;
uint64_t size = m_pendingHash.size;
uint64_t mtime = m_pendingHash.mtimeMs;
m_pendingHash = PendingHashPreview();
if (r->status == FILE_HASH_TOO_LARGE ||
(r->status == FILE_HASH_OK && r->size > FILE_PREVIEW_MAX_BYTES)) {
CString msg;
msg.FormatL("文件较大,不支持预览:%s(%llu MB,上限 %u MB)", full,
(unsigned long long)(r->size / 1024 / 1024),
(unsigned)(FILE_PREVIEW_MAX_BYTES / 1024 / 1024));
::MessageBox(m_hWnd, msg, _TR("提示"), MB_OK | MB_ICONINFORMATION);
} else if (r->status == FILE_HASH_OK) {
ContinueRemotePreview(full, r->size, r->mtimeMs, r->sha256);
} else if (r->status == FILE_HASH_ERROR) {
// 明确的错误(不存在/无权限/读失败):提示,不静默降级下载。
CString msg;
msg.FormatL("获取远程文件信息失败(错误码 %u)", r->err);
::MessageBox(m_hWnd, msg, _TR("提示"), MB_OK | MB_ICONWARNING);
} else {
// 未知状态/哈希超时按 P1 降级:用列表里的 size+mtime 继续。
Mprintf("[Preview] hash error status=%u err=%u; fallback to metadata\n",
r->status, r->err);
ContinueRemotePreview(full, size, mtime, std::string());
}
}
}
delete r;
return 0;
}
#ifdef _DEBUG #ifdef _DEBUG
// 无鼠标端到端测试:直接以 NM_DBLCLK 调同一个处理函数,避免跨进程鼠标注入。 // 无鼠标端到端测试:直接以 NM_DBLCLK 调同一个处理函数,避免跨进程鼠标注入。
LRESULT CFileManagerDlg::OnPreviewTest(WPARAM wParam, LPARAM lParam) LRESULT CFileManagerDlg::OnPreviewTest(WPARAM wParam, LPARAM lParam)
@@ -3035,6 +3154,8 @@ void CFileManagerDlg::PostNcDestroy()
} }
m_FileRecvDlgs.clear(); m_FileRecvDlgs.clear();
CFilePreviewMgr::Instance().CancelForHwnd(m_hWnd); CFilePreviewMgr::Instance().CancelForHwnd(m_hWnd);
KillTimer(kPreviewHashTimer);
m_pendingHash = PendingHashPreview();
__super::PostNcDestroy(); __super::PostNcDestroy();
} }
+11
View File
@@ -129,12 +129,23 @@ public:
bool m_bRemoteSearchResults = false; bool m_bRemoteSearchResults = false;
struct RemoteMeta { uint64_t size = 0; uint64_t mtimeMs = 0; }; struct RemoteMeta { uint64_t size = 0; uint64_t mtimeMs = 0; };
std::map<std::string, RemoteMeta> m_RemoteMeta; // key = 完整远程路径(GBK) std::map<std::string, RemoteMeta> m_RemoteMeta; // key = 完整远程路径(GBK)
struct PendingHashPreview {
CString fullPath; // 空 = 没有待响应的哈希请求
uint64_t clientID = 0;
uint64_t size = 0;
uint64_t mtimeMs = 0;
};
PendingHashPreview m_pendingHash;
enum { kPreviewHashTimer = 0x51 };
afx_msg LRESULT OnPreviewResult(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnPreviewResult(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnPreviewHashResult(WPARAM wParam, LPARAM lParam);
#ifdef _DEBUG #ifdef _DEBUG
// E2E 测试钩子:WM_APP+0x123,wParam=行号,lParam!=0 表示远程列表。 // E2E 测试钩子:WM_APP+0x123,wParam=行号,lParam!=0 表示远程列表。
afx_msg LRESULT OnPreviewTest(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnPreviewTest(WPARAM wParam, LPARAM lParam);
#endif #endif
void BeginRemotePreview(const CString& fullPath); void BeginRemotePreview(const CString& fullPath);
void ContinueRemotePreview(const CString& fullPath, uint64_t size, uint64_t mtimeMs,
const std::string& sha256);
void OpenLocalPath(const CString& path); void OpenLocalPath(const CString& path);
bool GetRemoteFileMeta(const CString& fullPath, RemoteMeta& meta); bool GetRemoteFileMeta(const CString& fullPath, RemoteMeta& meta);
std::string GetPreviewClientKey(uint64_t clientID); std::string GetPreviewClientKey(uint64_t clientID);
+16
View File
@@ -157,6 +157,22 @@ CFilePreviewMgr::PrepareResult CFilePreviewMgr::Prepare(
if (m.remotePath == hit.remotePath && m.localName == hit.localName) if (m.remotePath == hit.remotePath && m.localName == hit.localName)
m.lastUsed = now; m.lastUsed = now;
} }
// 按 SHA 命中另一条远程路径(跨路径去重):把当前路径补进索引,
// 下次同一路径可直接按 remotePath/size/mtime 命中,不必再查哈希。
if (hit.remotePath != remotePath) {
Meta m;
m.remotePath = remotePath;
m.size = hit.size;
m.mtimeMs = mtimeMs;
m.sha256 = hit.sha256;
m.localName = hit.localName;
m.lastUsed = now;
bool replaced = false;
for (auto& e : index) {
if (e.remotePath == remotePath) { e = m; replaced = true; break; }
}
if (!replaced) index.push_back(m);
}
SaveIndex(clientDir, index); SaveIndex(clientDir, index);
outPath = localPath; outPath = localPath;
if (outSha) *outSha = hit.sha256; if (outSha) *outSha = hit.sha256;
+12
View File
@@ -21,6 +21,18 @@ class CONTEXT_OBJECT;
// 预览完成/失败:lParam 是 new 出来的 CFilePreviewMgr::Result,由对话框 delete。 // 预览完成/失败:lParam 是 new 出来的 CFilePreviewMgr::Result,由对话框 delete。
#define WM_PREVIEW_RESULT (WM_USER + 0x306) #define WM_PREVIEW_RESULT (WM_USER + 0x306)
// 哈希查询响应:lParam 是 new 出来的 FilePreviewHashResult,由对话框 delete。
#define WM_PREVIEW_HASH_RESP (WM_USER + 0x307)
// COMMAND_FILE_HASH 响应的解析结果(对话框 UI 线程消费)。
struct FilePreviewHashResult {
std::string path; // 请求里原样回显的路径(GBK)
uint32_t status = 0;
uint32_t err = 0;
uint64_t size = 0;
uint64_t mtimeMs = 0;
std::string sha256; // 64 位小写十六进制;status != FILE_HASH_OK 时为空
};
// 设备级文件传输闸门:预览与 MCP 的 download/read、upload、C2C 都在同一临界区认领设备。 // 设备级文件传输闸门:预览与 MCP 的 download/read、upload、C2C 都在同一临界区认领设备。
// C2C 需要原子认领 src+dst 两个键。owner 只用于释放校验,避免旧会话误放新会话。 // C2C 需要原子认领 src+dst 两个键。owner 只用于释放校验,避免旧会话误放新会话。
+1
View File
@@ -2370,3 +2370,4 @@ MCP
无法获取文件信息,请刷新目录后重试=Dateiinformationen nicht verfuegbar; Verzeichnis aktualisieren und erneut versuchen 无法获取文件信息,请刷新目录后重试=Dateiinformationen nicht verfuegbar; Verzeichnis aktualisieren und erneut versuchen
文件较大,不支持预览:%s(%llu MB,上限 %u MB)=Datei zu gross fuer die Vorschau: %s (%llu MB, Grenze %u MB) 文件较大,不支持预览:%s(%llu MB,上限 %u MB)=Datei zu gross fuer die Vorschau: %s (%llu MB, Grenze %u MB)
正在预览 %s ...=Vorschau von %s ... 正在预览 %s ...=Vorschau von %s ...
获取远程文件信息失败(错误码 %u)=Dateiinformationen konnten nicht abgerufen werden (Fehler %u)
+1
View File
@@ -2381,3 +2381,4 @@ MCP
无法获取文件信息,请刷新目录后重试=Cannot get file information; refresh the directory and retry 无法获取文件信息,请刷新目录后重试=Cannot get file information; refresh the directory and retry
文件较大,不支持预览:%s(%llu MB,上限 %u MB)=File too large to preview: %s (%llu MB, limit %u MB) 文件较大,不支持预览:%s(%llu MB,上限 %u MB)=File too large to preview: %s (%llu MB, limit %u MB)
正在预览 %s ...=Previewing %s ... 正在预览 %s ...=Previewing %s ...
获取远程文件信息失败(错误码 %u)=Failed to get remote file information (error %u)
+1
View File
@@ -2374,3 +2374,4 @@ MCP
无法获取文件信息,请刷新目录后重试=無法取得檔案資訊,請重新整理目錄後重試 无法获取文件信息,请刷新目录后重试=無法取得檔案資訊,請重新整理目錄後重試
文件较大,不支持预览:%s(%llu MB,上限 %u MB)=檔案過大,不支援預覽:%s(%llu MB,上限 %u MB) 文件较大,不支持预览:%s(%llu MB,上限 %u MB)=檔案過大,不支援預覽:%s(%llu MB,上限 %u MB)
正在预览 %s ...=正在預覽 %s ... 正在预览 %s ...=正在預覽 %s ...
获取远程文件信息失败(错误码 %u)=取得遠端檔案資訊失敗(錯誤碼 %u)