Commit Graph
316 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash bfb17d0d25 Feature: Draw the remote cursor in the web desktop out of control mode
Screen frames are captured without the pointer composed in (GDI SRCCOPY,
DXGI), so browsers only ever knew the cursor's shape index and could show a
cursor just in control mode, where the local pointer stands in for the remote
one. Both servers now relay the cursor position that every per-frame header
already carries: shape changes go out immediately, position changes at most
every 50 ms, and an unchanged cursor is re-sent once a second so a viewer that
joins while the pointer is idle still learns where it is.

The page hides the local pointer and draws the remote cursor at its true
position while out of control mode; entering control mode restores exactly the
old behaviour (remote-shaped CSS cursor on desktop, touchpad pointer on touch).
A server that never sends x/y leaves the page on its previous fallback.

The C++ server broadcasts from the per-frame path, so header-only frames keep a
static desktop's cursor fresh; the Go hub dedups and throttles before fanning
out. Tests cover the throttle/refresh rules and the relayed payload.

Co-Authored-By: deepseek-flash
2026-10-26 17:44:13 +01:00
yuanyuanxianganddeepseek-flash 6236ed1eb4 Fix: Make the Go web console wheel scroll correctly
The Go web server's mouse handler read deltaY as an int, so json.Unmarshal
rejected the entire mouse message whenever the browser reported a
fractional delta (Chrome's smooth scrolling splits one 100px notch into
33.33 + 33.33 + 33.34), and the wheel was dead while clicks and moves
kept working. Treating every event as one notch was wrong the other way:
it scrolled three to four times too far, and sub-pixel deltas from a
touchpad truncated to zero.

The server now accumulates the delta in notch units per client and
injects WM_MOUSEWHEEL only once a whole notch is reached. The remainder
is rounded, not truncated, so a float sum of 99.99px still lands on
exactly one notch and the first notch fires halfway through a physical
one, like native scrolling. The page forwards e.deltaMode so line and
page based deltas convert correctly, and touchpad flings are capped at
20 notches per event.

Verified against a live Go server with a connected client: 100px sends
one packet, three 33.33px events send one, 53.33px sends one, sub-pixel
events accumulate to none, and the wParam is -120 down / +120 up with
SendToScreen returning no error. The MFC web console is untouched.

Co-Authored-By: deepseek-flash
2026-10-26 17:10:09 +01:00
yuanyuanxianganddeepseek-flash c271911fcb Feature: Add copy_files_c2c to transfer files between clients directly
Adds the 54th MCP tool, copy_files_c2c, which asks the source client to
push a set of files straight to another online client. Previously the only
way to move files between two clients was to download them to the server
machine and upload them again, so the data crossed the wire twice and
needed free disk on the server. With C2C the server only relays packets
and never parses or stores the payload.

Protocol. Two new ids in common/commands.h: COMMAND_C2C_SEND_FILES (174),
carrying the destination directory followed by a NUL-separated path list,
and TOKEN_C2C_SEND_RESULT (175), a fixed 45-byte result packet sent back
over the same sub-connection the transfer used. Clients advertise support
with the LOGIN_INFOR capability bit CLIENT_CAP_C2C_PATHS (0x0008), exposed
server side as Context::SupportsC2CPaths(). File transfer V2 already knew
how to push to dstClientID, so the destination side needed no change at
all; existing V2 receive paths keep working, and older clients simply do
not advertise the bit and are rejected with a clear error instead of
hanging.

Client. OnC2CSendFiles expands environment variables, collects directories
recursively, opens its own sub-connection (with sub-connection auth), and
runs FileBatchTransferWorkerV2 in a detached thread, then reports the
result on that same connection. Every early exit now reports a structured
failure rather than staying silent. The worker needs the process-level
InitFileUpload call that the receive path performs lazily, and a source
client may never have opened a file manager or received an upload, so the
initialization is factored into EnsureV2TransferInited() and called from
both paths.

Server. copy_files_c2c mirrors the existing upload tool: gates, id parsing,
capability checks, path validation, then a session keyed on the source host
that WaitC2CDone polls until the result packet arrives. The C2C relay
branch used to attach a CDlgFileSend progress dialog to the source's
sub-connection; NotifyProc then routed every later packet on that
connection to the dialog, which parsed the result packet as a V1 file
chunk and dropped it, so the tool always timed out even though the files
had arrived. IsC2CTransferPending() now suppresses dialog creation for
MCP-driven transfers only, leaving manual Ctrl+V transfers untouched.
Errors map to -32001 for a source-side transfer failure, -32010 for access
denied, -32009 for a missing path and -32002 for an offline destination.
Both hosts must be Windows: the destination is restricted too, because the
source embeds dst_dir in each V2 chunk name as an absolute Windows path and
only the Windows receiver applies it literally. A Linux or macOS receiver
never gets a target directory here (the clipboard flow sets one with
COMMAND_C2C_PREPARE, which this path does not send), so it would strip the
drive letter and write under / instead. Supporting that needs a prepare
packet carrying an explicit path plus an upgrade of those clients, so for
now the tool rejects them with -32005 rather than writing somewhere wrong.

Verified end to end on the Debug build: three files including a non-ASCII
name, an empty directory and a 3 MB binary arrived with matching SHA-256
in 3.2 s, a non-existent destination directory was created, and the
negative cases returned the documented codes. mcp_smoke.ps1 passes 41/41
with two new assertions and 27/27 in -SkipHost mode. Design notes, error
table and limitations are in docs/Mcp_FileTransfer_Design.md section 14
and docs/Mcp_Design.md section 15.

Co-Authored-By: deepseek-flash
2026-10-26 15:38:07 +01:00
yuanyuanxianganddeepseek-flash 27d40f5678 Fix: Expose tool payloads in the content text block
List and query tools put only a human summary in content and kept the real
payload in structuredContent. Clients that hand just content to the model
(WorkBuddy does) therefore never saw a host id: search_hosts answered "1 host
matched" and every follow-up tool was out of reach, and guessed ids 1-3100
could never work because host ids are 64-bit snowflake values.

BuildResult now appends the serialized structuredContent as a second text
block, as the MCP spec recommends for tools with structured output. The append
sits in the single result choke point, so every tool in McpServer, McpMachine
and McpChat gains it, including future ones; empty action results such as
remote_mouse keep their bare "ok".

Tools whose text already carries the payload expose only the difference:
exec_command and terminal_exec add exit_code, get_keylog adds counters,
get_activity_history exposes records without the duplicated raw dump, and the
hosts file reader drops its copy of the content. The override rides in a $
key that BuildResult consumes and removes, so responses change only by the
extra block.

Verified on a Debug instance: list_all_hosts, search_hosts, get_server_status
and list_registry return parseable JSON in content[1] with ids intact, and
tools/mcp_smoke.ps1 -SkipHost passes 27/27 with four new assertions.

Co-Authored-By: deepseek-flash
2026-10-26 14:12:50 +01:00
yuanyuanxianganddeepseek-flash a7dd86ff0f Feature: Terminate TLS for the MCP endpoint inside YAMA
MCP was served by a plain httplib::Server, so remote clients could only use
cleartext HTTP. YAMA now terminates TLS itself: a small front-end owns the
MCP port, sniffs the first byte and either runs a Schannel handshake and
forwards the decrypted bytes or passes plaintext through, with httplib
moving to a loopback-only internal port. No OpenSSL, no frp change, existing
local HTTP clients keep working, and an unusable certificate fails closed
instead of falling back to cleartext.

The identity loader grew the two things a public certificate needs. ECDSA
(P-256/P-384/P-521) keys are persisted by importing PKCS#8 with an
NCRYPTBUFFER_PKCS_KEY_NAME parameter, the only route MS Software KSP
supports for Schannel; RSA keeps its old export-and-repersist path.
Fullchains are accepted, and the intermediates are added to the current
user's CA store so Schannel, which builds chains only from system stores,
actually sends them. The shared handshake also now buffers a full TLS
record before the first AcceptSecurityContext, which a partial ClientHello
would otherwise poison (SEC_E_UNKNOWN_CREDENTIALS).

Session resumption exposed a second trap: when a client resumes a session,
ChangeCipherSpec, Finished and the first application record arrive in one
segment and AcceptSecurityContext leaves the application record pending in
the session. Nothing drained it, because both callers only decrypt when new
ciphertext arrives, so the request waited until the peer gave up (the MCP
front-end saw no request at all and the client reported "fetch failed
(other side closed)"; the device port had the same hole behind its
occasional login timeouts). Decrypt now drains pending data on len == 0, and
both the front-end and the device port's handshake thread use it before
entering their receive loops.

Configuration is McpHttps, McpCertPath, McpKeyPath and McpInternalPort, the
first three editable in the MCP settings dialog (the certificate rows stay
greyed out until HTTPS is enabled and saving rejects missing files).

Verified with a real Let's Encrypt ECDSA fullchain (53 tools over TLS, 401
with no or bad token), a local three-level chain whose intermediate was
absent from the store, Node 24's fetch on a resumed session (initialize,
notifications/initialized and tools/list all complete), and the device
port's RSA handshake as a regression check. Details in docs/Mcp_Design.md
section 13.

Co-Authored-By: deepseek-flash
2026-10-26 13:56:41 +01:00
yuanyuanxianganddeepseek-flash b4cb34fea9 Fix: Stop MCP tool timeouts from popping MFC dialogs
A sub-connection's first packet doubles as the readiness packet: the file,
service, registry, process, log and terminal tools all get answered that way.
Once a tool has given up (timeout or failure) its pending entry is gone, so if
the client only gets around to sending that first packet afterwards,
MessageHandle cannot tell it apart from a human click and opens the matching
modeless dialog - a File Manager window appeared while timeouts were being
exercised on this machine.

The wait paths now record, per device, which first-packet token the abandoned
tool would have sent (MarkLateFirstPacketForTool from WaitPending,
WaitPendingRegistry, WaitPendingWrite, WaitFileTransferDone and
WaitTerminalReady), and every dialog-opening case consumes that marker before
falling back to the MFC path. The marker is one-shot, expires after five
minutes and is never set on the success path, so normal use is unaffected; the
worst case is that a single manual open on a host that just had an MCP timeout
is swallowed.

ClientMsg packets are dropped with a log line while a tool is pending for that
host: new clients still send the legacy popup message alongside the structured
failure token, which would otherwise put a modal box on the server UI during an
MCP call.

Co-Authored-By: deepseek-flash
2026-10-25 18:12:56 +01:00
yuanyuanxianganddeepseek-flash 1456882f16 Docs: Record the structured failure protocol and -32010
Spell out the new token layout and who sends it, add -32010 to the error
table, and narrow -32008 to parameter validation now that capability
limits report -32005. Document McpToolTimeoutMs as an ini-only key and
correct the note about where the list_files 500-entry cap is applied.

Update the remote-control design and the test report so P2, P6 and P8
show as fixed with the measured evidence.

Co-Authored-By: deepseek-flash
2026-10-25 17:59:24 +01:00
yuanyuanxianganddeepseek-flash 3b1626f415 Feature: Turn client failure reports into branchable MCP errors
Wire the four new failure tokens into MessageHandle and translate them
in the tool builders, so the three previously silent failures now return
a code an agent can branch on: list_services on a non-elevated client is
-32010 in well under a second instead of a 20 s timeout, list_files and
list_registry distinguish a missing path or key (-32009) from an empty
one, and download_file no longer waits for the stall watchdog when the
remote path does not exist. Access denied gets its own code, -32010, and
the win32 code is kept in the message for every case.

TakeRegError fills both registry wait flags in one packet because a
failing client sends no subkey or value packet at all. OnDownloadError
sets the session error without cancelling the file-manager sub-connection,
which stays owned by ClearFileTransfer. ListRemoteTopLevelNames treats
"not found" as "directory not created yet" so uploading into a fresh
directory keeps working now that the client reports it.

Also converge the error codes that were overloaded: a multi-monitor host
is a capability limit, not a parameter mistake, so remote_open reports
-32005 instead of -32008. The tool wait timeout moves from a compile-time
constant to McpToolTimeoutMs in settings.ini (default 20000, clamped to
1-600 s), which makes it possible to tune without a rebuild.

The smoke test gains the three reproducible negatives.

Co-Authored-By: deepseek-flash
2026-10-25 17:59:21 +01:00
yuanyuanxianganddeepseek-flash 315a0855dc Feature: Let the client report structured failures for MCP tools
Four new client-to-server tokens carry a win32/LSTATUS code when a
command fails instead of returning empty data: TOKEN_SERVICE_ERROR
(170), TOKEN_FILE_LIST_ERROR (171), TOKEN_REG_ERROR (172) and
TOKEN_DOWNLOAD_ERROR (173). They sit on byte values that were unused,
so existing numbering is untouched.

The three data paths that used to collapse "failed" and "empty" into
the same packet now distinguish them: OpenSCManager failures, directory
enumeration failures and RegOpenKeyEx failures all report the code that
was actually returned, and UploadToRemoteV2 reports why it found no
file to transfer before the transfer sub-connection is ever created.

Every failure branch still sends the packet the old server expects
(TOKEN_FILE_LIST, the empty TOKEN_REG_PATH/KEY pair, the ClientMsg
popup), so a new client talking to an old server degrades to exactly
today's behaviour instead of timing out. Success paths are byte-for-
byte unchanged.

Co-Authored-By: deepseek-flash
2026-10-25 17:59:17 +01:00
yuanyuanxianganddeepseek-flash eaa10cc7d3 Fix: Make the MCP command sentinel robust and fail stalled downloads fast
Re-verified every finding of the 2026-10-25 MCP test report against the source and
then end-to-end on the Debug instance, and fixed the ones that live on the server.

P1/P3/P4 share one root cause: the sentinel was appended to the command line, so any
command that swallows the rest of its line (rem, cmd /c, if, for) swallowed the
sentinel too and the call always timed out. On ConPTY clients the command and the
sentinel are now sent as two lines, the sentinel prints %errorlevel% (whose echoed
text is a literal template, not digits) so folding echo can no longer be mistaken
for the sentinel, and FindSentinel returns the real exit code (9009, 1, 0, ...)
instead of 0/1. Old non-PTY clients keep the single-line form, since their echo
skipping depends on the write length.

ConPTY also returns a rendered screen stream rather than a byte stream, so stripped
VT sequences leave duplicate text behind; output cleaning now cuts through the
echoed command line, strips the echoed sentinel line and erases any leftover
sentinel text by its per-command nonce. StripAnsi no longer leaves the backslash of
an OSC terminated by ST.

A terminal session destroyed by a timeout used to report the same "not found" text
as a typo in the session id; a 600s tombstone now says what happened instead.
download_file gets a stall watchdog: no data for 60s fails with a clear message and
releases the host, where a missing remote path used to hold the whole host for the
full 600s default timeout.

Also corrects the get_activity_history annotation (it does reach the remote host),
completes the -32007/-32008/-32009 error table, documents the sentinel design in
Mcp_Design.md 12.1, and corrects the report's claim that the tools blocked during a
transfer are local DB reads -- they are remote machine-manager fetches, and purely
server-local tools are unaffected.

Co-Authored-By: deepseek-flash
2026-10-25 17:09:39 +01:00
yuanyuanxianganddeepseek-flash 1c5fab1645 Fix: Stop the client dropping chat messages that begin with e
CChatManager::OnReceive opened with the same heartbeat guard the other
managers use, `if (szBuffer[0] == TOKEN_HEARTBEAT) return;`, before it
looked at the length. TOKEN_HEARTBEAT is 101, which is also the letter e,
and this channel carries free text rather than command bytes, so every
message starting with e -- "echo", "error", anything -- was silently
discarded. The sender never learned: the server's chat dialog had already
written the text into its own log, so the two sides disagreed about what
was said.

The guard is dead code here. Heartbeats travel on the main connection
only, as a multi-byte [101][Heartbeat] packet consumed by the main
dispatcher; the server never sends one on a chat sub-connection. Delete
it and keep the length check that follows.

The server keeps prepending a space when the GBK payload starts with
101, because already-deployed clients still carry the guard and losing
the message outright is worse than an invisible leading space. Note the
same guard, harmless today, still sits in the machine, file, proxy and
screen-hide managers.

Verified with the Debug instance and a local Debug client: with the
server's space temporarily disabled, chat_send "echo test" and
"second line" both showed up verbatim in the client dialog (read back
with WM_GETTEXT); with the space restored the first arrives as
" echo test". Details in docs/Mcp_Chat_Design.md section 5.

Co-Authored-By: deepseek-flash
2026-10-25 14:57:47 +01:00
yuanyuanxianganddeepseek-flash cc3e11d30d Improve: Cover protocol and policy error codes in the MCP smoke test
The suite only exercised the happy paths, so a regression in the
negative paths -- unknown method, unknown tool, a missing required
argument, an oversized batch or a policy refusal -- would have gone
unnoticed. Add those checks alongside a section that reads the switches
from get_server_status, picks a feature that is actually turned off and
asserts its tool answers -32006; with every switch on it skips rather
than guessing, and with -AuditLog it also asserts the refusal shows up
as CALL_DENIED.

Document the full error-code table in section 12, including which codes
mean "retry with different arguments" and which mean "this is a policy
decision, retrying is pointless", and note that a batch call never
fails as a whole for per-host errors.

Verified against the Debug instance with McpKeylog temporarily set to
zero: get_keylog refused with -32006 and the audit log gained the
matching CALL_DENIED line, 34 checks passing; with the switch restored
32 pass, and 37 with a search path.

Co-Authored-By: deepseek-flash
2026-10-25 14:44:45 +01:00
yuanyuanxianganddeepseek-flash 7c5bf3e73d Feature: Filter search_file results by size, mtime and slim fields
Add four optional arguments to search_file that narrow the match list
after the client has returned it: min_size and max_size in bytes,
modified_after in either YYYY-MM-DD or YYYY-MM-DD HH:MM:SS form, and
name_only to keep just path and name per entry. The client still runs
the same name-matched recursive search, so these filters cut the
response size and the reasoning work on our side, not the scan time on
the host -- the summary sentence says so and totalAll keeps the
pre-filter count so a too-narrow condition is obvious. Invalid values
(negative sizes, an inverted range, a malformed timestamp) are rejected
with -32602 before any packet goes out.

The timestamp validator only accepted the ten-character form because
its shape loop never allowed the two colons, which rejected every
nineteen-character value; the loop now whitelists them.

Smoke tests cover the unchanged totalAll under a size filter, the slim
name_only payload and a rejected timestamp, for 33 checks when the
search path is supplied. Design notes are in section 11.4.

Co-Authored-By: deepseek-flash
2026-10-25 14:41:52 +01:00
yuanyuanxianganddeepseek-flash 929065e7be Feature: Filter the MCP host lists by group, OS and client type
list_online_hosts and list_all_hosts could only page, so finding "the
hosts in this group" or "the Linux ones" meant walking pages or falling
back to search_hosts, which has no client type filter and treats online
and offline hosts differently.

Both tools now accept group, os and client_type. They are substring
matches, combined with AND and case-insensitive over ASCII, matching the
semantics search_hosts already used, and the shared implementation keeps
the two tools from drifting apart. The filter runs before paging, so
total counts the matches and totalAll keeps the pre-filter size, and the
summary switches to the "matches" wording with a trailing line naming
the unfiltered size - a mistyped condition then shows up immediately
instead of silently returning nothing.

Offline hosts carry no clientType in their stored record, so a
client_type filter never matches them; the tool description says so and
points at os for that case.

Verified on the Debug instance: client_type=exe matches the single EXE
host while client_type=lnx matches nothing and still reports totalAll=1;
list_all_hosts with group=default matches all 3161 recorded hosts and
splits them into 1 online and 3160 offline, and os=zzz matches none. The
smoke test gains two checks and passes 28/28.

Co-Authored-By: deepseek-flash
2026-10-25 14:37:28 +01:00
yuanyuanxianganddeepseek-flash 5ce453797c Feature: Add a get_server_status tool to the MCP server
Answering "did my rebuild actually take effect" or "why was that tool
refused" used to mean reading list_online_hosts and get_audit_log and
inferring the rest. A single read-only call now returns the server's own
state: brand and version, the exe link time (taken from the file's last
write, which unlike __DATE__ reflects the whole build), how long the
process has been up, the address and port MCP is actually listening on,
every MCP switch, online and offline host counts, the number of sessions
in flight per family, and how many source IPs are currently blocked.

The bind and port are recorded by Start rather than re-read from the
configuration, so the tool reports what the listener really got. Session
counters take each subsystem's lock in turn and release it immediately,
so the numbers are an estimate of one moment, not a consistent snapshot.
Nothing sensitive is exposed: the token and the command whitelist never
appear, and the switches are reported as booleans only.

The tool is registered as read-only, non-destructive, idempotent and
server-local, which brings tools/list to 53 entries. The smoke test gains
three checks for it, including one that fails if a token-shaped field
ever appears in the output.

Verified on the Debug instance: the summary line reports version, uptime
and listener correctly, sessions.terminal goes 0 to 1 while a persistent
terminal is open and back to 0 after terminal_close, and the smoke test
passes 26/26.

Co-Authored-By: deepseek-flash
2026-10-25 14:35:19 +01:00
yuanyuanxianganddeepseek-flash ae37e812ee Feature: Page and filter the MCP audit log tool
get_audit_log used to hand back every entry in the main window's message
mirror on each call. The mirror is a 1000-entry ring buffer, so a busy
server returned a lot of text the caller never looked at, and there was
no way to ask for just the MCP entries or just the ones mentioning a
particular subject.

The tool now takes the same limit/offset pair as the other list tools
and two optional substring filters: type matches the type column and
keyword matches the message text, both case-insensitive. Filtering runs
before paging, so total counts the matches while totalAll keeps the size
of the whole mirror, and the summary line adds the pre-filter count when
a filter is in use so a typo is easy to spot. The GBK to UTF-8
conversion moved into the filter loop so the comparison happens between
strings in the same encoding, still under the dialog's critical section.

The output schema gains total/totalAll/offset/limit/hasMore, and the
smoke test now asserts the paging fields, the limit bound and an empty
result for a filter that cannot match, bringing it to 23 checks.

Verified on the Debug instance: limit=2 returns entries 1-2 then 3-4
with hasMore set, offset=999 reports the out-of-range text, type=mcp
matches the "MCP命令执行" entry, type=提示 matches both hint types and
keyword=监听 matches the listening-port line.

Co-Authored-By: deepseek-flash
2026-10-25 14:31:14 +01:00
yuanyuanxianganddeepseek-flash d9a1a9ebcb Fix: Record policy refusals in the MCP audit log
Every policy denial - read-only mode, one of the Mcp* switches turned
off, or a host that lacks the required capability - answers -32006. The
audit log only ever showed CALL_FAIL for those, which lumped them
together with parameter errors, offline hosts and timeouts, so after the
fact there was no way to tell "nobody called this" from "it was blocked
by policy".

The hooks all live in one place: the tools/call exit in the HTTP
handler now also reads error.code and error.message from the response it
already parses, and appends a CALL_DENIED event when the code is -32006.
The original CALL_FAIL line is still written, so its statistics keep
their old meaning, and the reason text is the fixed English sentence
each branch already returns - no tool arguments or user input reach the
log. Tool names taken from the request are flattened to a single line
first, both in the denied event and in the existing CALL_OK/CALL_FAIL
lines, so a crafted name cannot forge extra audit rows.

Also refresh the stale note in the design document that still called the
client search MAX_PATH overflow unfixed; the source was fixed in
8f718d9, but already-deployed clients still carry it, which is why the
smoke test keeps its search cases opt-in.

Verified on the Debug instance: with McpFileTransfer temporarily set to
0, download_file returns -32006 and the audit log gains the expected
CALL_DENIED line right after its CALL_FAIL; with the switch restored the
same call is CALL_OK again and no denied line appears. The read-only
smoke test passes 20/20.

Co-Authored-By: deepseek-flash
2026-10-25 14:28:16 +01:00
yuanyuanxianganddeepseek-flash 16f23e164c Fix: Clear the file transfer session when its sub-connection drops
A file transfer session holds raw pointers to its file-manager and
stream sub-connections, but nothing on the offline path looked at them.
OfflineProc cleans up terminal, remote-control and chat sessions and
skipped file transfers entirely, so a client that disconnected in the
middle of a transfer left the session pointing at a context that went
back to the connection pool. When the tool thread timed out it called
CancelIO on that stale pointer, which could cancel somebody else's
connection.

Add a context-to-device table next to the sessions, kept under the same
mutex and erased by ClearFileTransfer so a recycled pointer is never
mistaken for a live one. OfflineProc now calls
OnFileTransferContextClosed, which drops both pointers. A dropped
stream sub-connection means the transfer cannot complete, so it also
fails the session with error 1003 and wakes the waiting thread; the
file-manager sub-connection only issues the command and its loss is not
treated as a failure of the transfer itself.

Verified against the debug client: killing it 1.2 s into a 500 MB
download returns "Connection lost: the transfer sub-connection closed"
after about 1 s instead of waiting out timeout_ms, and the server stays
up. After the client restarts, two consecutive downloads and one upload
still work.

Co-Authored-By: deepseek-flash
2026-10-25 14:20:13 +01:00
yuanyuanxianganddeepseek-flash 39f0928de7 Fix: Finish a directory-only download instead of waiting for the timeout
The completion check compared filesDone against totalFiles minus
directoryCount and only ran on COMMAND_FILE_COMPLETE_V2. The client
sends no COMPLETE for directory entries, so a download of an empty
directory, or of a tree that holds only subdirectories, had zero
expected files and could never satisfy the check. The call sat there
until timeout_ms expired (600 s by default) and then reported 1002.

Mark the session done as soon as the directory entries account for
every entry the client declared. Verified with the debug client: an
empty directory returns in 0.2 s with zero files, a tree of nested
subdirectories returns in 0.2 s with the directories created, and a
directory holding three files still downloads them with the same
sizes and hashes as before.

Co-Authored-By: deepseek-flash
2026-10-25 14:16:46 +01:00
yuanyuanxianganddeepseek-flash 8f718d9b39 Fix: Stop the client file search from overflowing its path buffers
SearchFilesRecursive built "%s\*.*" and "%s\%s" with wsprintf into
char[MAX_PATH] buffers and never checked the lengths. The recursion
allows 32 levels, so a search from a drive root accumulates paths well
past 260 characters and writes off the end of the stack frame. Debug
builds raise Run-Time Check Failure #2 and the dialog blocks the search
thread; release builds corrupt the stack silently.

Check the length before each build and skip the entry when the full
path does not fit, so neither the name nor the recursion below it is
recorded. The root directory is checked once at function entry, which
also stops an over-long root from being enumerated at all.

Apply the same guard to the directory listing paths in both file
managers, and bound the search pattern built from the incoming keyword.
Zero-initialize the buffers filled by ExpandEnvironmentStringsA so a
failed expansion is treated as an empty path instead of reading
uninitialized stack.

Verified against the debug client with a full C:\ scan (10,000 results,
finished, no dialog) and a repeated deep search afterwards.

Co-Authored-By: deepseek-flash
2026-10-25 14:05:25 +01:00
yuanyuanxianganddeepseek-flash abe7e99a77 Feature: Harden the MCP transport and add non-destructive host tools
Cap MCP request bodies at 2 MB, set a 15 s idle read timeout and a 60 s
write timeout, and give httplib an explicit 32-thread pool: long tools
such as chat_wait hold a worker for up to 55 s, and the default pool of
8 to 15 left other callers queued.

Every tool returned by tools/list now carries readOnlyHint,
destructiveHint, idempotentHint and openWorldHint. The table is
per-tool; anything not registered defaults to destructive so a new
write tool cannot silently look harmless. Read-only tools are forced
to destructiveHint=false.

get_host_detail appends the technical fields the host store already
holds (cpuCores, memoryGB, systemBits, programBits, user, isAdmin,
installTime, expiredDate, monitors, exeVersion, clientPath, pid,
publicIp). The JSON writer is pinned to 15 significant digits so
memoryGB renders as 27.8 instead of 27.800000000000001. list hosts
output is unchanged.

Add host_set_remark and host_set_watch_level. Both validate the host
against the store, are refused in readonly mode, repaint the affected
row, and are audited without recording the value written.

Add search_file, which drives the client file-manager search channel
and returns paged results. The root path is normalized before sending:
the client enumerates with wsprintf("%s\*.*"), so a trailing
backslash produced C:\*.* and FindFirstFile failed, returning zero
hits instantly. The client only searches recursively, so non-recursive
requests are filtered server-side by comparing the parent directory.
Collection stops at 5000 records or 4 MB and the client is told to
stop; on timeout the partial results are returned. Search result
packets are never closed early: the sub-connection stays open until
TOKEN_SEARCH_FILE_FINISH, because the client's search thread holds a
pointer into the file manager object.

Batch reads report a skipped counter and are bounded to 50 ids and a
50 s deadline.

Add tools/mcp_smoke.ps1, a read-only end-to-end smoke test that asserts
auth rejection, the payload limit, annotation coverage, paging fields
and the main read tools. It takes the token from the environment and
never prints it.

Document all of the above in docs/Mcp_Design.md section 10, including
the client-side MAX_PATH stack overflow that a deep search_file call
can trigger, together with the workaround of searching shallow
directories.

Co-Authored-By: deepseek-flash
2026-10-25 13:59:17 +01:00
yuanyuanxianganddeepseek-flash ac5b174b5f Feature: Add offline hosts, batch reads and MCP hardening
Expose hosts the server already knows about. list_all_hosts enumerates
both live contexts and the historical records in the client list, with
authStatus as a three-state string instead of a boolean. search_hosts
now honours online=false instead of returning an empty list, while the
default stays online-only so existing callers see the same results.
get_host_detail falls back to the last known record for an offline host
rather than failing with -32002.

Let read-only tools take an ids array of up to 50 hosts in one call.
The batch path reuses the single-host dispatcher and pages per host, so
behaviour cannot drift; write tools reject ids with -32602 so a mistake
cannot fan out across machines.

Add get_keylog behind its own McpKeylog switch. It drives the client's
existing keylogger sub-connection, accumulates the streamed text for a
bounded window and byte cap, then closes the sub-connection and returns
UTF-8 lines. The client pushes its buffered history first, so a result
contains both history and fresh keystrokes; the tool description says so.

Harden the endpoint. Failed bearer checks are counted per source IP and
ten failures within a minute block the IP for fifteen minutes. Auth
failures and tool calls append to logs\mcp_audit.log with metadata only:
no token, no arguments, no response bodies, and rotation at 5 MB. Loopback
sources are audited but never blocked, because the built-in frp tunnel
makes every remote request arrive from 127.0.0.1 and banning that address
would lock out legitimate clients along with the attacker.

Give list-style tools one pagination contract (limit/offset plus
total/totalAll/hasMore) and fix the generated schemas so id and ids are
genuine alternatives: the stale required:[id] left over from the
single-host schema would otherwise reject ids-only calls.

Co-Authored-By: deepseek-flash
2026-10-25 12:44:45 +01:00
yuanyuanxianganddeepseek-flash cc0e4bbd7a Fix: Pass win keys down the hook chain while a chat is locked
During a locked chat the client installs a WH_KEYBOARD_LL hook that
swallows Alt+Tab, Alt+F4, Alt+Esc, Ctrl+Esc and the Win keys, so the person
sitting at the machine cannot get out of the lock. The hook returned 1
without calling CallNextHookEx. Low-level hooks run last installed first,
and this one is installed later than the server's hotkey forwarding hook,
so it sits in front of it: returning 1 ended the chain and the forwarding
hook never saw those keys. With YAMA running on the same machine as the
client, Win shortcuts stopped reaching the remote host for as long as the
lock was up.

The event is now passed down the chain before it is swallowed.
CallNextHookEx hands the event to the other hooks only, not to the system
or the shell, so the local shell is still blocked and the lock behaves
exactly as before, while the forwarding hook can see the key and act on
it.

Co-Authored-By: deepseek-flash
2026-10-25 02:40:30 +02:00
yuanyuanxianganddeepseek-flash 73aa2725b9 Fix: Pick an MSBuild instance that has ATL, not the first found
build.ps1 took the first MSBuild.exe matching a hardcoded glob under
%ProgramFiles% / %ProgramFiles(x86)%. On a machine that has both a
command-line build tools instance and an IDE, that is the build tools one.
It ships the v142 compiler, but ATL is a separate optional component there,
so the link step failed with LNK1104 on atls.lib while the same sources
built cleanly in the IDE whose instance carries ATL. The vswhere lookup
meant to cover installations on other drives never ran, because the glob
had already matched.

Candidates are now validated against VC\Tools\MSVC\*\atlmfc\lib\x86\atls.lib
before being accepted, every rejected instance is reported, and the vswhere
lookup enumerates all instances and applies the same check, so an
installation on another drive is found as well. When no instance carries
ATL the first candidate is still used, with a warning, which keeps the
previous behaviour and lets MSBuild emit the more specific error.

The script is also saved as UTF-8 with BOM: Windows PowerShell 5.1 reads a
BOM-less UTF-8 script as ANSI, which turns some Chinese comment characters
into a trailing backtick and swallows the following line.

This commit also carries the pending build script work: the Go server
builder, the -ClientOnly fast path, and the serverd / client debug presets
in build.cmd. Skills.md documents the two new presets.

Co-Authored-By: deepseek-flash
2026-10-25 02:38:46 +02:00
yuanyuanxianganddeepseek-flash 37d0297f07 Fix: Keep the keylogger thread pumping so the hook chain stays alive
The low-level keyboard hook callback runs only while the thread that
installed it pumps messages, but KeyLogger() gated PeekMessage on
IsConnected(). With offline recording enabled (kbrecord=Yes) and no
keyboard sub-connection, the hook stayed installed while its thread
never pumped, so every keystroke on the machine stalled against
LowLevelHooksTimeout (300 ms by default) and the hook was eventually
dropped by the system. Because the client installs its hook after YAMA
installs its own, the client's hook sits in front of YAMA's in the
chain, and the starved events broke the key pairs YAMA needs: Win
shortcuts and Ctrl+V forwarding stopped working while ordinary typing
was unaffected.

Pump messages unconditionally; this code is only reached while the hook
is installed, and the offline-record path installs it even without a
keyboard sub-connection.

Co-Authored-By: deepseek-flash
2026-10-25 02:22:17 +02:00
yuanyuanxianganddeepseek-flash 7160ea8f42 Fix: Stop the online-host list header from flickering
The list header is a child window of the list view, and
LVS_EX_DOUBLEBUFFER only covers the item area. The list view was created
without WS_CLIPCHILDREN, so every whole-list Invalidate or RedrawWindow
also erased the header with the class background brush before repainting
it. On top of that, AdjustColumnWidths ran on every WM_SIZE and issued an
unconditional SetColumnWidth per column, and each call repaints the
header. The result was an occasional one-frame blink of the header row:
irregular, low frequency, and confined to the header because the item
area is double-buffered.

Both lists now carry WS_CLIPCHILDREN, RDW_ALLCHILDREN was dropped from the
redraw calls that only need the list body (that flag forces child
repaints even when they are clipped), and column widths are only set when
they actually change.

The header still needs its background erase, but only for the strip to
the right of the last column: AdjustColumnWidths reserves 20px there and
the header's own paint stops at the last column, so that strip is colored
by WM_ERASEBKGND alone. Skipping the erase entirely left it black after a
minimize/restore cycle, when the window contents are discarded. The
header subclass now fills just that strip with COLOR_3DFACE and leaves the
column area untouched, which keeps the flicker fix, and the needRefresh
branch of OnSize forces an erase-redraw of the header so the strip is
repainted on minimize/restore and maximize/normalize.

Verified with a standalone probe that mirrors the list setup for the
header erase counts, and by rebuilding the app and checking the
minimize/restore case reported against the first version of this change.

Co-Authored-By: deepseek-flash
2026-10-24 15:45:49 +02:00
yuanyuanxianganddeepseek-flash 434812f87d Fix: Show the instant-message popup on packed clients
Clients packaged as SC_AES/sRDI shellcode run the payload image as raw
shellcode inside the loader stub, so the instant-message manager was
handed the stub's module handle. The stub's resource section carries no
IDD_DIALOG, and Windows rejects resource APIs on manually mapped images,
so DialogBoxParamA failed (error 1812 on Windows 11) and the bottom-right
popup never appeared after the operator sent a message.

The popup now falls back to an embedded compiled dialog template
generated from the IDD_DIALOG block in Script.rc and verified
byte-for-byte against the resource in the built ghost.exe. When the
resource lookup fails, the dialog is created with
DialogBoxIndirectParamA instead. Deployments where the resource lookup
already works keep the original path unchanged.

The incoming text is now terminated at the copied length. The server
sends the message body without a trailing NUL, so a message that filled
the 1024-byte buffer left SetDlgItemText reading past the end.

The title is now set with SetWindowTextW before the window is shown.
DialogBoxParamA converts the template's UTF-16 caption through the
system ANSI code page, so the Chinese title turned into "???" on 1252
systems (verified locally with a caption containing a character outside
CP936). The title follows the UI language: Chinese systems keep the
Chinese title, everything else shows "Message". The message body still
uses the ANSI path, preserving the existing per-ACP semantics.

Co-Authored-By: deepseek-flash
2026-10-23 12:22:44 +02:00
yuanyuanxianganddeepseek-flash c99a1c375e Feature: Add MCP tools for remote chat with the client user
Add chat_open, chat_send, chat_wait and chat_close to the MCP tool set,
behind a new McpChat switch that defaults to off and is independent of
the read-only switch. The tools reuse the existing client chat link: the
main connection sends COMMAND_CHAT, the client opens a sub-connection
with TOKEN_CONN_AUTH and TOKEN_CHAT_START, the server answers with
COMMAND_NEXT_CHAT, and both directions then carry raw CP936 text.

Sessions are per host and held in shared pointers under their own mutex,
so a waiting chat_wait survives a close or a dropped sub-connection, and
chat_send is serialised per session. Text is converted strictly between
UTF-8 and CP936: invalid UTF-8, characters GBK cannot represent (emoji,
accented letters) and messages over the client's 4000-byte buffer are
rejected with -32602 instead of being mangled. A one-second settle delay
after the sub-connection binds keeps the first message from reaching the
client before its chat window exists.

The routing hooks run before the host-management hooks in MessageHandle
and clear the route in OfflineProc before the context leaves the list. A
five-second tombstone absorbs a late TOKEN_CHAT_START after a timeout, so
a failed chat_open does not pop the MFC chat dialog. Idle sessions are
swept on every tool call, and audit entries record the session id and
byte counts only, never message bodies.

The settings dialog gains the chat checkbox and the translated labels
for all three languages, and the strict UTF-8 to CP936 helpers move from
McpMachine.cpp to McpInternal so both tool families can share them.

Co-Authored-By: deepseek-flash
2026-10-23 11:19:21 +02:00
yuanyuanxianganddeepseek-flash fff7c67af6 Fix: Make the remote chat dialog Unicode and loader-independent
Clients packaged as SC_AES/sRDI shellcode run the payload image as raw
shellcode inside the loader stub, so the chat manager was handed the
stub's module handle. The stub's resource section only carries a
manifest, and Windows resource APIs reject manually mapped images
outright, so creating IDD_CHAT failed and the chat thread exited before
the window ever existed.

The chat window now falls back to an embedded compiled dialog template
that is byte-identical to the IDD_CHAT resource, and the title-bar icon
is rebuilt directly from the module's own resource directory instead of
LoadIcon, bypassing the loader on both paths. The PE walking code checks
every offset against SizeOfImage and the resource directory size, so a
malformed or truncated image returns NULL instead of faulting.
Deployments where the resource lookup already works keep the original
code path unchanged.

The dialog is now created and driven with the wide-character API. The
client is still an MBCS build, but an ANSI dialog renders text with the
system code page, so GBK chat text turned into mojibake on German and
other non-936 systems. Incoming text is converted CP936 to UTF-16 and
outgoing text strictly back to CP936; characters GBK cannot represent
(emoji, accented letters) are refused with a visible notice instead of
silently becoming '?'. Static labels follow the system UI language, and
IDD_CHAT now uses the scalable MS Shell Dlg face so font linking can
supply CJK glyphs.

The window is now positioned explicitly as well. DS_CENTER in the
template put it at the work area origin on the three-monitor host: the
centred position came out negative there and Windows clamps out-of-range
creation coordinates to that origin. It is centred in the work area of
the monitor under the cursor instead, falling back to SPI_GETWORKAREA.

Teardown no longer leaves a hidden window behind either. The dialog
thread blocked in GetMessageW and never saw m_bRun cleared, while the
destructor waited for that thread before sending the message that would
have destroyed the window, so a close command that never arrived (the
sub-connection already gone, or WaitSendIdle timing out before CancelIO)
leaked the window, the dialog thread and the manager loop. The
destructor now destroys the window first, the loop checks m_bRun before
blocking, and it destroys the window itself if it exits first.

Co-Authored-By: deepseek-flash
2026-10-23 11:19:21 +02:00
yuanyuanxianganddeepseek-flash 3ae6298746 Fix: Align macOS mouse coordinates with the captured display
The macOS client derived its logical screen size from [NSScreen mainScreen]
while it captured CGMainDisplayID. In clamshell mode with an external display
the former can still report the disabled built-in panel (1470x956) while the
captured frame is 1280x1024, so every injected point was scaled by
logical/encode and drifted linearly with the distance from the top left
corner, independently on each axis. Take the logical size from
CGDisplayBounds of the captured display instead, and report the same bounds
in the login resolution.

For hosts that still run the old client, the remote desktop dialog gains a
per-host mouse calibration in its system menu. The factors are stored by
client ID together with the reported resolution and the captured frame size,
so they stop applying once the client is upgraded or a different display is
captured, and come back automatically when the original display returns.
When no calibration has been saved the dialog pre-fills the factors from
frame/reported, but only for macOS clients, because the other clients derive
their conversion from the captured display itself and a mismatching report
there would be misleading.

Co-Authored-By: deepseek-flash
2026-10-22 11:33:39 +02:00
yuanyuanxianganddeepseek-flash 38cd207f5d Feature: Add host management and connection management MCP tools
Expose the online-list TLS column through list_online_hosts, search_hosts
and get_host_detail. The value comes from the flag the client reports at
login, so old clients always read false.

Add list_network_connections and kill_network_connection on top of the
connection manager sub-connection protocol. The kill path matches the
original 110-byte record instead of rebuilding addresses, supports a dry
run, refuses UDP/IPv6 targets, and verifies that the quadruple really
disappeared instead of assuming success.

Add a host_* family backed by the machine manager protocol: ten read
tools covering every tab of the host management dialog, and four
recoverable write tools for process freeze/thaw, window restore/hide/
maximize/minimize, service start/stop/pause/continue/restart, and
scheduled task run/stop. Every write re-reads the snapshot before sending
and re-checks afterwards, reporting -32009 for stale targets rather than
acting blindly. The family is gated by McpMachine, the risky subset by
McpMachineDangerous, and writes additionally require read-only mode to
be off.

Route managed sub-connections from MessageHandle and OfflineProc, keep
the single-in-flight rule by sharing the pending table with a request
kind, and move the shared JSON/lock/encoding helpers into McpInternal so
both tool families use one implementation. Settings dialog, design docs
and en_US/zh_TW/de_DE translations are updated accordingly.

Co-Authored-By: deepseek-flash
2026-10-21 20:01:41 +02:00
yuanyuanxianganddeepseek-flash 6c8336b497 Fix: Repair task actions and harden machine management
Scheduled task actions never worked end to end: the server built task
packets with Unicode-style lengths in a MultiByte build, the client had
no dispatch for the run/stop/delete/create commands, and the directory
column was derived by replacing every occurrence of the task name, which
misplaced tasks whose name also appeared in a parent folder. Packets are
now assembled with narrow strings, the four commands are routed to
RunOrStopTask/DelTask/CreateTask, and the folder is taken from the task
path suffix only. The task list reply is trimmed to its real length
instead of sending the whole 32 KB scratch buffer.

On the client side, thawing a process resumed a single thread, the
inject output path was copied from a narrow string using a wide-character
length, and an empty window list dereferenced a NULL buffer. The service
list leaked its enumeration block and one service handle per skipped
entry, and the description was copied without a bound. Service start and
stop now validate every handle, initialize the status structure, and stop
synchronously before the start that follows a restart request, which
previously always failed because the service was still in STOP_PENDING.
Deleting a process used to test only the low byte of the PID and leaked
the process handle on early exits, and a failed path conversion kept the
previous process image name. The IE history timestamp wrote minutes and
seconds in the wrong order, the favorites reader queried and closed an
uninitialized registry key, software enumeration never closed its subkeys,
and the task scheduler objects were not released after use.

The network state list now frees the module, snapshot, and extended
tables on every exit path, uses HeapFree for tables allocated on the
process heap, and no longer calls an export that may be missing. Growth
failures everywhere keep the original buffer instead of overwriting the
pointer, the hosts reader rejects an invalid file size, and the COM task
walk releases definitions and folders.

Co-Authored-By: deepseek-flash
2026-10-20 21:48:13 +02:00
yuanyuanxianganddeepseek-flash c208b7368e Fix: Format net-state addresses as narrow strings on the client
The client is a MultiByte build, so the destination buffers are char[]
and _T("%s:%u") expands to an ANSI format that expects a char pointer.
The code nevertheless converted inet_ntoa() output to WCHAR* first, and
the ANSI %s stopped at the zero byte that follows the first wide
character. Every address therefore collapsed to its leading digit, so
192.168.0.55:443 was shown as 1 and 0.0.0.0:80 as 0 in the local and
remote address columns of the network connections tab.

Write the address and port straight into the char buffers with
sprintf_s in all four enumeration paths (legacy and Vista APIs, TCP and
UDP), and drop the now unused char2wchar_t helper.

Co-Authored-By: deepseek-flash
2026-10-20 21:24:47 +02:00
yuanyuanxianganddeepseek-flash 15a50db0a7 Fix: Keep IPv4 address bytes in network order for connection list
iphlpapi stores the address in network byte order inside the memory of
the DWORD, it is not a host-order integer. For 192.168.0.55 the DWORD
value on x86 is 0x3700A8C0 while its bytes are C0 A8 00 37, so shifting
the value by 24/16/8/0 produced 37 00 A8 C0 and the dialog rendered
"55.0.168.192" for both the local and remote address.

Copy the DWORD with memcpy instead, which preserves the memory layout
that inet_ntop and SetTcpEntry both expect. GetAddr4 is changed the
same way, otherwise a forced disconnect would rebuild a wrong address
and miss the target connection.

Co-Authored-By: deepseek-flash
2026-10-20 21:15:45 +02:00
yuanyuanxianganddeepseek-flash ca35e6e26f Feature: Add menu icons for the advanced and disclaimer entries
Add four 16x16 bitmaps and wire them through the existing m_bmOnline
table. The three entries under the "Advanced" menu had no icon at all,
and the disclaimer entry shared the help question mark with "what is
this", so the two were indistinguishable.

- desktop quality levels: a monitor with three ascending level bars in
  the screen
- screen preview levels: a thumbnail card with a sun, a folded corner
  and layered hills
- file transfer speed: a half-circle gauge with a red needle
- disclaimer: a document with a folded corner and an amber exclamation
  badge, so it no longer looks like the help entry

Grow the bitmap array to 75 entries and reserve resource IDs 412-415.

Co-Authored-By: deepseek-flash
2026-10-20 21:13:05 +02:00
yuanyuanxiang 679136e73e Release v1.4.1 v1.4.1 2026-10-20 15:00:35 +02:00
yuanyuanxiang b637c94e24 Feature: Allow user to select an installation location for client 2026-10-20 13:12:16 +02:00
yuanyuanxianganddeepseek-flash f76cd79bb0 Fix: Renew expired licenses from today and report the actual expiry
Preset renewal stored its target date as the old expiry plus the entered
days, while the authorization actually issued to the client is always
today plus a day count. For a license that had already expired, the
preset date was therefore in the past: SendPendingRenewal clamped the
day count to one, the client received a one-day license starting today,
but the renewal tip and the logs still printed the stale preset date.
The result was a message such as "renewed until 2026-05-30" while the
license really ran until tomorrow.

Presetting a renewal now bases the new date on today when the license
has already expired, and on the original expiry date otherwise, which
matches the one-day-per-day extension admins expect for live licenses.
The renewal dialog and the success prompt state which base was used, so
the computed date is never ambiguous. Renewal tips and both logging
paths (heartbeat-driven SendPendingRenewal and client-requested
GenerateRenewalInfo) now print the date that was actually issued, which
also corrects legacy preset records whose stored date has already
passed.

Co-Authored-By: deepseek-flash
2026-10-19 15:15:49 +02:00
yuanyuanxianganddeepseek-flash 39c8daa9b0 Fix: Keep the audit log open across WebSocket reconnects
Hiding the browser tab while the audit log was open closed the socket,
because the visibility handler treats only the remote screen, terminal
and wall pages as streaming pages. Returning to the tab reconnected the
socket, and the onopen restore path took its catch-all branch, which
navigated to the device list. The audit log therefore vanished whenever
the browser was minimized.

The catch-all branch now leaves the active page alone when it is the
audit log, and only refreshes the device list in the background. Every
other page keeps the previous behaviour: the login page advances with a
cached token, and the terminal page falls back to the device list
because its session died with the socket. Audit results already rendered
stay on screen, so the admin can keep reading without re-querying.

Co-Authored-By: deepseek-flash
2026-10-19 10:39:36 +02:00
yuanyuanxianganddeepseek-flash cd4f3675fd Improve: Replace native browser prompts with themed in-app dialogs
Native alert() and confirm() render their buttons in the browser or OS
locale, so on a German system prompts such as the Clear Screen Wall
confirmation showed German labels that disagreed with the rest of the
web UI. Both are now served by a single themed modal that reuses the
logout confirmation styling: an info variant with one OK button for
notices, and a danger variant with Cancel/OK for destructive actions.

The alert helper is fire-and-forget, while the confirm helper returns a
Promise, so the two call sites that need an answer (clearWall and
deleteUser) are now async. Dialog title and message are written with
textContent so device names, user names and server error strings can
never be interpreted as markup. A pending dialog is resolved as
cancelled when another one supersedes it, keeping callers from hanging,
and clicking the backdrop or pressing Escape closes the dialog. Remote
keyboard forwarding now ignores keys while a dialog is open.

Co-Authored-By: deepseek-flash
2026-10-19 10:27:09 +02:00
yuanyuanxianganddeepseek-flash bbb3d8c2fa Fix: Recover proxied client IPs and fit audit filters on phones
The MFC web server now resolves the real client address from the
WebSocket upgrade request when the TCP peer is loopback, so audit records
and login rate limiting stop reporting the reverse proxy's 127.0.0.1.
X-Forwarded-For is preferred over X-Real-IP because its last hop is the
address the local proxy appended; a client-supplied header list cannot
forge it. Forwarded headers are ignored for non-loopback peers so a
client connecting directly over the internet cannot spoof its identity
or rotate addresses to bypass throttling. FRP deployments can keep using
the existing Proxy Protocol v2 support instead.

Collapse the audit log search conditions behind a toolbar toggle that
starts closed and switches to an accent-colored "Hide filters" state
while the panel is open. On portrait phones the panel uses one control
per row, and From/To move their border and padding onto a wrapper so the
iOS WebKit datetime-local width miscalculation cannot overflow the
viewport.

Co-Authored-By: deepseek-flash
2026-10-19 10:05:58 +02:00
yuanyuanxianganddeepseek-flash ca671d6453 Feature: In-memory web audit log for the MFC server
Add a process-local security audit trail to the Windows server's web
console, mirroring the Go server's event names and reply shape. The ring
keeps the most recent 1000 events since process start and is never
persisted.

- New query_audit WebSocket command, admin-only, with time/event/actor/
  IP/device/keyword/warn-only filters and pagination; the reply is the
  audit_result payload the existing Audit Log page already understands.
  The challenge advertises caps.auditLog so browsers enable the button.
- Record logins (success, failure, throttling, salt probes), WebSocket
  connect/close, screen and terminal session start/stop/denials,
  clipboard transfers (byte counts only), RDP resets, and admin user
  mutations.
- Repeated failed logins and username probes are de-duplicated per
  connection so scanners cannot flood the ring.
- Audit writes never hold m_ClientsMutex: disconnect paths snapshot the
  client identity before the map entry is erased, and offline-device
  stops are audited after the clients lock is released.

Co-Authored-By: deepseek-flash
2026-10-18 19:16:17 +02:00
yuanyuanxianganddeepseek-flash a522424491 Feature: Security audit logging with admin web query page
Add a dedicated security audit trail to the Go server. Login attempts,
authorization denials, WebSocket lifecycle, remote screen and terminal
sessions, clipboard operations, device authentication and admin mutations
now emit stable JSON-line events (audit=true, event=<name>) to a separate
logs/audit.log, mirrored to server.log. The path is configurable through
YAMA_AUDIT_LOG and the separate file can be switched off. Records never
contain passcodes, password hashes, tokens or clipboard contents, and
untrusted string fields are stripped of control characters and truncated
so they cannot forge log lines.

Expose the trail to administrators through a query_audit WebSocket command
and an Audit Log page in the web UI. The page filters by time range, event
(exact or prefix), actor, IP, device id, keyword and warning level, pages
newest-first, and stays hidden unless the server advertises the auditLog
capability, so older C++ servers degrade cleanly. Each query scans at most
the newest 32 MB of the current file to bound latency, records itself as
admin.audit.query, and tolerates torn or non-audit lines.

Add unit tests for event emission and redaction, query filtering, paging,
malformed lines, missing or disabled audit files, and handler
authorization.

Co-Authored-By: deepseek-flash
2026-10-18 18:44:17 +02:00
yuanyuanxianganddeepseek-flash b1ddec1b8a Feature: Offline device history with delete and remote uninstall
Persist every device that has ever logged in to the Go server in a small
JSON store (devices.json, overridable with YAMA_DEVICES_FILE and capped by
YAMA_DEVICES_MAX, default 1000 newest). The store follows the users.json
convention: atomic temp-file write with fsync and rename, a 500 ms debounce
for bursts of reconnects, first_seen preserved across logins, and pruning
that evicts offline records before devices that are still connected.
Devices connected at shutdown are stamped offline before the final flush so
last_seen stays accurate across restarts.

The server advertises an offlineDevices capability and device_list now
appends historical devices that are not online, marked with online:false and
last_seen. The web UI shows an Offline checkbox after Total/Showing (state
kept in localStorage), renders offline cards dimmed and dashed, and always
lists them in the screen-wall sidebar. Older servers without the capability
keep the online-only list.

Grid and List cards gain a delete button after the terminal button, admin
only, behind a confirmation dialog. Deleting an offline device removes its
history record; deleting an online device first sends the single-byte
TOKEN_UNINSTALL command (matching the MFC OnOnlineUninstall flow) and then
removes the record too, so the device does not come back as a dead offline
entry. The agent's own disconnect then runs the existing cleanup path:
screen and terminal sub-connections are closed, the hub entry is removed,
and browsers receive device_offline to release their watch sets, wall
sessions, and stream references. Wall mode exposes no delete action.

Tests cover history persistence/pruning/recovery, offline ordering, the
device_list merge, and all three delete outcomes (offline removal, online
uninstall with a single 0x3F byte, and viewer rejection).

Co-Authored-By: deepseek-flash
2026-10-18 17:54:30 +02:00
yuanyuanxianganddeepseek-flash 1922f87dd2 Feature: Multi-device screen wall on the Go server
Bring the Go web backend up to parity with the MFC server's screen wall.
A browser tab can now stream several devices over one WebSocket: the
single `watching` field becomes a per-connection watch set guarded by the
hub mutex, capped at 32 devices per socket. The challenge advertises
`caps.multiWatch` and `caps.keyframeRequest`, binary frames stay keyed by
the low 32 bits of the device ID, and connect/disconnect replies echo the
device id and request id so the wall can route concurrent responses.

Input commands (mouse, key, clipboard, rdp_reset) resolve their target
from the watch set: an explicit id must be a current subscription, and an
absent id is accepted only while exactly one device is watched. Legacy
frontends that do not send `multiWatch` keep replace-all semantics, so a
repeated device switch cannot grow the set without bound. Offline
devices are removed from every watch set, and teardown is computed from a
snapshot taken outside the hub lock to avoid re-entrant locking.

Add the `keyframe` command: it replays the cached IDR, then asks the
device to emit a fresh one, rate-limited to one request per device per
second. This exposed a Go-only corruption bug: the client answers the
request with TOKEN_KEYFRAME (134), which the dispatcher treated as a
no-op. That token only appears on forced IDRs because the client's GOP is
effectively infinite, so the dropped IDR left the browser decoding
P-frames against a reference chain it never received, producing
persistent garbling. Relay it as a keyframe instead. Also drop the
cached IDR when the resolution changes, mirroring the C++ server, so a
late joiner cannot receive an old-geometry keyframe.

Add tests for the watch-set transitions and for relaying TOKEN_KEYFRAME.

Co-Authored-By: deepseek-flash
2026-10-18 11:51:28 +02:00
yuanyuanxianganddeepseek-flash 8eab26c1f6 Feature: Web screen wall for multi-device live monitoring
Add a third view to the web UI, the screen wall, which shows several
devices at once in one tab with 1x1 / 2x2 / 3x3 / 4x4 / 5x5 layouts and a
device sidebar on the left. Tiles are monitoring-only; clicking one
enlarges that device into the existing single-screen page for control, and
Back returns to the wall. The same device can be added several times: all
tiles of one device share a single decoder and a single stream.

The wall decodes at most 9 streams on desktop and 4 on touch devices.
Tiles beyond the budget keep receiving frames but have their decoder
closed and show the last frame plus a Paused badge; they are promoted
automatically when a live tile goes away. Subscriptions are reference
counted on the client (streams map with owner sets), so a stream is only
connected on the 0 -> 1 transition and disconnected on 1 -> 0, and the
wall and the single-screen page can share one device without tearing the
stream down.

Server side, WebClient now holds a set of watched devices instead of a
single id. A new multiWatch command flag selects set semantics, while
clients without it keep the old replace-all behaviour, so an old frontend
against the new server is unchanged. connect and disconnect responses echo
id and req so the frontend can route them, input commands carry an id and
are resolved against the watch set (dropped when the set has several
devices and no id), and the per-client watch set is capped at 32.

For fast recovery after a pause or when joining late, the server caches
each device's raw IDR payload and replays it on connect and on a new
keyframe command, then asks the client to force a new IDR. The client gets
COMMAND_SCREEN_KEYFRAME_REQ = 169 and an atomic request flag that is only
cleared after an IDR actually came out of the encoder, so a failed capture
or EAGAIN does not lose the request. The frontend retries the keyframe
request up to three times; an old client that ignores the command simply
recovers on the next natural GOP.

Also fix the keyframe cache double wrapping: BroadcastH264Frame used to
cache the full packet header and HandleConnect wrapped it again. The cache
now stores data + 9, len - 9 and every sender wraps it through
BuildFramePacket, and the cache is cleared on cold start and on resolution
change. StopRemoteDesktop is always called outside m_ClientsMutex, with
the ids collected under the lock first.

Co-Authored-By: deepseek-flash
2026-10-18 11:03:17 +02:00
yuanyuanxianganddeepseek-v4-pro 04f4eb9947 Fix: share web login session across browser tabs
The login token and role were stored in sessionStorage, which is
isolated per tab, so opening a second tab forced a fresh password
login. Switch every token/role read and write to localStorage so all
tabs on the same origin share the session and a new tab auto-resumes
it on load. Expiry (device_list ok:false) and explicit logout still
clear it as before.

Co-Authored-By: deepseek-v4-pro
2026-10-17 22:44:50 +02:00
yuanyuanxianganddeepseek-v4-pro 5cea1167be Feature: Web remote desktop phone IME input box ("I")
Add an "I" button to the mobile shortcut bar that opens a chat-style
input box pinned above the virtual keyboard. Text is delivered to the
remote through the existing clipboard bridge (clipboard_set + synthetic
Ctrl+V); an empty box turns Enter/Backspace into remote Enter/Backspace
so the phone can submit and edit text in the focused window. The box
soft-wraps and auto-grows up to four lines.

The box is a <textarea>, so the desktop key-forwarding handlers now skip
TEXTAREA targets as well, which stops an empty-box Backspace from being
forwarded twice (once by imeBackspace, once by the document handler).

Co-Authored-By: deepseek-v4-pro
2026-10-17 22:06:46 +02:00
yuanyuanxianganddeepseek-v4-pro 0c04f7516b Feature: Web remote desktop bidirectional text clipboard sync
Add keyboard-shortcut (Ctrl+C / Ctrl+X / Ctrl+V) text clipboard transfer
between the browser and the remote desktop, reusing the clipboard protocol
that already exists in the native viewer (COMMAND_SCREEN_GET_CLIPBOARD=24,
COMMAND_SCREEN_SET_CLIPBOARD=25, TOKEN_CLIPBOARD_TEXT=118) so the client
needs no change.

Local -> remote: pressing Ctrl+V reads the browser clipboard, pushes it to
the remote clipboard (UTF-8 -> GBK, matching the client's CF_TEXT/ANSI
handling) and then synthesizes a remote Ctrl+V so the pasted text is the
newly delivered one.

Remote -> local: Ctrl+C or Ctrl+X is forwarded to the remote as usual and,
after a short delay, the remote clipboard is pulled back and written to the
browser clipboard for a later local Ctrl+V.

Both the MFC and Go servers get the same three clipboard signaling paths
(clipboard_set, clipboard_get, clipboard_text) so the shared single-page
frontend behaves identically on either backend.

Co-Authored-By: deepseek-v4-pro
2026-10-17 19:52:38 +02:00
yuanyuanxianganddeepseek-v4-pro e6b4fe3a85 Fix: reissue client_id on clone collision and harden V1 file-transfer command
撞 ID 的克隆机(同镜像 MachineGuid 相同导致 client_id 相同)此前会被服务端暂存为
替补、永远无法转正,从而不显示在主机列表。现在服务端检测到「client_id 相同但主机名
不同」时,主动下发 COMMAND_REGEN_CLIENT_ID,客户端在旧 ID 基础上掺随机 UUID 重算后
重连,以新 ID 正常上线;触发条件仅看主机名,排除 IP 漂移与纯用户名变化,避免误伤
正常重连的机器。

同时加固 V1 服务端→客户端文件传输:COMMAND_GET_FILE 指令的一次性 md5 令牌绑定登记
时的客户端源 IP(PutCmd/PopCmd 均带 peerIP),防止异常客户端冒用;并对指令包增加边界
校验(len 与 NUL 结尾),杜绝无 NUL 包导致的越界读。

Co-Authored-By: deepseek-v4-pro
2026-10-17 09:29:33 +02:00