80c7d1ed53ecc576d4a70e6e433f1a5ac31bc0d8
100
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
80c7d1ed53 |
Fix(go): decode Windows host names with the system code page
The web console showed Chinese computer names as a run of U+FFFD. ParseLoginInfo sent every string field through the UTF-8 decoder once a client advertised CLIENT_CAP_UTF8, but szPCName and the OS string are not covered by that bit: Windows fills them from gethostname(), a narrow API, so they carry CP936/GBK even on modern clients. The MFC server decodes these two fields with CP_ACP (HostJson.cpp::AnsiToUtf8), which is why the Windows server and its web view were never affected. A new DecodeLoginAnsiField picks by client type instead of capability: LNX/MAC/macOS/APK are UTF-8 (they build the field from a UTF-8 host name or, for Android, the device model), everything else is GBK. "macOS" is what pre-1.0 macOS builds report; GetClientType sends "MAC" today and the MFC WebService still accepts both. ASCII host names come out byte-identical either way, and legacy clients keep the name they had. Reserved keeps its capability-based decoding, so UTF-8 file paths and locations are untouched; OS strings are ASCII in practice. The one case that gets worse is a Windows machine running the "Beta: Use Unicode UTF-8" locale, which will now mojibake there. Sniffing UTF-8 to cover it would misfire on real GBK names -- 930 of 6763 GBK hanzi pass as a UTF-8 two-byte sequence, roughly 2% of two-character names -- so the deterministic rule wins and the trade is written next to the function. Tests cover GBK names from capable and legacy clients, UTF-8 names from Linux, Android and legacy macOS, and Reserved still honoring the bit. Co-Authored-By: deepseek-flash |
||
|
|
9fadb58c76 |
Fix(client): rotate HELL header encoding across reconnects
A Release client drew one of the twelve HELL header encodings in the constructor and kept it for life. The Go fallback server latches a type from the first packet and only decodes None..V6, so every client that drew V7..V10 could never log in to it — a third of them, at random, for good. The main connection now advances to the next type when it reconnects after a connection that was never login-acked (CMD_MASTERSETTING), and republishes the accepted type into CONNECT_ADDRESS::szFuture. A type that did log in is kept, so a healthy client no longer churns through values the fallback would reject. Sub-connections, including one-shot ones (file/process/screen), inherit the published value at construction and on every reconnect instead of rolling their own dice. Debug keeps its None..V6-only range; the initial Release type now comes from random_device rather than time() % N, which handed a whole batch started in the same second the same value. The slot sits at szFuture+16, after LOCAL_TEST_CLIENT_MAGIC, guarded by static_asserts; it is memory-only and never persisted or sent. Swapping the encoder is a single atomic function-pointer store, so the send and receive threads see either the old or the new encoder and never a dropped object. Co-Authored-By: deepseek-flash |
||
|
|
a818ace83c |
Fix(mcp): declare conditional tool arguments and surface probe headers
Several tools enforced argument requirements that existed only in prose, so a model had to send a bad call to learn them. A new AppendConditionalRequired helper emits allOf/if/then entries, and the schemas now say: - get_screenshot: mode=region needs width and height; mode=window needs hwnd. monitor keeps its default of 0. - remote_keyboard: action=type needs text; key_down/key_up/key_press need key. - remote_mouse: action=drag needs x2 and y2. - terminal_exec: command or session_id, at least one (anyOf), matching the handler's -32602 when both are missing. http_probe put the response headers only in structuredContent, which a client that reads the text block never sees; Location, Set-Cookie and Content-Type are exactly what a redirect or auth decision needs. The text block now starts with a headers section, bounded to 4096 bytes and 1200 bytes per line, backing off to a UTF-8 boundary when a line has to be cut. The full set stays in structuredContent.headers. mcp/tools.json mirrors the schemas and tools_minimal.json is regenerated. Verified against a fresh Debug build: verify_tools --live reports 49 tools identical. Co-Authored-By: deepseek-flash |
||
|
|
31883edc09 |
Fix(mcp): align Go tool text and list_files batch with Win32
The Go minimal server sent models after tools it does not have: read_file pointed at download_file and search_file, both absent from its nine-tool set, and the 2 MiB message named a download path that does not exist. It now names list_files, terminal_exec and the Windows controller server. Terminal errors lost the one piece of state the model needs to recover. A busy terminal now says the holder is the web console (no MCP session to close), and a cancelled exec carries the session_id to poll or release. list_files ids[] was advertised in the shared schema but answered -32005. It now implements the Win32 batch contract: 50 ids, ids past the 50 s deadline marked skipped rather than failed, results in input order. The deadline only gates starting a host; one already running finishes on its own timeout, so its result is never mislabelled as a client abort. Each entry takes the per-device lock the single-host path gets, so a host busy with another tool fails that entry with -32003 instead of running beside it. An empty ids array is a valid empty batch, as on Win32. The initialize instructions now describe only what this build implements. Co-Authored-By: deepseek-flash |
||
|
|
61b9031269 |
Fix(mcp): bound host_inspect, precheck remote_open, name the busy holder
Three smaller contract fixes that remove ways for an agent call to hang or fail without an explanation: - host_inspect with several aspects opens one sub-connection per aspect (5s ready + 12s list each), so all ten could run ~170s and outlive the caller's HTTP timeout. After 60s no new aspect is started; the running one finishes on its own timeout and the skipped ones land in errors.<aspect> with code -32001 and a "skipped:" message, so the model can retry with fewer aspects. - remote_open checked nothing before opening the hidden screen session. A Linux host that declares capability bits but not CLIENT_CAP_SCREEN_PREVIEW has no X11 display, so capture and injection cannot work: return -32005 immediately instead of waiting out timeout_ms and then reporting a sub-connection timeout. Android is deliberately excluded -- its SCREEN_PREVIEW bit tracks accessibility (API 30+ takeScreenshot for get_screenshot), while remote control uses MediaProjection capture and dispatchGesture, which can work without it. Old hosts with empty caps are still let through. - The -32003 busy errors in remote_open now append the DescribeBusy suffix (tool, elapsed), matching the other busy paths. tools.json descriptions are kept byte-identical to the C++ literals. Debug build green; check_platform_table, gen_go_tools --check and go test ./... pass. Co-Authored-By: deepseek-flash |
||
|
|
d49ebe521d |
Docs(mcp): correct claims in the server instructions agents rely on
The initialize.instructions text is the only guide a model gets (it cannot read docs/), and several statements disagreed with the code: - get_keylog was described as always visible; it is gated by McpKeylog and hidden when the switch is off. - Dangerous machine actions were not mentioned: freeze/thaw and stop/restart stay in tools/list but need McpMachineDangerous and return -32006 at call time. - -32006 was described as policy/admin-only; MFC also returns it when an old client lacks CLIENT_CAP_V2. The Go server returns -32005 for that case, so its own instructions now say so. - -32001 advice assumed every failure is a timeout; it also covers cancellations, http_probe parse failures and unconfirmed writes. - "Unsupported combos always return -32005 immediately" ignored paths that surface as -32001 once a sub-connection is involved. - Linux matrix listed all host_* as unsupported, but host_set_remark and host_set_watch_level only touch server-local data. - local_dir / local_path are paths on the controller, not the user's box. Also align the error table and platform distribution in the docs, and note that hidden fallback aliases remain callable. Debug build green; go test, check_platform_table and gen_go_tools --check pass. Co-Authored-By: deepseek-flash |
||
|
|
292c3191dc |
Fix(mcp): make declared schemas match what the handlers return
Several tool contracts disagreed with the runtime shape, which forces an
agent to guess instead of following outputSchema:
- get_server_status returned {"status": {...}} while outputSchema has the
fields at top level; return the status object directly.
- get_screenshot description claimed structuredContent.image carries the
base64 data; it only carries mimeType/width/height/bytes, the bytes are
in the content image block.
- host_control_service accepted service_name silently, but not in schema;
document the alias and add anyOf [{required:[name]},{required:[service_name]}]
so a call missing both fails at validation, not at execution.
- kill_network_connection dry_run invented dryRun/connection fields absent
from ActionOutputSchema; use the shared BuildDryRunResult shape.
- search_file outputSchema left files.items untyped; declare
path/name/modified/dir/size and the paging fields it already emits.
- chat_* id hints still named the removed list_online_hosts/search_hosts.
tools.json hunks keep the live-dump key order (alphabetical inside schemas),
tools_minimal.json is regenerated, and mcp_smoke.ps1 now reads the flat
structuredContent. Debug build green; check_platform_table, gen_go_tools
--check and go test ./... pass.
Co-Authored-By: deepseek-flash
|
||
|
|
5e012019ba |
Fix(mcp): list the whole directory before paging list_files
list_files stopped parsing at 500 entries, so a larger directory reported total=500 with hasMore=false and offsets past 500 returned nothing: the model was told a false limit and could not reach the tail. Parse the full TOKEN_FILE_LIST payload (100000 cap only to bound a pathological directory), page over it, and report truncated=true plus a summary note when the cap hits. Only an empty path now means list drives. Windows "." "/" "\" are normalized to empty in BuildListFiles, while Linux/macOS "/" is a real root directory and is listed; OnDriveList no longer keeps its own copy of the magic-path rule. The file-manager channel carries GBK both ways (Windows FindFirstFileA; common/FileManager.h runs gbkToUtf8 on incoming paths, utf8ToGbk on outgoing names). The old CP_UTF8 choice for LNX/MAC decoded GBK names wrongly and sent UTF-8 paths to a client that treats them as GBK. Paths now go out as GBK, or as raw UTF-8 when GBK cannot represent them (the client's iconv then passes the bytes through). Names decode GBK-first, UTF-8 on failure: UTF-8-first misreads ~18% of common hanzi whose GBK bytes are also valid UTF-8. Go's server gets the same contract: 100000 cap, truncated in structuredContent, and the cap check after a real record so an exact-cap listing with trailing padding is not called truncated. tools_minimal.json is regenerated; the Go truncation test and the design doc are updated. Debug server builds; check_platform_table, gen_go_tools --check and go test ./... pass. The Release instance was not rebuilt or restarted. Co-Authored-By: deepseek-flash |
||
|
|
42dd70fe20 |
Fix(mcp): make terminal busy and cancel semantics usable by an agent
exec_command answered -32003 "device busy" with no way forward: the message named neither the occupying session nor how to free it, and mcp_cancel_session could only target in-flight calls, so a persistent terminal left behind by an earlier session blocked the host until its idle timer expired. An agent had no route back to a working state. Build the busy text from the live session table: terminal sessions now report parent session_id, idle and elapsed seconds, and point at terminal_exec (or terminal_close with id and session_id) when a persistent session holds the host, or at mcp_cancel_session(request_id) when the occupier is a running exec_command. exec_command sweeps idle terminals before it begins a pending wait, so a session abandoned after 300s does not require a terminal_* call first; SweepIdleTerminals now requires started so it cannot reclaim a session that is still in BeginTermPending and hand the device to a second caller. Cancel becomes addressable and honest. id=0 is rejected with -32602 instead of being treated as "all hosts", the calling request is excluded from matched and released (previously the poll saw itself and released was never true), rows carry cancellable, and when nothing was cancelled the reply lists what matched and which close tool takes it. Instructions, tool description, inputSchema (anyOf request_id/id/session_id) and the released description now agree: kind=call only, persistent sessions close by id+session_id, pending and file_transfer entries are released by cancelling the call that owns them. tools.json is regenerated for the schema and description changes. Debug server builds, check_platform_table.py and gen_go_tools.py --check pass; the Release instance was not rebuilt or restarted. Co-Authored-By: deepseek-flash |
||
|
|
3d18b2119a |
Fix(mcp): put listing rows and host ids into text blocks
MCP clients that surface only content[].text saw just count summaries from list_hosts and get_audit_log; the 64-bit host id lived only in structuredContent. Without the id, read_file, get_host_detail and terminal_exec cannot be addressed, so the tools were unusable from those clients. Append a tab-separated table after the summary for every list-shaped local tool: list_hosts (id first, then name/ip/group/os/online/clientType/ last_seen), get_audit_log (time/type/msg), list_files (drives and directory entries) and get_host_detail (compact host JSON; id/ok/detail rows for a batch call). Only the returned page is rendered, cells are flattened to one line, and the truncation note stays on its own line before the table. structuredContent is unchanged and remains the authoritative copy. Tests cover row contents, paging, escaping and truncation ordering; a live run against a Debug client confirmed the id is now visible in text. The MFC server needs no equivalent change: BuildResult already appends the full structuredContent as a second text item, so text-only clients there already receive host ids. Go's envelope emits a single text item, which is why the rows go into it. Co-Authored-By: deepseek-flash |
||
|
|
70556391dd |
Docs(mcp): record the Go MCP overall acceptance
Run the section 5 checklist end to end against the debug Go server and a Windows debug ghost: nine tools called, tools/list at 22578 B, twenty consecutive terminal_exec calls with zero failures, read_file SHA-256 matched, 30 audit entries with device/tool/code/ms, and --subset passing in both 9-tool and readonly 7-tool modes. Race tests stay clean. Two checklist items get corrected rather than ticked: hub did change (SendToConn in M6 and the terminal lease generation in M4a, both needed and unit tested), and the MFC regression has no target because the whole milestone range touches no C++ file. Note the running Release binary is an older build reporting the old tool names; it was left alone. Co-Authored-By: deepseek-flash |
||
|
|
d4f10db1f2 |
Feature(Go): verify_tools --subset and MCP deployment docs
Add a third mode to verify_tools.py that validates the Go server end to end: it fetches /mcp tools/list and requires the name set to equal the nine implemented tools exactly (seven in readonly mode), compares description / inputSchema / outputSchema field by field against mcp/tools.json, and also checks the published order. Unlike --live, extra or missing tools are failures, not notes. The field-comparison loop is factored into report_field_diffs so --offline / --live and --subset share one comparison, diff printer and FIELDS tuple. Document and deploy the endpoint: the systemd env example gains YAMA_MCP_TOKEN / READONLY / TERM_IDLE / MAX_CONCURRENCY / READ_MAX, the design doc moves to implemented and its section 10 now matches the code (embedded tools_minimal.json, the three packet dispatch groups). The tools README explains gen_go_tools.py --check and --subset. Verified against a freshly built debug Go server on 16543/18090: read-write mode passes with 9 tools, YAMA_MCP_READONLY=1 passes with 7, and both mismatch directions (extra tools, missing tools) fail with exit 1. gen_go_tools.py --check stays clean; no Go code changed. Co-Authored-By: deepseek-flash |
||
|
|
9ce1a58bc3 |
Feature(Go): read_file over the V2 stream receiver
read_file reuses the list_files handshake: COMMAND_LIST_DRIVE opens the file-manager sub-conn, which then gets [CMD_DOWN_FILES_V2][targetDir\0][path\0][\0] and streams COMMAND_SEND_FILE_V2 chunks plus a COMMAND_FILE_COMPLETE_V2 carrying the whole-file SHA-256. Windows clients open a fresh authenticated sub-conn for the chunks; POSIX clients stream on the file-manager conn itself, so that conn is retired when the call ends rather than right after the request. TOKEN_DOWNLOAD_ERROR on the file-manager conn maps to -32009 / -32010 / -32000 like the Win32 server. Bytes land only in a per-call os.MkdirTemp dir; the client name is checked against the target dir (separator-normalised, path.Clean, so ..\.., absolute, UNC and mixed separators are refused) as defence-in-depth, never used as a path. First chunk enforces the size gate (ReadMax) and rejects multi-file batches, so an expanded directory fails with -32602 instead of returning its first file. Chunks from a sub-conn opened for an earlier call are dropped by connection ID, data sub-conns are closed when the call ends, and a closed sub-conn fails the call fast instead of waiting for the stall watchdog. Text windowing, encoding detection (BOM / UTF-8 / GBK / explicit / latin1) and EOL handling mirror McpServer.cpp. Verified with the Debug ghost on Windows 11 and the WSL Ubuntu ghost: .env text plus newline is byte-identical, sha256 equals SHA-256 over the file, windows/GBK/empty/ max_bytes/directory/size-gate/missing-path/POSIX-path cases all pass. Co-Authored-By: deepseek-flash |
||
|
|
d7accf1d30 |
Feature(Go): list_files over the file-manager sub-connection
The MCP server could not browse a device's file system. It now sends COMMAND_LIST_DRIVE on the main connection, waits for the client to open its file-manager sub-connection and report drives, then reuses that same sub-connection for COMMAND_LIST_FILES with the directory path. Replies are TOKEN_DRIVE_LIST, TOKEN_FILE_LIST or TOKEN_FILE_LIST_ERROR, decoded from the same GBK the C++ client writes on every platform. An empty or missing path returns the drive list, matching the published tool description. Any other path, including /, lists one level of that directory; the Win32 server folds / into the drive list, but doing so would make a POSIX root listing unreachable. Entries carry name, isDir, size and an mtime converted from FILETIME, and the 500-entry cap matches the served contract and the Win32 parser; a truncated listing says so in the summary. The reply is paged with the usual limit/offset window. Errors are translated like the Win32 server: win32 5 is a permission error, 2 and 3 are not-found, anything else is internal. Legacy clients stay silent instead of reporting an error, which surfaces as a timeout with an explanation. The sub-connection is a resource the client allocates per call, so one deferred cancel is the single retirement point: it reports the sub-conn it saw and that connection is closed on every exit path, including a call that gives up while the drive list is already queued. Packets that arrive after the call returned are treated as orphans and retired, and only the connection that answered the drive-list phase may answer the directory request. Also add a uniqueness test over the command and token byte constants, and SendToConn so sub-connections are written through the hub's framing path instead of a raw conn write. Co-Authored-By: deepseek-flash |
||
|
|
5227d4d78e |
Feature(Go): get_screenshot over the main-connection preview RPC
COMMAND_SCREEN_PREVIEW_REQ (247) / TOKEN_SCREEN_PREVIEW_RSP (248) is a request/reply pair on the device's main connection: the client captures, scales and encodes the frame itself, so no sub-connection is opened and no screen-session slot is taken. get_screenshot can therefore run while a human is watching the same machine. The server keeps one pending request per device in a small table, matches replies by reqId and drops foreign or late ones, and bounds a round trip with an 8s timer. A missing CLIENT_CAP_SCREEN_PREVIEW bit is refused with -32005 before anything is sent; region/window/monitor parameters are refused with the same code because the v2 CLIENT_CAP_SCREEN_REGION extension is not implemented in this build. Status 4 maps to -32602 because the caller can fix the target, while capture/encode failures stay -32000. Windows clients return JPEG directly. Linux clients have no JPEG encoder and return top-down BGRX, which the server converts (R/B swap, opaque alpha) before wrapping the frame as an MCP image item. The image item is new to the content envelope; text tools keep text-only items. Verified live against x64\Debug\ghost.exe (JPEG FF D8 FF, decoded size matches metadata, max_width clamped to 64) and against linux/ghost under WSL (BGRX path, valid JPEG, black frame from the known Xwayland capture limitation). gofmt/vet clean, unit and -race tests green. Co-Authored-By: deepseek-flash |
||
|
|
808747f9d2 |
Feature(Go): terminal_close, idle sweep and legacy-client guard
Add the terminal_close tool so a caller can release a shell session explicitly instead of waiting for it to age out. The tool is idempotent for the session it names, rejects a session_id that does not match the live session with -32002, and runs without the per-device lock so it can interrupt a terminal_exec call that is still polling on the same device. Give hub leases a generation counter: the generation is bumped when a pending lease is created and carried across a device re-login. MCP-side closes pass the generation, so a stale session can no longer tear down a shell a human operator opened after the device reconnected. The reaper runs on a 30 s ticker (shortened when TermIdle is smaller), skips sessions that are still opening, and reclaims idle sessions as well as commands overdue past the one-hour busy cap. The pre-bind terminal-close path in cmd no longer closes unconditionally; it touches only a pending lease, because an unbound sub-connection carries no lease identity and may be a stale orphan. Covered by unit tests for close semantics, lock exemption, reaper lifecycle and lease-generation ownership, plus a live run against a Debug ghost: close before and during a command, reopen, idle reap and mismatched-id rejection all behave as specified. Co-Authored-By: deepseek-flash |
||
|
|
599c891c00 |
Feature(Go): terminal_exec with sentinel cleaning and polling
Implement M4b of the Go MCP minimal plan: terminal_exec runs one command in a device's persistent shell and polls the rest of a timed-out command. Wire format follows the Win32 server: ConPTY sends "@echo off & <cmd>" plus a sentinel line carrying %errorlevel%; POSIX PTY clears PS1 and uses $?. Output cleaning is a byte-faithful port of the MFC stages (ANSI, CRLF, echoed input, sentinel remnants) and is shared by commands and polls. A timed-out call leaves the session and the command running; the next call with only session_id delivers from the cursor it left. Per-window output is bounded by max_output_bytes, truncated on a line boundary, and ring evictions are reported as dropped_bytes. When the shell dies mid-command the session stays reachable until its buffered tail has been polled, then is released without touching the hub, which may already belong to a new viewer. Adds ClientCapTerminal (0x8000) for the Android gate; older APKs, macOS and legacy non-PTY shells are refused with -32005. Co-Authored-By: deepseek-flash |
||
|
|
12b1bd4786 |
Feature(Go): MCP terminal sessions with a 256 KiB ring buffer
Add the server-side half of the terminal tools: a per-device session table that claims the hub's single-viewer shell lease for MCP, and an output ring that survives a timed-out request so a later poll can still collect the command's result (terminal_exec itself arrives in M4b). The ring keeps the newest 256 KiB of shell output, tracks absolute offsets, and counts dropped bytes so callers can report truncation. A sentinel scanner looks for the per-command done marker, skipping the echoed command line and accepting Windows' negative error codes; its scan position is incremental with a small overlap so a marker split across TCP reads is still found. Server implements hub.EventHandler and cmd subscribes it when the endpoint is enabled; only the three terminal callbacks do work, and OnTerminalData stays cheap on the TCP read loop (lookup, append, scan, broadcast). Opening inserts the session before calling the hub so an early OnTerminalReady cannot be lost, stale close events that race a fresh open are ignored while the hub still holds the lease, and idle sweeps verify session identity. The reaper and terminal_close land in M4c. Co-Authored-By: deepseek-flash |
||
|
|
1076e7614a |
Feature(Go): per-device locks, a global call gate and tool-call audit
Add the three cross-cutting guards the Go MCP endpoint needs before any tool talks to a client. Each tools/call now takes one of MaxConcurrency global slots and, for single-host tools, that host's device lock; both are non-blocking, so contention returns -32003 instead of queueing. Panicking handlers are converted to -32000 rather than dropping the connection. Write one mcp.tool.call audit record per named call, including rejected ones: actor/role/source, tool, device, ok/code, duration, a size-only result summary and a truncated argument digest. Commands keep only their first word plus length, and free-form or credential fields (text, message, body, headers, password, token) are replaced by their size, so secrets do not reach the audit file. Co-Authored-By: deepseek-flash |
||
|
|
774c0d2545 |
Feature(Go): four local MCP read tools and a shared audit query package
Implement milestone M2 of the minimal MCP plan: the tools that answer from the server's own state instead of opening a device channel. - Extract the audit-log scanner from web into package auditquery so the admin page and get_audit_log share one implementation. The web handler keeps its 500-row cap, the MCP tool uses the protocol's 1000-row cap. Query gains json tags for the web snake_case wire format (device_id, warn_only) and reports TotalAll before filters. - Add package buildinfo and inject Version/Commit with -X from build.ps1 and the Makefile; go-winres refreshes Windows resources from the git tag when available. An unversioned build reports "", and only initialize substitutes "dev". - list_hosts: online/offline pools, include_offline merge, every documented filter, limit/offset paging with total/totalAll/hasMore, and schema-named host fields (authStatus/tls/remark are never fabricated). - get_host_detail: single id or a batch of up to 50, online lookup then the last history record, capabilities from protocol.SupportsCap plus the Windows/registry/virtual-desktop rules; v2 is not listed. - get_server_status: version, uptime, online/offline counts, port and bind. sessions stays absent until the MCP session table lands in M3. - get_audit_log: case-insensitive event substring, keyword, paging; hasMore turns false at the MaxOffset clamp so paging cannot loop. Wire hub, history, audit path and listen address through mcp.Config from cmd/main.go. Tests cover pools/filters/paging, capability bits, batch failures, audit paging and the unversioned build. Co-Authored-By: deepseek-flash |
||
|
|
3f1957a9c9 |
Feature(Go): MCP endpoint with bearer auth and tools/list
Add a stateless POST /mcp endpoint to the Go server, mounted by the web server and built from an environment-driven Config in cmd. The endpoint gates on YAMA_MCP_TOKEN: without it the route is not registered and /mcp 404s. Requests use a constant-time bearer compare, and transport failures stay transport failures (401 with a WWW-Authenticate challenge, 405 for anything but POST, 413 above 8 MiB, 204 for notifications). Everything after a parsed JSON-RPC request is HTTP 200, including -32600 for batch arrays and -32601 for unknown methods or tools. tools/list returns the nine minimal tools verbatim from an embedded copy of the canonical schemas. tools/mcp_tools/gen_go_tools.py extracts them from mcp/tools.json, preserving order and only the four published fields, and its --check mode detects drift. Readonly mode hides and refuses terminal_exec/terminal_close (-32006); tools that are listed but not implemented yet answer -32000 until their milestone lands. Also sync design §3.2 and the M2/M7/M8 plan text to tools.json, which is the sole schema contract: files not entries, line-based read_file, no since, camelCase capabilities, max_width [64,1920] defaulting to 1024, and outputSchema included in the M8 subset comparison. Co-Authored-By: deepseek-flash |
||
|
|
5f124fcb3a |
Docs(mcp): add Go minimal MCP design and implementation plan
Add the v1.0 design for the Go-side minimal MCP server (nine read-only tools over hub, audit log, terminal and file channels) and the staged plan that turns it into eight commits. Record the five decisions settled before construction: extract the audit query scanner into server/go/auditquery, inject version and commit via a buildinfo package plus go-winres, treat mcp/tools.json as the only tool schema contract, verify against a real client, and expose seven tools in readonly mode. Add the M0 findings: TestRun.exe cannot log in, because it needs ServerDll.dll loaded through MemoryDllRunner and the release build deletes itself when started outside its install path. A Debug ghost.exe came online against a local Go server in trial signer mode within ten seconds. Co-Authored-By: deepseek-flash |
||
|
|
425d737ca0 |
Fix(mcp): harden terminal teardown and fill annotation gaps
OnTerminalClosed now erases the shell route and nulls the session pointer before OfflineProc returns that context to the pool, and WaitTerminalReady re-looks-up the session on every wake, failing with cleanup when it is gone, closed, or has no sub-connection. Before, a waiter could CancelIO a recycled context, or a late cleanup could unroute a connection that reused it. terminal_close only set closed and expected a waiter to clean up, so after a caller timeout the remote shell kept running and the slot stayed busy for an hour. A waiters counter now separates the cases: with a waiter the close hands off, without one it erases the session and cancels IO at once. WaitTermCommand's closed branch keeps a truncated tail pollable instead of dropping it, cancelling IO immediately, and the drained poll cleans up. The write side had the same hazard. exec_command, terminal_exec and http_probe wrote the command line after the prompt wait without rechecking the sub-connection; IsTermSubCtxLive now skips the write when the shell has died, and WaitTerminalDone reports closed on every failure path so callers never CancelIO a pointer that may be back in the pool. list_hosts, read_file and http_probe were missing from kToolHints and got destructive defaults; the first two are now read-only/idempotent, http_probe stays writable because its method can mutate the probed service. Verified on the isolated Debug instance: the truncated tail drains without gaps (12514 lines), a waiterless close frees the slot in 0.1s, and the terminal, exec_command, http_probe, 8a/8b/8c and verify_tools checks pass. Co-Authored-By: deepseek-flash |
||
|
|
5841f27df9 |
Feature(mcp): unify window and service controls behind one name per state
operate_window / host_control_window and control_service / host_control_service were two implementations of the same intent. tools/list now exposes exactly one of each pair, chosen by McpMachine: the host_control_* names when host management is enabled, the main-connection names when it is not. The advertised tool accepts the union of actions. host_control_window routes close/show to the main-connection implementation, which stays the only path with close/show semantics and requires McpManage; the machine path keeps its post-action verification for restore/hide/maximize/minimize/activate. host_control_service routes set_auto/set_manual the same way and rejects dry_run for them instead of pretending to run one. Both old names remain callable aliases, and service_name is accepted as an alias for the machine tool's name parameter. The manifest generator treats the two main-connection tools as !machine entries, so the two-capture union still covers both states. tools/list is 49 entries when everything is on (was 51) and 47 when host management is off; the response shrinks from 193,008 B to 168,634 B (-12.6%), short of the 15% estimate because state-conditional tools must stay in the manifest. The plan document records that measurement and the reason. Verified with a dedicated two-state test: visibility matrix, close/show and set_auto/set_manual routing through dry_run and validation paths, alias dispatch, and -32006 for host_* names when host management is off. Step 8a/8b regressions and verify_tools --live still pass. Co-Authored-By: deepseek-flash |
||
|
|
c73db530f4 |
Feature(mcp): hide the degraded list_* tools when host management is on
host_inspect now covers processes, windows and services, so with McpMachine=1 the older list_processes / list_windows / list_services entries only competed with it: same intent, two names, two long descriptions to read before choosing. They no longer appear in tools/list while host management is enabled, but their names still dispatch, so callers that cached them keep working. They must stay visible when McpMachine=0: that is the default state and the only way such a server can list processes, windows or services, so the entries sit behind !IsMachineEnabled() rather than being removed. list_network_connections is deliberately not folded in: it reads the connection-manager view (IPv6 rows, killable flag, numeric state) which host_inspect's IPv4-only network aspect does not provide. tools.json is now generated from two captures, all-switches-on plus McpMachine=0, because neither state contains the whole surface; the off-state entries are marked gate "!machine" and verify_tools.py skips them when comparing against an all-on server. tools/list went from 54 to 51 entries and from 183,336 B to 171,929 B (-6.2%). Co-Authored-By: deepseek-flash |
||
|
|
59f0f16f74 |
Feature(mcp): merge the ten host_list_* tools into host_inspect
The ten read-only host-management tools (host_list_processes, windows, network_state, software, browser_history, favorites, win32_services, driver_services, scheduled_tasks, host_get_hosts_file) each carried a name, description and schema for what is one connection to the host, one tab id per aspect and one paged list shape. Ten entries made tools/list hard to scan and took a large share of the description budget. They are now one tool, host_inspect(aspects[], ...), where aspects is a required, deduplicated array of the ten former names. A single aspect returns exactly what the old tool returned (same builder, same code path), so output is byte-identical; several aspects are fetched over separate managed sessions and merged into results.<aspect>, with failures isolated in errors.<aspect> and isError only when every aspect failed. Filters (pid/name/arch/title/url/publisher/folder/status/ start_type/process/protocol/ports/state/max_bytes) are still applied server-side before paging and are ignored by aspects they don't apply to. The old names stay as dispatch aliases so existing callers keep working but no longer appear in tools/list; the platform table, batch read-only list, tool hints, instructions, generator tables and the captured mcp/tools.json move to the new name (63 tools -> 54). The description also notes that win32_services / driver_services need an elevated client: a non-elevated one cannot open SCM and never answers, so the call times out after ~12 s. Co-Authored-By: deepseek-flash |
||
|
|
cac5adaafc |
Docs(mcp): distinguish client runtime log from business app logs
get_client_log reads the YAMA client's own in-memory ring buffer, but its description could easily be read as "the logs of whatever program runs on the host". That misreading sends callers looking for business logs into the wrong tool and back out empty-handed. The description now opens by saying this is not the business program's log, points at read_file with offset=-N for reading files on the host, and states that this tool is for client/connection troubleshooting. read_file's description gains the same explicit offset=-N hint at the tail where log-reading is recommended. Descriptions only - no behavior change. mcp/tools.json regenerated from the live capture. Co-Authored-By: deepseek-flash |
||
|
|
88269df548 |
Feature(mcp): merge the three host-list tools into list_hosts
list_online_hosts, search_hosts and list_all_hosts differed only in whether offline hosts were included and in which filter fields they accepted, which made the host-list surface confusing and duplicated three handlers over the same CollectAllHosts snapshot. They now share one tool, list_hosts(query?, online?=true, include_offline?=false, group?, os?, client_type?, limit?, offset?). The old names stay as aliases routed to the same handler, so existing callers keep working, but tools/list exposes only list_hosts. The legacy "offline" boolean of list_all_hosts is still honored, and list_all_hosts keeps its online+offline default. With offline history included the list is now ordered online-first: the host library holds thousands of records, so the default page of 100 would otherwise be all stale entries and the online hosts a caller can actually operate on would be buried behind paging. instructions, every id-description string, the platform table, the tools.json generator and the captured mcp/tools.json are updated to the new name (65 tools -> 63). Co-Authored-By: deepseek-flash |
||
|
|
613aa7291a |
Feature(mcp): add http_probe for private-network HTTP checks
Run an HTTP/HTTPS request inside a shell on a managed host and return a structured result: status code, headers, body (UTF-8 or base64), size and elapsed time, so interface health on the host or its subnet can be checked without a full remote-control session. The safety boundary is hard-coded on the server, not in the shell script: only http/https and IP literals (or localhost); only loopback and private ranges (127/8, ::1, 10/8, 172.16/12, 192.168/16) are accepted; redirects are not followed; the body is capped at 64KB; TLS certificates are verified. Domain names are refused on purpose - resolving them on the server would probe the wrong network. Windows runs a single-line PowerShell 2.0-compatible script based on HttpWebRequest. Accept/User-Agent/Referer are mapped to their dedicated properties because .NET rejects them through Headers.Add. Linux uses curl with temp files. Payloads cross the terminal channel as 56-character base64 chunks with a declared byte length. ConPTY re-emits the boundary character of lines wider than 80 columns, so single-line base64 arrives corrupted; the length check converts any remaining loss into an explicit error rather than silent garbage. The tool reuses an existing persistent terminal session. Sessions it creates itself are closed after the command and kept only when the probe timed out while still running. Platform gating: Windows and Linux only. Co-Authored-By: deepseek-flash |
||
|
|
697044d84b |
Feature(mcp): add read_file for byte-accurate remote text reads
read_file fetches a single remote file through the existing V2 download channel into a per-call temp directory, decodes it, and deletes the temp files on every exit path. It returns the file size, detected encoding, EOL style, total line count, the requested slice (negative offset counts from the end), a truncation flag and the whole file's SHA-256. Encoding auto-detection follows BOM -> UTF-8 validity -> GBK fallback, and utf-8/gbk/gb18030/latin1 can be forced. Files above 2MB and directories are rejected from the first chunk, so nothing is written to disk for them. The tool is gated by McpFileTransfer only: it never writes to the remote host, so it stays available in readonly mode. The V2 receive path now serves both download_file and read_file. Co-Authored-By: deepseek-flash |
||
|
|
0378e96470 |
Feature(mcp): let terminal_exec open or reuse a session implicitly
terminal_exec no longer requires session_id. Given a command and no session_id, it reuses the host's persistent terminal session or opens one through the same path as terminal_open, and reports session_id, is_pty and reused in the result so the caller can keep using it. Polling still requires the session token. terminal_open now returns the existing session with reused:true instead of -32003 when one is already active. An implicitly created session is invisible to the caller, so rejecting would silently lock the host's single terminal slot and leave exec_command failing with a busy error. A session that is still starting, or one owned by a one-shot exec_command, still answers -32003. The server instruction line that told models to always pair terminal_open with terminal_close is updated accordingly. Co-Authored-By: deepseek-flash |
||
|
|
3fe3a11494 |
Feature(mcp): keep terminal sessions on timeout and allow output polling
terminal_exec used to destroy the persistent session on timeout, so long commands (robocopy, upgrade scripts) could never be observed: the collected output was thrown away and the shell was killed. Waiting is now decoupled from the command: - WaitTermCommand delivers [delivered, ...) and no longer erases on timeout. It returns done:false plus the output produced so far; the session stays busy and polling continues until done:true with exit_code. - Calling terminal_exec with only session_id polls (no command); command is optional and the result gains session_id / done / truncated / dropped_bytes / elapsed_ms. - Request cancellation still destroys the session (-32800 path); shell exit and terminal_close deliver the remaining output and then clean up. - Chunks are capped at max_output_bytes (default 64KB, newline-aligned); the per-command buffer is capped at 8MB and reports dropped_bytes; busy sessions are force-reclaimed after an hour so a host cannot stay busy forever. - A finished command with undrained output returns -32003 with a drain hint instead of silently losing it when the next command clears the buffer. Verified on an isolated Debug instance against a Windows host: a 3s timeout on an 8s ping returns done:false + partial output and two polls finish it; a 277KB dir listing needs 5 polls and then accepts a new command; 200 echo lines delivered in 12 chunks arrive exactly once in order; cancel returns -32800 and destroys the session. tools.json regenerated (63 tools, PASS). Co-Authored-By: deepseek-flash |
||
|
|
b63c97c5eb |
Feature(mcp): allow sc qc/enumdepend/sdshow in default command whitelist
exec_command's read-only default whitelist only listed `sc query`, so service configuration inspection was rejected even though `sc qc` is a read. Add `sc qc`, `sc enumdepend` and `sc sdshow`; `sc start/stop/config/create/delete` stay rejected because matching is prefix based, and a comment says so. verify_tools.py --live now prints the tools/list response size plus the description / inputSchema / outputSchema breakdown, so shrinking tools/list can be measured against a running server. Verified on an isolated Debug instance (port 6555, local test client): sc qc/enumdepend/sdshow/query succeed; powershell, icacls, net user, net localgroup, sc start and `&` chaining still return -32007/-32012; tools.json still matches the live tools/list (63 tools, PASS). Co-Authored-By: deepseek-flash |
||
|
|
f5ac7ba45f |
Docs: revise MCP tool optimization plan against measured baseline
The v1 plan was written without measuring the live server. Re-measure and fix it against the code: - tools/list response is 193,008 B (tools array 136,692 B; description 31,874 / inputSchema 44,192 / outputSchema 49,320), not 103,158 B; the >=15% goal now refers to this baseline. - TermSession::sentPos is the sentinel offset, not a delivered cursor, so P0-2 introduces a real `delivered` cursor instead of reusing it. - The whitelist additions icacls / net user / net localgroup are writes under prefix matching; only sc qc / enumdepend / sdshow qualify. - "file too large" uses -32602, not the invented -32011 (destination write failure). - P0-3 gains four prerequisites (size pre-check, McpFileTransfer gate, RAII cleanup, sha256/lines_total semantics); P0-1 spells out the default-session slot hazard; the stage order is P0-4 first since it is the cheapest win. Appendix B records how the baseline was measured (verify_tools.py --live). Co-Authored-By: deepseek-flash |
||
|
|
23fb50b7d4 |
Build: add server-linux target for cross-compiling the Go server
`build server-linux` now builds the Go server as a Linux/amd64 binary at Bin\server_linux_amd64 instead of the Windows YamaGo_x64.exe, so the artifact can be copied to a Linux host as-is. It reuses the go-server flow: web asset sync, Release builds strip with -s -w (debug keeps symbols), and the caller's GOOS/GOARCH/CGO_ENABLED are restored afterwards so a direct .\build.ps1 run does not leak the cross-compile environment into later builds. UPX compression is skipped for Linux output (the script only ships upx.exe for the Windows build) and logs a warning instead. Verified: the generated binary is a stripped static ELF that runs under WSL and prints its flags. Co-Authored-By: deepseek-flash |
||
|
|
81f0d6c031 |
Fix(server,client): keep web terminal alive across heartbeat reconnects
The Go server answered TOKEN_HEARTBEAT with a 33-byte CMD_HEARTBEAT_ACK, while the Linux and Android clients gate the ACK on 1 + sizeof(HeartbeatACK) (1025 bytes) and silently drop anything shorter. Their application-level ACK watchdog therefore never got fed and disconnected the main connection every 60s. Each re-login replaced the whole hub.Device, wiping the screen/shell sub-conn bindings that ride their own TCP connections, so a web terminal kept receiving shell output while every keystroke was dropped — the "terminal goes unresponsive after a while" symptom — and the shell could no longer be torn down (orphan bash + leaked sockets). Clients now accept the 32-byte old ACK (Windows already did), and the server sends the full 1024-byte struct. Hub.Register carries the sub-conn session state across a re-login, and the disconnect cleanup is pinned to the connection it belongs to so a stale OnDisconnect cannot tear down a registration that has already replaced it. A shell sub-conn that can no longer be bound now tells the viewer instead of leaving the pane waiting. Verified on aa: RTT restored, zero "Heartbeat ACK timeout" lines, main-conn port stable; Go build/vet/test pass. Server deploy to the Go host is still pending, so un-upgraded clients will keep reconnecting until then. Co-Authored-By: deepseek-flash |
||
|
|
4aedca8ee0 |
Feature: Support voice monitoring on Android hosts
The master's voice monitoring menu sends COMMAND_AUDIO; the client opens a ConnAuth sub-connection with TOKEN_AUDIO_START, the server opens CAudioDlg and answers COMMAND_NEXT, then audio flows both ways. The protocol matches the Windows client, so the server needs no changes. The server's ACM format was read from Audio.cpp and AudioDlg.cpp first: WAVE_FORMAT_GSM610, 8000 Hz mono, 65-byte blocks of 320 samples (40 ms), about 1625 B/s. libgsm 1.0.13 (AOSP external/libgsm mirror) is vendored under cpp/gsm and built with -DSASR -DWAV49 so its MS-GSM packing is byte-identical to ACM GSM610. Encode and decode use separate gsm states because frame_index/frame_chain live in the state. Uplink packets are always exactly 1000 bytes: CAudio::PlayBuffer copies 1000 bytes from the buffer start regardless of packet length, so a short packet would over-read. Since 1000 is not a multiple of 65, blocks straddle packets; the stream is continuous and codec state carries over. AudioMonitor.kt owns AudioRecord (8 kHz/16-bit/mono, 320 samples a read) and AudioTrack playback of decoded downlink PCM. RECORD_AUDIO is requested with POST_NOTIFICATIONS before the projection dialog, and CaptureService adds the microphone FGS type only when held, falling back on failure. An 8-second dialog wait or missing microphone reports a tip to the master instead of failing silently. Verified on an Android 15 emulator against the Debug server: dialog opened, uplink started, server receive counter grew at ~1.6 KB/s. Downlink playback was not exercised (the test machine has no recording device); that path is code-reviewed only. Co-Authored-By: deepseek-flash |
||
|
|
3ab5154db1 |
Feature: Honor remote desktop tuning commands on Android hosts
The Android client dropped CMD_QUALITY_LEVEL, CMD_FPS, CMD_QUALITY_PROFILES and CMD_SCREEN_TUNING as log lines, and hardcoded ScreenSettings.QualityLevel to Good. Because the server initializes adaptive quality from the client's reported level, that hardcoded value pinned every Android session to a fixed profile: adaptive quality could never start. ScreenTuning.kt now owns the state in SharedPreferences (level, max fps and the master's six-row profile table), and C++ only parses the wire format. The level is persisted when the master sets it explicitly, including -1 adaptive and -2 disabled, and is reported back in TOKEN_BITMAPINFO on the next screen session. A concrete level switch applies the profile bitrate at runtime via MediaCodec.setParameters(PARAMETER_KEY_VIDEO_BITRATE), which is smooth and needs no encoder rebuild. Frame rate is stored as-is (255 = unlimited, matching Windows) and only reaches KEY_FRAME_RATE at the next capture start, since surface encoders have no runtime fps cap. Ultra and High default to a zero bitrate because their Windows algorithms are DIFF/RGB565, so Android falls back to the previous 4000 kbps. CMD_SCREEN_TUNING stays log-only: all four flags belong to the Windows capture/x264 path and Android does not claim SCREEN_CAP_TUNING_FLAGS. CMD_SCREEN_SIZE is ignored; the server's pending resolution-change mark self-heals after one second. Verified on the emulator: a seeded Level 5 starts capture at 800 kbps/8 fps and the server title shows Minimal; a master-side switch to Good changes the live bitrate to 3000, and a restart picks up fps 30 from CMD_FPS. Co-Authored-By: deepseek-flash |
||
|
|
a801a2999a |
Feature: Support input blocking and privacy overlay on Android hosts
remote_block_input rejected anything but Windows because the Android client had no COMMAND_SCREEN_BLOCK_INPUT handler. This adds the overlay on the client and the server gating, and wires up COMMAND_SCREEN_BLANK. Client: the accessibility service hangs a full-screen TYPE_ACCESSIBILITY_OVERLAY on itself. block=true makes it transparent and touchable so it swallows physical taps; black=true paints it black. Both are absolute states, so repeated commands are idempotent, and the handler clears the overlay when the screen sub-connection dies (Android has no "released when the calling thread exits" fallback). During a remote gesture the overlay is flipped to FLAG_NOT_TOUCHABLE, mirroring Windows' BlockInput(false) wrap; the flag change and the injection must be separated by a short delay or the gesture is swallowed. Server: CLIENT_CAP_PRIVACY_OVERLAY distinguishes new APKs from old ones; Linux/macOS and old APKs still get -32005 up front. Tool masks, instructions and mcp/tools.json follow the change. COMMAND_SCREEN_BLANK is implemented but not exposed as a tool: MediaProjection captures the overlay, so blacking out the screen blinds the operator too and cannot emulate Windows' WDA_EXCLUDEFROMCAPTURE. Verified on the Android 15 emulator: blocked taps are swallowed while remote clicks still land, the block re-arms after each gesture, the watchdog auto-unblocks at the deadline, a dropped sub-connection clears the overlay, and a black overlay shows up in both screencap and get_screenshot. The committed ghost.apk is stale; rebuild before release. Co-Authored-By: deepseek-flash |
||
|
|
445bd8bbb9 |
Feature: Support the remote terminal on Android hosts
The terminal tools were Windows/Linux only because the Android client had no COMMAND_SHELL handler: the server opened a shell sub-connection and the command was silently dropped, leaving exec_command to time out. This adds the PTY path on the client and the matching server gating. Client: COMMAND_SHELL on the main connection spawns a terminal thread that opens an authenticated sub-connection, sends TOKEN_TERMINAL_START and keeps the PTY alive until the server closes it. common/PTYHandler.h is reused, with a minSdk-21 openpty built from posix_openpt/grantpt and /system/bin/sh (mksh) as the shell. A new CLIENT_CAP_TERMINAL bit lets the server reject old APKs up front with -32005. Server: the tool masks, instructions and docs matrix accept APK. While verifying, exec_command left a second echoed copy of the command line in stdout: mksh forks with ECHO still on, so input written before its line editor takes over is echoed by the line discipline in addition to the shell's own redraw. The server now waits for the shell's first output (the prompt) before sending the command and sentinel, which restores the single-echo assumption the cleaning step relies on. terminal_exec on a ready session is unaffected. Verified on the Android 15 emulator: exec_command returns clean stdout and real exit codes for id/uname/df/ls (including a failing command), and terminal_open keeps cwd across commands, pipes work and close is clean. The committed ghost.apk is stale and must be rebuilt before release; a rebuilt APK was used for this testing. Co-Authored-By: deepseek-flash |
||
|
|
915c587964 |
Feature: Support remote chat on Android hosts
The chat tools were Windows-only because the Android client had no COMMAND_CHAT handler: the server asked for a chat sub-connection and the command was silently dropped, leaving chat_open to time out. This adds the full path on the client and the matching server gating. Client: COMMAND_CHAT on the main connection spawns a chat thread that opens an authenticated sub-connection, sends TOKEN_CHAT_START and waits for the server to bind it. Incoming GBK lines are decoded and dispatched to ChatSession, which drives an in-app chat activity; when accessibility is available the activity is pulled to the front, otherwise a tappable notification is posted. Outgoing text is strictly GBK encoded so emoji and unmappable characters are rejected instead of becoming '?'. When the server ends the session the activity closes itself, matching the Windows client's DestroyWindow, and a new session starts from an empty log. Server: a new CLIENT_CAP_REMOTE_CHAT bit lets the server tell new APKs from old ones. ResolveHost now accepts Windows and Android hosts and rejects older APKs up front with -32005 rather than waiting for the command to expire. Tool platform masks, instructions, the docs matrix and mcp/tools.json follow the same change. Verified end to end on the Android 15 emulator: chat_open pops the activity, Chinese text from the server renders, a device reply reaches chat_wait, and ending the session from the master closes the activity instead of leaving a dead window. The committed ghost.apk is stale and must be rebuilt before release. Co-Authored-By: deepseek-flash |
||
|
|
f33a205fd9 |
Fix: Report chat_wait timeouts only when no message arrived
WaitChatMessages decided overtime after the drain loop had already emptied the session inbox. Whenever a reply arrived during the wait the loop moved every queued message into the result and then evaluated timed_out on the now-empty queue, so a successful wait was still reported as a timeout. Callers that key off timed_out would either retry needlessly or treat the answer as noise. The arrival state is now captured before draining and the deadline flag is computed from that snapshot. A wait that returns messages is never marked timed out, while an empty wait still reports timed_out so the caller can distinguish silence from a closed session. Verified end to end against the Android emulator over the MCP debug endpoint: after a device reply chat_wait returned one message with timed_out=false, and a follow-up wait on the empty inbox returned timed_out=true, preventing a regression in the other direction. Co-Authored-By: deepseek-flash |
||
|
|
29d7ee1a18 |
Feature: Support host uninstall on Android and expose uninstall_host
The server's "uninstall host" action is the single-byte TOKEN_UNINSTALL on the main connection. Windows clients have handled it for a long time; the Android client ignored it, so the menu entry silently did nothing there. Handle it in the Android client the only way Android allows: ask the system to uninstall the package. The client first replies with COMMAND_BYE and drops the connection, then opens the package installer's confirmation dialog through the accessibility service, or posts a notification that resumes the dialog from MainActivity when accessibility is off. The user still has to confirm on the device; if they cancel, the client has already left the server and must be reopened by hand. The manifest gains REQUEST_DELETE_PACKAGES, without which the installer activity refuses the request outright. New APKs advertise CLIENT_CAP_UNINSTALL so the server can reject old clients instead of sending a command nobody handles. The new MCP tool uninstall_host is gated on McpManage and McpReadonly=0, rejects Linux and macOS hosts, and offers the same wait=true verification as power_action, reporting went_offline once the host disappears from the online list. Verified on the emulator end to end: the tool returned went_offline after 200 ms, the system dialog appeared, confirming it removed the package. Co-Authored-By: deepseek-flash |
||
|
|
fd1b085279 |
Feature: Add remote lock screen for Android hosts
Implement the Ctrl+Alt+Del path on Android as a system lock screen. Android has no secure attention sequence, so COMMAND_SCREEN_CTRL_ALT_DEL is mapped in the client to GLOBAL_ACTION_LOCK_SCREEN and the server exposes it as the new MCP tool remote_lock_screen. The Android client resolves ControlService.lockScreen()/canLockScreen() in nativeInit and dispatches the command from the screen sub-connection through the usual attach/detach JNI path. The lock action is posted to the accessibility service handler because performGlobalAction must not run on the receiver thread. Login advertises the new CLIENT_CAP_LOCK_SCREEN bit only when the accessibility service is bound and the API level is 28+, so the server can reject old APKs and Windows/Linux hosts up front instead of reporting a lock that never happened. There is no receipt: a successful call only means the command was delivered, and the tool description tells the caller to confirm with get_screenshot. Server side adds the schema and handler next to remote_clipboard, audits the call, and gates it on client type plus the capability bit. Since it is the only APK-only tool, check_platform_table.py gains a documented exemption from the Windows baseline invariant, and make_tools_json.py learns an APK-only platform set. tools.json is regenerated from the live server and the plan document now counts 62 tools. Co-Authored-By: deepseek-flash |
||
|
|
0a0b709e8a |
Feature: Support remote clipboard and input on Android hosts
The MCP remote-control family (remote_open / remote_close / remote_mouse / remote_keyboard / remote_clipboard) previously stopped at Windows and Linux, even though the Android client already translated injected events into touch gestures and global actions. This wires up the missing piece and opens the five tools to APK hosts. Client side, the screen sub-connection now handles COMMAND_SCREEN_SET_CLIPBOARD: the native handler forwards the raw GBK bytes to CaptureService.onClipboardText, which decodes them, strips the trailing NUL that the human clipboard-sync senders append, and writes the system clipboard from a background app (allowed on Android 10+, only reads are restricted). Pasting cannot be a Ctrl+V combo, so VK_V is mapped to ACTION_PASTE on the focused node, falling back to the accessibility focus and then to the first editable node, since WebView and self-drawn inputs often do not flag FOCUS_INPUT or isEditable. A new capability bit CLIENT_CAP_SCREEN_CLIPBOARD (0x0800) tells the server the APK understands both paths, so builds without the handler get an explicit -32005 instead of a package that is silently dropped. action=type is rejected outright for APK hosts - physical key events would only turn 'v' into a paste - and the error points at remote_clipboard + key=V. The platform table, server instructions and the five tool descriptions now describe Android support, which keys actually act as global actions (ESC, HOME, APPS, PRINTSCREEN), and that injection needs the accessibility service while capture needs an authorized MediaProjection session, both without receipts. Verified on the API 35 emulator against a Debug server: ASCII and GBK Chinese text round-tripped through the clipboard into a focused Settings search field, type / expect_hwnd / window_hwnd returned -32005, and PRINTSCREEN produced a saved screenshot. check_platform_table.py and verify_tools.py --offline pass. Co-Authored-By: deepseek-flash |
||
|
|
ac43ad92ef |
Fix: Harden the Android client connection lifecycle
Five review findings from the screen-preview work, all in the same connection plumbing. The main client handle is now a shared_ptr taken through GetMainClient(). ScreenPreviewThread, ActivityReportThread and sendClientMsg run detached and can outlive ConnectionThread's teardown, so a raw pointer snapshot could dereference freed memory; the copy they hold now keeps the client alive until the send is done. sendClientMsg also uses one handle for both the connected check and the send instead of reading the global twice. The reconnect loop now checks its connection generation in every condition, so a thread that was asked to stop can no longer reconnect after a quick nativeStop -> nativeInit reset g_bExit and g_running into "running again", which produced two main connections with the same client ID. ActivityReportThread gets the same try/catch and RAII in-flight counter as the preview thread: an exception used to call std::terminate, and one failure left the counter above zero, silently dropping every later get_activity_history. nativeStop now stops the activity sampler, and Stop() clears m_started so a service restart can start it again. Sub-connections (remote screen and client log) now inherit g_SETTINGS.protoType like the main connection; without it they silently dialed plain TCP even when WS/WSS was configured. Verified on the emulator against a local debug server: get_screenshot, get_activity_history and get_client_log all still answer, and the log sub-connection completes the TLS handshake. Co-Authored-By: deepseek-flash |
||
|
|
f29150d20e |
Feature: Add screen preview to the Android client
get_screenshot and the server's online-list and hover thumbnails were gated to Windows and X11 Linux. The Android client now answers COMMAND_SCREEN_PREVIEW_REQ on the main connection with TOKEN_SCREEN_PREVIEW_RSP plus a JPEG, and advertises CLIENT_CAP_SCREEN_PREVIEW at login only when it can really capture. Capture goes through AccessibilityService.takeScreenshot (API 30+), enabled by canTakeScreenshot in the service config. MediaProjection is deliberately not reused: its VirtualDisplay already feeds the H.264 encoder and Android 14+ refuses a second one from the same projection, while accessibility capture runs alongside the live stream. The JPEG is scaled to maxWidth and encoded in Kotlin; native only copies the bytes and drops a request while one is in flight. Only mode=screen is supported, and capabilities are re-evaluated on every login so turning the service off withdraws the capability. Also fix two review findings: a screenshot callback that lands after the 3 s timeout now recycles its bitmap instead of leaking it, and the server's failure hint lists the possible Android causes instead of asserting disabled accessibility. Verified on the emulator against a local debug server: get_screenshot returns 640x1422 and 720x1600 JPEGs, the 120-wide list thumbnail works, and both MCP tool-table checkers pass with apk added for get_screenshot, get_activity_history and get_client_log. Co-Authored-By: deepseek-flash |
||
|
|
66acde0301 |
Fix: Keep the screen preview tip inside the monitor work area
RecalcLayoutAndResize only clamped the window position, so a portrait capture (an Android phone's 1080x2400 arrives as 480x1067 at the desktop default width) plus the info text made a tip taller than the screen, with its bottom half off it. The tip now also shrinks the image to the work area's height and width budget before placing the window. Text wraps to the image width, so the measurement is redone after each pass; two passes are enough because every pass only shrinks. Verified with the emulator's 1080x2400 client against a local debug server: the tip is 521x1016 inside a 1920x1032 work area and the image kept its portrait aspect. Co-Authored-By: deepseek-flash |
||
|
|
5ed1a07dc4 |
Feature: Add activity history to the Android client
get_activity_history was gated to Windows and Linux. The Android client now answers COMMAND_QUERY_ACTIVITY with a TOKEN_REPORT_ACTIVITY snapshot on the main connection, the same RPC shape as the other platforms; the server takes the first packet without CancelIO, so no sub-connection or request correlation is involved. The sampler reuses linux/LinuxActivityHistory.h, whose ActivityHistory class and formatters are platform-neutral, and is fed by a probe that asks the new ControlService.currentActivityTitle() once per second over JNI. The accessibility service already tracks the foreground package from TYPE_WINDOW_STATE_CHANGED; the title is "label (package)" with the label resolved once and cached, "Home" for the launcher, and idle for lock or screen-off, so no permission beyond the service users already enable is needed. Without the service the report says so instead of recording placeholder "Android" entries. Also scope the connection teardown to its own generation: a ConnectionThread that exits late (CaptureService restart) no longer clears the new run's g_running or g_pMainClient, and the report thread takes one local snapshot of the main client pointer. Verified on the emulator against a local debug server: five records (Settings, Chrome, launcher, Home) came back newest-first with dwell times, and disabling accessibility produced the permission hint. Co-Authored-By: deepseek-flash |
||
|
|
d365a4f948 |
Feature: Report client run logs from the Android client
Before this change the Android client's run log went to logcat only: Logger's init tried to create a log directory, enable was true, and the in-memory ring that MCP's get_client_log reads was never fed, so the tool returned an empty log for APK hosts. Logger now has an Android branch that skips the directory and file writer and keeps only the ring, which is always written regardless of enable. Mprintf carries the source file and line as on Windows/Linux, and both android_log (Mprintf) and a new android_log_tag (platform LOGI/LOGE, LOGI_SH/LOGE_SH) print to logcat and append to the ring. A new ClientLogThread opens a sub-connection on COMMAND_QUERY_LOG and lets ClientLogHandler send TOKEN_REPORT_LOG plus the full ring as the first packet. It has to be a sub-connection: the server takes the first packet and calls CancelIO, which would drop the main connection. The server side allows get_client_log on kPlatApk and decodes the payload as UTF-8 like the other POSIX clients. Verified on the emulator against a local debug server: get_client_log returned 21 UTF-8 lines including [file:line] Mprintf output, LOGI lines, and the ClientLogThread handshake. Co-Authored-By: deepseek-flash |
||
|
|
51747dc0ea |
Feature: Add on-demand TLS transport with hot-switch to the Android client
Reuse the Linux OpenSSL TlsChannel implementation (platform guard widened to __linux__); the trust anchor lives in the app-private filesDir, injected via TlsSetAnchorDir in nativeInit before the connection thread starts. COMMAND_TLS_ENABLE/DISABLE save/remove the anchor, hot-reload and reconnect only when the transport actually changes, so the master menu takes effect within seconds without restarting the app. Login reports RES_TLS, refreshed before each re-login. The reconnect flag is consumed before the drop check and cleared before reconnecting so a switch racing a disconnect cannot cause an extra reconnect/login cycle. Cross-compile OpenSSL 3.5.0 per ABI with build_openssl_android.sh (NDK clang + MSYS2 perl/make), integrated into build_android_libs.ps1 (-OpenSslOnly). Static libs and per-ABI headers are tracked like the existing libzstd/libsign prebuilts; --exclude-libs keeps OpenSSL symbols private to libyama.so, isolated from the Java-layer Conscrypt. Co-Authored-By: Qoder <noreply@qoder.com> |
||
|
|
36618b0ad0 |
Feature: Install Android APK updates pushed from the master
The master now sends COMMAND_UPDATE to Android hosts: it picks a "Build Client -> Android" APK, checks the ZIP magic and that the package carries this master's fingerprint, then sends [cmd][size][APK][xxh64]. The client verifies length and hash, writes filesDir/update.apk and commits a PackageInstaller session, so the system installer still asks the user to confirm - an app cannot replace itself silently. Write and hash failures come back over TOKEN_CLIENT_MSG, so the master sees why nothing happened instead of a silently dropped packet. Sending the wrong file is what the fingerprint check guards against: a template without the master id installs fine and then cannot connect back. "Send anyway" is offered only after spelling that out, and the client advertises CLIENT_CAP_APK_UPDATE (0x0400) so an old APK gets "install a new build once by hand" instead of a packet it would discard. Also report the real versionName/versionCode at login instead of the hardcoded v1.0.0, add android/tools/verify_update_apk.py (pre-send check of size, ZIP_STORED libs, ABI, package, versionCode and the decrypted CONNECT_ADDRESS, which it still locates after BuildDlg rewrote szFlag), and translate the nine new strings in en_US, zh_TW and de_DE. Verified on the emulator and against the live release server: generate, sign, send, install, and the device reconnects and re-grants screen capture. Language packs are GBK and were appended as bytes. Co-Authored-By: deepseek-flash |
||
|
|
cdd9c56b3d |
Feature: Add window/region capture targets to remote_open
Pass the target HWND through the COMMAND_SCREEN_SPY token and send COMMAND_SCREEN_ROI after session start, so MCP remote control can stream just the target window or region instead of the scaled virtual desktop. The session records the target kind, remote_mouse refuses a redundant window_hwnd basis, and the cached resolution is refreshed per action so resized windows keep mapping correctly. Cold starts now clear the stale resolution cache used by the region handshake. |
||
|
|
5501889d33 |
Feature: Add window-relative remote_mouse coords and PTY pipes in terminal_exec
New Windows clients append an optional 20-byte WINDOWINFO_MCP_DESKTOP block (virtual desktop rect, magic 'VDCP') after the window list, so the server can map window-relative coordinates into the capture frame. remote_mouse accepts an optional window_hwnd; x/y and drag x2/y2 are then normalized against the intersection of the window and the virtual desktop, which is exactly the source rect of get_screenshot mode=window. The target window must be foreground by default, and window_hwnd/expect_hwnd must agree when both are given. structuredContent gains coordinateWindow and resolved (frame coords plus the basis rect), so callers can verify the mapping. terminal_exec now allows pipes, && and || in PTY sessions (ConPTY on Windows, POSIX PTY on Linux) because the sentinel runs on its own line; legacy non-PTY sessions still reject & and |. A read-only PeekTermSession lets the server reject unsupported syntax before BeginTermCommand. POSIX still rejects bare background & (&&, &>, 2>&1 stay allowed). Docs: Mcp_Design.md sections 12.1/20.2/22 and Mcp_Terminal_Design.md 4.4/4.6 are synchronized with the protocol, the new validation order, and the basis rect semantics. Co-Authored-By: deepseek-flash |
||
|
|
235a8a622c |
Feature: Add native region, window and monitor capture to get_screenshot
New Windows clients advertise CLIENT_CAP_SCREEN_REGION and accept a 24-byte ScreenPreviewReqEx appended to the existing 8-byte preview request, so get_screenshot can capture a region, a window or a single monitor at 1:1 resolution instead of only the scaled virtual desktop. Successful v2 responses append an optional ScreenCaptureMeta block reporting the source rect and scale, letting callers map coordinates back for remote input. Old clients and old servers keep the v1 byte stream unchanged. The 8192 px per-side bound only applies to native (1:1) capture, where it guards bitmap memory; scaled captures are unaffected so ultra-wide virtual desktops (for example triple 4K) still produce thumbnails and previews. max_width is clamped to [64,1920] as before instead of rejected, matching the documented schema. Co-Authored-By: deepseek-flash |
||
|
|
b2c0d81396 |
Feature: Add window info RPC for foreground checks and window activation
Add a capability-gated main-connection RPC (COMMAND_MCP_WINDOW_INFO=179 / TOKEN_MCP_WINDOW_INFO=180) that returns visible top-level windows with UTF-8 titles, screen rectangles, foreground flag and z-order, so MCP can verify focus before injecting input. New tool get_foreground_window; host_list_windows switches to the richer fields; host_control_window and operate_window gain action=activate; remote_keyboard and remote_mouse gain expect_hwnd, require_foreground and report_foreground. Old clients keep the previous behavior: the RPC is refused up front via CLIENT_CAP_WINDOW_INFO. The client caps a response at 96 windows (about 101 KB, under MAX_SEND_BUFFER). Signal the cut-off in the mode byte (0x80) instead of silently dropping windows: host_list_windows now reports truncated=true and says the list is incomplete, and activate verification reports state=unknown with reason=list_truncated rather than claiming the window is gone. expect_hwnd is checked only after the session is validated, so an invalid session_id no longer burns a window RPC and no longer reports a window error for a session that does not exist. Nullable output fields (foreground, window) are declared as ["object","null"] so strict clients do not reject responses. Co-Authored-By: deepseek-flash |
||
|
|
c7e23f750d |
Fix: Keep the web remote view alive across resolution and quality changes
Hidden web/MCP screen sessions never receive TOKEN_FIRSTSCREEN and never run the local decode path, so m_bIsFirst stayed TRUE and every keyframe or scroll frame after a resolution change was dropped, leaving the browser black. The same black screen appears whenever the client runs a non-H.264 quality level (Ultra/DIFF, High/RGB565): DrawNextScreenDiff forwards to the web only inside the ALGORITHM_H264 branches while the MFC window renders every algorithm, and the existing web clamp cannot run in fixed-level mode because EvaluateQuality returns early when adaptive quality is disabled. Clear m_bIsFirst once an IDR decodes and forward keyframe/nextscreen frames for hidden web sessions. Clamp web sessions to QUALITY_GOOD in OnInitDialog, re-push the level when the client reports a lower one in BITMAPINFO, and nudge a flapping client back to H.264 at most three times. The browser now receives stream_algorithm/web_supported notices and shows an explicit hint in both the focus view and the wall instead of a silent black frame. Resolution-change recovery moved into OnTimer(4) so hidden sessions flush the decoder and request a fresh IDR too. Also bound the client-supplied block offsets and scroll parameters in the DIFF/GRAY/RGB565 decoders, which could otherwise write outside the destination DIB, and share one keyframe-request throttle between the resolution path and the web console. Verified with a Debug x64 server build and node --check on the page script; the Go server does not emit the new notices yet and degrades to the old behavior. Co-Authored-By: deepseek-flash |
||
|
|
5eb44307ee |
Feature: Capture the virtual desktop for multi-monitor remote control
The MCP Observe/Act loop requires screenshots and mouse injection to share one coordinate space. Previously the client sent only the primary monitor while injection used virtual-desktop coordinates, so multi-monitor hosts were rejected outright. - Client: COMMAND_SCREEN_SPY param buffer[11] (wire index 12) now forces whole-virtual-desktop GDI capture; preview JPEGs also cover the virtual desktop including negative origins. - Server: advertise CLIENT_CAP_VIRTUAL_DESKTOP, gate multi-monitor remote control on that capability, and pass the flag when starting the session. Linux stays exempt (X root capture/injection are already consistent). |
||
|
|
5bb24d714a |
Fix: Release remotely injected keys the controller never lifted
A browser or native controller can lose a keyup (window blur, tab switch, browser shortcut, in-app dialog, disconnect). The remote OS then keeps Ctrl/Shift/Alt down, later keystrokes turn into shortcuts, and only pressing the modifier again clears it. The web console now tracks the keys it sent down and releases them on blur, visibilitychange, pagehide, dialog, control off, device switch and disconnect; the next keydown/mousedown/wheel reconciles tracked modifiers against the event's real modifier state. Keys held when the socket drops are stashed and released once the screen session is confirmed after reconnect, tagged with the device so they never reach another host. The Ctrl+V bridge flag is reset wherever its physical keyup can be lost. The Windows client tracks injected keys by VK + scan code + extended bit so right-hand modifiers release the key that was pressed, and releases them on session teardown and reconnect; the Linux agent does the same on teardown with XTestFakeKeyEvent. Verified with a 20-scenario headless Chrome harness, group filter regressions, node --check, go build/vet/test, a Debug client build and the WSL Linux build. Not exercised against a real controller and host; the macOS agent is unchanged. Co-Authored-By: deepseek-flash |
||
|
|
6fd6e9cbaa |
Feature: Add a group filter to the web console device list
Operators running several groups had to scan the whole fleet. The device list now has a group filter: desktop renders the groups as chips in the Total row (click to toggle any number), while touch devices get a compact dropdown with checkbox rows plus Clear/Done. An empty selection means "all groups"; multiple selections are OR-ed and combined with the search box. Hosts without a group appear as "Ungrouped". Groups are derived from the current device snapshot (no admin-only get_groups call, so restricted users can filter too), and the selection persists in localStorage for the browser. The offered list follows the Offline toggle, while a selected group whose devices are temporarily gone stays visible with count 0 instead of being silently dropped. Logout clears the selection so the next account does not inherit it. The Wall view keeps its own search and is unchanged. Verified in headless Chrome at desktop and phone widths: multi-select, counts, dropdown open/close/clear, stale-selection retention, search focus, long names and persistence across reloads. go build and go test ./web/ pass. Co-Authored-By: deepseek-flash |
||
|
|
2cbed0dcdf |
Fix: Report process uptime and harden the login reserved list
The "启动信息" elapsed time was computed by subtracting a client-formatted wall-clock string from the master's own local time. Windows clients send their local time, Linux/Android/macOS send Beijing time, so a host whose clock runs ahead of the master (UTC+8 clients on a UTC+1 master, a fast CMOS clock) gave a negative difference that was clamped to 0s — permanently, for that host. Add RES_UPTIME to the login reserved list: the client reports its process uptime in seconds, a difference between two readings of the same clock, so timezone and clock skew cancel out. The master adds the connection's alive time to get the current value, and keeps the old string path as the fallback for clients that do not send the field. That fallback now also treats MAC as Beijing time, which was simply missed. AddReserved() now goes through one bounds-checked append. The separator used to be written without any length check (an overflow aborts the client, which installs no invalid parameter handler), and an over-long value now leaves an empty slot instead of dropping its separator, so positional lookups cannot shift. Verified with an ASan/UBSan test over the encoding boundaries and Debug builds of the client and the master. The Linux/Android/macOS clients only append the same field at the end of the list; they were not compiled here. Co-Authored-By: deepseek-flash |
||
|
|
2e34e49186 |
Fix: Keep the captured monitor stable across restarts
GDI and DXGI each kept their own static monitor index, and DXGI committed the index before its initialization had succeeded. When a quality change restarted capture and DXGI fell back to GDI, the next DXGI attempt read the failed attempt's index and jumped to the other monitor. Both backends now share one process-wide index with separate peek and commit steps, and the commit only happens after the backend is actually up. Manual switching is made a one-shot request: InitScreenSpy consumes the flag and RestartScreen only sets it, so an adaptive restart that lands in the middle of a switch no longer drops the request or re-applies it on every later rebuild. Window capture no longer touches the index at all, so leaving window mode returns to the monitor that was on screen. Also: restart capture on a bitrate change only when the target level is still H.264 (switching to RGB565/DIFF never uses the bitrate), and bound the DXGI output fallback so a session without any enumerable output cannot spin forever in InitDXGI. Co-Authored-By: deepseek-flash |
||
|
|
d8048979e3 |
Feature: Report activity history on Linux clients
Implement COMMAND_QUERY_ACTIVITY -> TOKEN_REPORT_ACTIVITY with two backends picked at startup. With a desktop, a sampler thread reads the foreground window every second and books dwell time like the Windows client: under five seconds is dropped, five idle minutes close the window, the last 500 records stay newest first, each line being "[YYYY-MM-DD HH:MM:SS] [title] duration". It uses its own ActivityChecker because an Xlib connection cannot be shared with the heartbeat thread, and it is stopped before main's locals go away. A reachable X server is not enough: the window backend is only chosen when the root window carries _NET_SUPPORTING_WM_CHECK, so Xvfb or a bare X without an EWMH window manager falls back to the headless backend instead of sampling a window id that never appears. Without a desktop the answer is computed on demand: logins from "last -n 100 -F" plus bash/zsh history of root and /home/*, tagged [登录] or [命令] after a [来源] header. Both halves are merged and sorted by timestamp; three fifths of the budget goes to logins and reboot records are capped at ten, since a WSL or container writes one reboot per start. activity_commands=0 drops the command half. A single detached thread builds and sends it, only while the main link is up. The MCP gate now admits Linux for get_activity_history and documents both shapes. test/unit/linux covers the parsers, ordering and UTF-8 truncation; 15 cases pass. Co-Authored-By: deepseek-flash |
||
|
|
5f40f3726c |
Fix: React to slow-frame congestion and keep remote audio recoverable
The adaptive quality controller counted only complete frames per second, so when a single frame took several seconds to arrive the sample was 0 fps and the throughput criterion abstained forever: Ultra and High kept flipping while a foreground video played. The audio watchdog had the opposite problem: it rebuilt the WASAPI capture every three seconds on an idle endpoint, and its sleep detector measured the whole loop including a blocking send. Sample the last ten seconds in a ring buffer and feed the criterion a windowed rate, guarded so a scroll burst, a stale window or a few KB clock patch is not mistaken for congestion. Apply the same per-frame floor to the one-second fallback and to the post-downgrade local-bottleneck probe. Normalize delayed timer ticks by real elapsed milliseconds, and make the 40 second upgrade-failure window outlast the resolution cooldown it has to cross. On the client, rebuild only when an audio session is actually rendering, and rebuild immediately when the captured endpoint is no longer the default output; refresh the sleep timestamps on failed as well as successful init. Tests cover the window and fallback helpers directly; the full suite passes 845/845, and both the Debug server and Debug client build. Co-Authored-By: deepseek-flash |
||
|
|
2a97471b51 |
Feature: Share a Linux host to another master
Add COMMAND_SHARE (SHARE_TYPE_YAMA) with the Windows semantics: the record goes into share_list and a second connection is opened to the target master while the main link stays where it is. main()'s connection state is all global, so each record is served by a forked "--share <entry>" child that reuses the whole login, heartbeat and command path; the parent only starts, tracks and reaps them. COMMAND_SHARE_CANCEL clears the list and stops the children right away (Linux can; Windows does it on the next start). Transfer now opens its connection immediately too, matching the Windows fallthrough that spawns a shared instance, and that temporary connection is dropped once the main link has actually moved to the target or when the transfer expires. common/host_endpoint.h holds the ip/port/shine/transport word list the two commands share; common/host_share.h holds the share payload, share_list encoding and the per-master dedup. Config writes now take a cross-process flock and replace the file by rename. The parent and every child write the same config.conf from their own snapshot, and a truncating overwrite could drop the other side's keys. Children ignore the commands that only mean something on the main link: share, transfer, upgrade, TLS anchor and group. Verified in WSL against fake masters: share start, cancel and restore, re-sharing with a different transport, share plus transfer on one master, and the transfer child disappearing after the main link moved. Co-Authored-By: deepseek-flash |
||
|
|
7240879792 |
Fix: Bound the Linux TLS handshake with a deadline
The handshake loop retried SSL_do_handshake on SSL_ERROR_WANT_READ and nothing else. IOCPClient arms the socket with SO_RCVTIMEO for the handshake, and a read timeout surfaces as EAGAIN, which OpenSSL reports as WANT_READ rather than a syscall error. A peer that accepted TCP and then went silent therefore put the loop into an endless retry: the handshake never finished, never failed, and logged nothing, while the main loop sat inside the read. Even SIGTERM could not stop the process, because the exit flag is only observed between heartbeats. Observed on a Linux client moving back to 443 when a transfer expired: frps had the connection ESTABLISHED, the server had sent a partial flight, the client's Recv-Q was empty and its log stopped dead at the reconnect line. Reproduced locally against a TCP server that accepts and never replies: one connection in 75 seconds and no output at all. Give the whole handshake a 30 second budget, longer than the 15 second read timeout so a single wake-up still fits, and treat expiry as a failure the caller can retry. The stalled peer now logs "[TLS] handshake timed out after Ns (peer silent), aborting" and the reconnect loop keeps running. Co-Authored-By: deepseek-flash |
||
|
|
4309865570 |
UI: Give the share/transfer dialog labels a full-width row
The address label was 81 dialog units wide at x=8 while the combo box starts at 93, and the prompt set at runtime - an IP:PORT hint that also mentions the optional wss:// prefix - is far wider than that. The static clipped it at its edge, so the rest of the hint looked hidden behind the input field; with the English or German translation almost the whole sentence disappeared. The days label had the same 81-unit width. Move both labels onto their own full-width rows above their controls and shift the combo box, days field, checkbox and buttons down to fit. The dialog grows from 105 to 128 units and the days field narrows from 201 to 80 units, so every translation stays on one line. The share variant still hides the days row, leaving the same gap it had before. The share and transfer dialogs share this template, so both are fixed. Co-Authored-By: deepseek-flash |
||
|
|
3b3aed50e5 |
Feature: Transfer a Linux host to another master
The Linux client ignored COMMAND_ASSIGN_MASTER, so a host could not be moved to a different controller the way the Windows client allows. The payload is host:port:days:shine[:transport]; the parsing, record encoding and address application live in a shared header so a macOS client can reuse them unchanged. An assignment only rewrites the connection target. The running session stays up and the next reconnect - a dropped link or a restart - goes to the new master, matching the Windows behaviour. The target and its expiry are stored in a single "transfer" config key, while the address the process started with is kept in memory only: the config's own master/port entries are never overwritten, so restarting mid-transfer still has the original to fall back to. When the expiry passes the client restores that address, clears the key and reconnects. Malformed payloads and zero-day assignments are rejected outright. The way back depends on an expiry time, so honouring a permanent move would strand a host on an address it cannot leave. Give the POSIX connect() a timeout as well (non-blocking connect plus poll, 10 seconds). A blocking connect waiting for SYN retransmission froze the main loop for about two minutes when the port was filtered, delaying both heartbeats and the expiry restore. The transfer state is initialised after daemonize() for the same reason it is logged: logging before the double fork can leave the child deadlocked on the logger mutex. Co-Authored-By: deepseek-flash |
||
|
|
0b22d5e870 |
Feature: Remember the fullscreen and remote-cursor view state on Linux clients
The Linux client always reported zero for ScreenSettings.FullScreen and RemoteCursor and dropped CMD_FULL_SCREEN / CMD_REMOTE_CURSOR on the floor, so a controller could never reopen a host in the state it was left in. The Windows client has done both for a while. Store both fields in ~/.config/ghost/config.conf next to QualityLevel, report them through the TOKEN_BITMAPINFO ScreenSettings, and update them whenever the controller toggles either option. The controller already applies the reported FullScreen in OnInitDialog, so no protocol or master-side change is required. CustomCursor is deliberately not persisted: Linux clients never send cursor images, so the flag would be inert. Co-Authored-By: deepseek-flash |
||
|
|
a628c19341 |
Fix: repaint the remote desktop after a window resize
OnSize only refreshed the cached client rect, letterbox offsets and zoom factors; it never asked for a repaint. Windows invalidates a window only when the client area grows, so restoring a maximized viewer marks nothing invalid. Since the dialog stops erasing its background after the first frame and has no periodic repaint timer, the sole remaining repaint source is a change on the remote screen. A static remote desktop therefore kept the maximized picture - cropped, not following the window - until something moved on the far end. Call InvalidateRect(NULL, FALSE) at the end of OnSize whenever the client area is non-empty, so every size change (restore, fullscreen transitions and interactive resizing) recomputes the layout and repaints once. It is a no-op while the window is hidden; CHideScreenSpyDlg::OnSize calls the base handler, so it inherits the same behaviour. Verified on a Debug build against a live test client: the maximized client (1920x1009) renders 63/64 px side bars and the restored one (717x355) 43/43 px, matching ComputeAdaptiveLayout (renderW=631, offsetX=43). Co-Authored-By: deepseek-flash |
||
|
|
49ba0c4850 |
Fix: keep the floating toolbar open while its quality menu is up
With the toolbar unpinned, CheckMousePosition() runs from the full-screen timer every 50ms and slides the bar out once the cursor leaves the edge band. The quality menu drops from the button's bottom edge, so its first item already sits past the monTop + m_nHeight + 10 threshold: the bar retracted the moment the user moved onto the menu, taking the menu with it. A m_bMenuOpen flag now suspends the retract decision while TrackPopupMenu is running. The menu's modal loop still dispatches the parent's WM_TIMER, so without this the bar animates away under it. The flag is set and cleared around the call, so behaviour is unchanged once the menu closes or is dismissed with Esc. Only the quality menu opens a popup, so nothing else needed the flag. Verified: debug server build, 0 errors, ToolbarDlg.cpp rebuilt. UI not exercised. |
||
|
|
6b87a31c6f |
UI: explain dangerous operations, screen modes and host filtering
Four items from a user-side review of the master. The common thread: the UI
now says what it is about to do instead of leaving the user to guess.
Confirm boxes. Logout, restart, shutdown, delete host and uninstall client
all asked "are you sure" without naming the action or the hosts, so a
multi-selection could not be checked. DescribeTargetHosts() lists
"note (or computer name) (ip)" capped at five lines, and the default button
is No. The preview is dropped before the modal box and targets are
re-resolved after it, since the list can reshuffle in between.
Screen modes. High Speed / Ultra Speed became High Quality (DXGI +
differential: lossless, bandwidth hungry) and Smooth (GDI + H264: lossy,
cheap). TranslateMenu looks menus up by displayed text, so the .rc entries,
the FeatureLimitsDlg item names and the language pack keys changed together.
Host filter. The Ctrl+F bar was find-next; it now filters as you type over
IP, location, note, OS and version, and Esc clears the filter. The status
line reads "filtered: N / M total" while active. Commands still resolve by
clientID and m_FilteredIndices still maps row to m_HostList index, so no
command path changes. SearchBarDlg drops from 446 to 312 lines.
Quality changes. The adaptive level now shows its reason for twenty seconds
("Good (high latency)") instead of silently changing. The full-screen info
bar was a fixed 170px, so that reason was clipped; the width is now measured
from the text with the same font that paints it, 170 becoming the floor and
16px quantisation so changing digits do not jitter the window. Cosmetic
only: no threshold, hysteresis, cooldown or lock-out logic is touched.
Verified: debug server build, 0 errors; new strings present in .res and in
the exe. UI not exercised - the debug master would fight the running release
master for the listening port in Bin/settings.ini.
|
||
|
|
a190c21217 |
Feature: make remote desktop tuning per client
The tuning switches lived in the master's Advanced menu and were saved globally, so two hosts could not use different settings. The client already sends ScreenSettings when a remote desktop starts, so the state belongs there: the four items now sit in the remote desktop window's system menu, directly below Screen quality, and are saved per client. ScreenSettings had a 40-byte Reserved area at offset 56; four bytes became TuningFlags, keeping the struct at 100 bytes with Capabilities at 96. A new Capabilities bit marks a value written by a versioned master; old clients, and new clients never configured, report 0 and are not trusted. CMD_SCREEN_TUNING now ends with a version byte. A five-byte command comes from an older master that does not know the server-only adaptive bit: the client applies those three bits to the session but does not save them. A fresh client starts at 0, so an old master still gets pre-feature behaviour; the new master's 0xE default is persisted on its first session. The per-client master copy stays as the old-client fallback, and the old global [settings] Tuning* keys are honoured when neither exists, so an explicit opt-out survives the migration. Verified on the Debug server with the in-process test client: a fresh client stored 0xE on first use; toggling VBV wrote 0xF to both sides; after deleting the master copy and reopening, the menu restored VBV from the client report. Co-Authored-By: deepseek-flash |
||
|
|
f96e4a7320 |
Fix: recover remote desktop audio after dropped formats and sleep
The client's audio thread starts before the capture thread sends TOKEN_BITMAPINFO, so its first packet - the only one carrying the AudioFormat - reaches the master before CScreenSpyDlg exists and is dropped as an unknown command. Without a format the master cannot open waveOut, and the client re-announced only on an audio off/on, so a remote desktop opened with audio enabled stayed silent until the toolbar button was toggled twice. The master now asks for a re-announce when data arrives with no format on record (CMD_AUDIO_CTRL enable, persist=0, one request per 2 s, 15 attempts max), and the client attaches the format to its next packet. Entering Modern Standby tears down the render endpoint. The client got AUDCLNT_E_DEVICE_INVALIDATED and rebuilt its loopback capture in that same instant; the new client initialized and started fine but was bound to the dying audio engine, so after resume GetNextPacketSize returned zero packets forever without error, and only a fresh screen session recovered. The audio thread now measures its own loop gap (GetTickCount64 plus wall clock, 2 s; a normal pass is ~10 ms) and rebuilds the capture client after the machine was frozen, waits a second after an invalidation, and rebuilds on an audio off-to-on. The master rebuilds waveOut on resume from WM_POWERBROADCAST. The format recovery was verified live; the resume recovery is build-verified and awaits a field check on a sleeping machine. Co-Authored-By: deepseek-flash |
||
|
|
74d64fec87 |
Fix: keep remote desktop audio alive when the playback device drops
Remote desktop audio could stop permanently after an idle period and only came back by closing and reopening the remote desktop. The ring buffer and WAVEHDRs were shared without locking between the IOCP worker thread (OnAudioData) and the UI thread (MM_WOM_DONE): headers were queued twice (waveOutWrite returning WAVERR_STILLPLAYING 33) and the non-atomic m_nRingDataLen underflowed, leaving the buffer "full" of stale data. Audio state is now serialized by a recursive m_AudioMutex, and opening, resetting and closing the waveOut device happens only on the window's UI thread: waveOutReset/Close can re-enter the MM_WOM_* handlers on that thread, and a lock-holding worker would deadlock against the UI thread. Workers post WM_AUDIO_INIT_DEVICE instead. Rebuilds are triggered by format changes, waveOutWrite failures (throttled to 2 s), MM_WOM_CLOSE with a 1 s guard against our own close notices, and a 2-second retry while audio is enabled. Failed header preparation now tears the device down instead of leaving a handle that rejects every write. The client re-creates its Opus encoder when the endpoint channel count or sample rate changes, downmixes more than two channels, and clamps oversized WASAPI packets to the PCM staging buffer. Web audio forwarding still runs outside the lock and is gated exactly as before. Verified by building the Debug x64 server and client; the silence scenario itself was not reproduced at runtime. Co-Authored-By: deepseek-flash |
||
|
|
4884b080e8 |
Improve: default the x264 bitrate cap off and label it for weak links
The cap is capped CRF (VBV): when a frame needs more bits than the profile's nominal bitrate allows, x264 has to raise QP to stay under the ceiling. Scenes with lots of change (video, scrolling, window dragging) therefore lose detail and look blurry, while static scenes stay sharp - the cap only bites on motion. That trade is worth it on intercontinental or otherwise constrained links, where an uncapped frame can take seconds to transmit and stall everything queued behind it, but it is a pure quality loss on a LAN. The tuning item now defaults to unchecked, so a master sends 0x3 (GDI no-sleep and send pacing) by default; machines that already stored TuningX264Vbv keep their explicit choice. The menu entry is renamed to "x264 码率封顶 (VBV,仅限洲际弱网)" and the en_US, zh_TW and de_DE translations were updated to match the new source string. Only newly opened remote desktops pick up the flag, since CMD_SCREEN_TUNING is sent when the session starts. Verified by rebuilding the Debug x64 server and client, and by finding the new menu and translation strings in the built binary. Co-Authored-By: deepseek-flash |
||
|
|
f77b18aa68 |
Feature: run a test client inside the master from the Advanced menu
The Advanced menu now ends with Run Test Program. It copies the kernel payload that was already read into memory, points its CONNECT_ADDRESS at 127.0.0.1:<listen port>, and loads it with MemoryLoadLibrary inside the master process, so this machine comes online as a controlled host -- no second machine is needed to try remote desktop or file transfer. A worker thread waits for the client to exit, then frees the module and re-enables the item. Only one instance runs at a time: the item is grayed while it does, and stopping it means uninstalling the test host from the online list. The loaded copy carries LOCAL_TEST_CLIENT_MAGIC in szFuture. The client uses that mark to refuse the commands that would otherwise hit the host process or the whole machine: uninstall (no self_del), update, run as admin, ban, share/assign, and shutdown/reboot/logoff. It also skips auth-kernel detection, which GetModuleFileName(NULL) would misjudge inside the master. Renames szFututre to szFuture and documents that the first 16 bytes of the reserved tail are now claimed, with a static_assert so it cannot silently shrink below the magic. Translations for en_US, zh_TW and de_DE, plus the HIDE_MENU_RUN_TEST feature flag and its row in the limits dialog. Verified on a Debug master: the item is last and has its icon, one click brings the host online, a second click is refused, uninstall stops it in about a second and the master survives, re-run works, and exiting the master with a live test client takes 2.6s (3.0s baseline). Co-Authored-By: deepseek-flash |
||
|
|
cc9ce35c4d |
Feature: export the built-in TLS certificate from the settings dialog
The built-in certificate lives only inside the server config as base64 DER, so there was no way to take it elsewhere -- to install it as a custom certificate on another machine, or to hand it to a proxy. The TLS certificate dialog now has an Export Certificate button next to the Built-in Certificate checkbox. It is enabled only while that box is checked. Clicking it opens a save dialog and writes two PEM files: the chosen .crt and a .key with the same base name in the same directory. The key is PKCS#8 and unencrypted; the success message says so. If the certificate has not been generated yet (box checked but the dialog not applied), the export generates it first, the same way OK does, then refreshes the expiry text. If the key cannot be written, the certificate written just before it is deleted, so no half pair is left. Translations added for en_US, zh_TW and de_DE; en_US and zh_TW are also embedded resources, so the server was rebuilt. Verified: Debug x64 server builds clean. Drove the dialog on a running Debug instance over window messages -- the button, its label and its enabled state track the checkbox. The PEM writer was checked against OpenSSL (x509 -subject, pkey -check) using the same CryptoAPI flags. The save dialog itself was not automated end to end. Co-Authored-By: deepseek-flash |
||
|
|
6a51116873 |
Fix: repair two quality-switch regressions (monitor jump, H264 stall)
Every quality change restarts the capturer on both sides, and two defects showed up along that path. Monitor jump: on a multi-monitor client the view moved to another monitor. switchScreen=false means "reuse the index", but index is the *next* monitor to switch to, not the one being shown. Track `current` and read it on the non-switch path; the switch path still advances. H264 stall: switching from RGB565/DIFF back to H264 froze the view for up to ten seconds. The client encoder kept its reference frames across the gap, so it emitted P frames the server could not decode until the next natural IDR. It is now rebuilt on the first H264 frame after an algorithm or tuning change. The rebuild is requested with an atomic dirty flag that the capture thread consumes in ensureEncoder(), because resetting the encoder from the network thread raced with encode(). On the server, ApplyQualityLevel() only sets m_bResolutionChanging when the client will really restart the capture: it compares the target maxWidth with the client's reported bitmap width (cached atomically on TOKEN_BITMAPINFO) and stays conservative while a previous resize is still in flight. The fallback timeout drops from 5s to 1s, flushes the decoder and asks the client for a keyframe (COMMAND_SCREEN_KEYFRAME_REQ). Verified: Debug client and server build clean; the 1920-wide High->Good switch no longer waits out the gate. Not yet retested on a live session. Co-Authored-By: deepseek-flash |
||
|
|
d6b04a98f0 |
Feature: throughput criterion for adaptive quality, plus anti-oscillation
Adaptive quality only looked at RTT, so a short RTT over a narrow pipe read as "excellent": at 20-40ms it picks Ultra/High (DIFF/RGB565), both with bitRate == 0, and never steps down. One 1080p RGB565 frame is 4.15 MB -- 1.66s of transmission on 20 Mbps. Adds GetTargetQualityLevelByLoad(): congestion needs both fps < 60% of baseline and bytes/frame still near the nominal bitrate, because a static screen has a near-zero byte rate on any link. Merged with the RTT result as max() -- averaging lets a good RTT mask a narrow pipe. Step-down is 3 confirmations and jumps straight to the level the throughput can carry (capped at +2); step-up stays RTT-only, so the criterion is one-way and the worst case is one level too low instead of a 30s/15s oscillation. Anti-oscillation, all inside the switch: RTT hysteresis (85%/115% dead band against the target level's threshold), failed step-up pinned for 3 minutes, cooldowns 3s -> 10s down / 15s up, counters interrupt each other, and a hard limit of 6 changes per 5 minutes. Server-only, no client change. m_ulBytesThisSecond had to be fixed first: it is accumulated before the switch, so file transfer, audio and clipboard counted as screen traffic; added m_ulScreenBytesThisSecond for the four frame cases. Also gates a real bug in the 10s post-step-down probe that disabled the criterion permanently on a static screen. Default on (same migration caveat as the other four). Unticking takes the original path unchanged. Verified on Debug: 27 hysteresis cases and the load cases pass, menu defaults correct; not yet measured end to end. |
||
|
|
ab83f5d685 |
Feature: persist file manager transfer history
History used to jump to the last directory merely visited, and lived only in memory. Now it is recorded only when a transfer actually starts (the four copy/transfer handlers) and persisted as an MRU list of the last 10 directories in THIS_CFG [file_history], keyed "local" plus one key per clientID. Paths are stored verbatim; '|' joins the list. The history handlers read the head of that list; the rest is kept for the future dropdown. Also translated the four zh_TW status messages, which were still simplified copies. Server-only; no protocol or client change. Co-Authored-By: deepseek-flash |
||
|
|
ca4e85826f |
Feature: remote desktop tuning flags, on by default with per-item opt-out
Adds "Advanced -> Remote desktop tuning" with three independently checkable items, all enabled by default: x264 bitrate cap (VBV) TUNING_X264_VBV 0x1 GDI capture: no slice delay TUNING_GDI_NO_SLEEP 0x2 Send pacing FPS floor TUNING_PACE_FPS_FLOOR 0x4 Unticking an item clears its bit and restores the pre-commit behaviour exactly, so the escape hatch is one click per measure -- no rebuild, no config edit. Each bit is independent; a problem with one does not force turning all three off. Plumbing -------- Menu state -> [settings] Tuning* -> CMy2015RemoteDlg::GetScreenTuningFlags() -> CScreenSpyDlg::SendScreenTuning() (right after TOKEN_BITMAPINFO) -> CMD_SCREEN_TUNING = 178 [cmd:1][flags:4 LE] -> CScreenManager::OnReceive -> m_nTuningFlags -> ScreenCapture::SetTuningFlags Why it is safe to send to old clients: CScreenManager::OnReceive has no default branch in its switch, so an unknown command falls straight out (verified). 178 was unassigned (177 = COMMAND_SET_PROTO, 199 = TOKEN_DECRYPT), and the enum re-anchors explicitly so nothing auto- increments onto it. Flags are sent even when all-zero on purpose: the client's flag lives in CScreenManager, which survives closing and reopening the remote desktop window on the same connection. Without the zero send, unticking the menu would leave the previous flags in effect. Per-measure notes ----------------- VBV: capped CRF (peak = target, 0.5s buffer, init 0.9). The hardware paths already cap via rc_max_rate (1.5x, 1s buffer); this is tighter and only affects x264. After an IDR the buffer drains and takes up to 0.5s to refill, so a brief quality dip follows every keyframe -- if that shows up, relaxing to 1.5x/1s would match NVENC/QSV. GDI: keeps the 50-line BitBlt slicing (large single BitBlts hit driver limits) and only drops the 5ms sleep between slices -- 1080p is 22 slices = a forced 110ms per frame against a 50ms budget at 20fps. Pacing: clamps s0 to 2x the base interval instead of 4x (2fps -> 4fps), taken as max(2x base, 1000/MaxFPS) so it never exceeds the configured MaxFPS. The growth/decay code itself is untouched. This one works against the loop's own congestion signal, so it is the first to untick if a bad link feels laggier rather than smoother. SetTuningFlags only rebuilds the encoder when TUNING_ENCODER_BITS (currently just VBV) changes -- the GDI and pacing bits are read live by the capture and send threads, and rebuilding for them would drop an IDR and visibly flash the picture. Defaults: the on-by-default value lives in the third argument of THIS_CFG.GetInt(), which only applies when the key is absent. A machine that already has an explicit 0 keeps it, so the flip is not retroactive and a test machine can end up with a mixed state. Verified on the Debug build: with no Tuning* keys all three items start checked; unticking VBV alone leaves the other two checked and survives a restart; en_US/de_DE/zh_TW translations all resolve. Not yet measured end to end on a real remote desktop session. |
||
|
|
1e336113a5 |
Feature: trial code can replace an existing licence, plus two UI refinements
三处独立的小改动,都在服务端 UI 层。 1) 试用软件:已有授权码时不再直接拒绝 原来 OnMasterTrail 一发现 settings\Password 非空就弹一句提示然后 return,用户 没有任何办法切回试用模式。现在把提示改成询问「是否更新试用口令?」,选「是」 继续走原有流程(合规声明 → 写 master/BindType/Password/PwdHmac/SN),原有授权 码被覆盖;选「否」保持原授权不变,与改动前行为一致。 2) 语言对话框显示语言包目录 语言选择框下面加一行只读信息:标签 + 可选中复制的只读编辑框。目录存在时显示 GetFullPathName 解析后的绝对路径(配置默认值是相对路径 ./lang,直接显示看不出 实际位置);未设置或目录不存在时显示「内置/预设」,此时只有内嵌的 en_US / zh_TW 可用。 对话框是 DLGTEMPLATE 手工拼的动态模板,.rc 里没有对应资源:高度 75→92、 cdit 4→6、OK/Cancel 下移到 y=67。标签 cx 取 120 而非 55,否则英文 "Language pack folder:"(约 70 DLU)和德语 "Sprachpaketordner:" 会被裁掉; 编辑框带 WS_BORDER,手工拼的控件没有资源编辑器那种默认边框。 3) 远程交谈:没选中主机时不弹确认框 OnChat 原来无条件弹「确定开始远程交谈吗?」,但没选主机时 SendSelectedCommand 的目标列表为空,确认了也发不出去。改为先判断再弹。用 GetFirstSelectedItemPosition 而不是 ResolveCommandTargets:后者要读 m_ClientIndex / m_HostList,网络线程会并发修改,UI 线程裸调不安全,而 SendSelectedCommand 内部本来就持 m_cs 调过一次;这个 API 就是 ResolveCommandTargets 里的同一个判定。m_CtxMenuTargets 判断保留——右键菜单 派发期间目标存在那个快照里,列表选中项可能为空。 三份语言文件各补 3 条译文(含第 1 条的询问文案)。德语沿用 ASCII 化写法 (fuer / ueberschrieben),因为 GBK 存不下变音字母。 已在 Debug 版实测:语言对话框两个分支(路径 / 内置预设)截图确认无裁剪、按钮 在框内;远程交谈未选主机时 PostMessage ID_TALK_MANAGE 后不产生任何窗口。 |
||
|
|
356aa27108 |
Feature: Reject MCP tool calls the target client cannot handle
tools/list 不带参数,无法按目标设备过滤工具列表。60 个工具里有 33 个只在 Windows 客户端上有实现,模型无从得知,只能下发命令后白等超时。 DispatchSingleHostTool 开头按 kToolPlatforms 表核对目标主机平台,不匹配立刻 返回 -32005;批量路径经由同一函数自动覆盖。主机不存在或离线时放行,把 -32002 留给工具自己报,避免同一个问题出现两种错误码。 支持面是刻意设计的阶梯:win 60/60、lnx 27、mac 16、apk 10。60 个工具全部含 win,所以 Windows 客户端永远不会被这道门禁拒绝,行为与改动前完全一致。 平台表按服务端实际放行来标,不按客户端能力标。两处会分叉的地方: - exec_command / terminal_* / kill_process:macOS 客户端有实现(main.mm:753 的 ShellworkingThread、SystemManager 的 KILLPROCESS),但服务端刻意拦着 (McpServer.cpp:3652「macOS 本轮不开放」、6870),故标 win+lnx。 - list_windows:Linux/macOS 的 SystemManager 都有 COMMAND_WSLIST 分支,但 BuildListWindows 把命令发在主连接上,而这两个平台的主循环只处理 COMMAND_SYSTEM (起子连接),WSLIST 只在子连接里才被处理,走不到。实测 Linux 上直接超时 -32001。那两个 case 是给 SystemDlg 用的,故标 win。 copy_files_c2c 是唯一的非对称工具(源端必须 Windows,目标端可 win/lnx/mac, 反向不支持),用 roles 按参数名分别声明,C++ 侧 CollectTargetReqs 对应处理。 配套 mcp/tools.json(60 个工具,version 2)与 tools/mcp_tools/ 下的抓取、生成、 比对、校验脚本。check_platform_table.py 校验 C++ 表、tools.json、instructions 三方一致,并把「Windows 全量」做成不变式。 已在 A6(Windows 11)与 Ubuntu24(Linux)上实测:Windows 侧 14/14 通过且无误拒, Linux 侧 11 项拒绝全部命中门禁,copy_files_c2c win->lnx 成功、lnx->win 被拒。 开关 McpPlatformGuard(默认 1),关闭只失去提前拦截,不影响任何执行路径。 |
||
|
|
8c0351b45b |
fix(server): show UTF-8 process names correctly in the connections dialog
The connections dialog decoded procName with CA2T(x, CP_UTF8). In this MBCS build CA2T expands to CA2A, whose nCodePage argument ATL explicitly ignores (atlconv.h: "(void)nCodePage") - the call just memcpy's the bytes. So the UTF-8 process names sent by the client were copied verbatim into a CString and rendered as GBK: Chinese names turned into mojibake while pure-ASCII names looked fine, since UTF-8 and GBK coincide there. Display via the established pattern instead (same as the client list and the process manager): convert UTF-8 to UTF-16 with MultiByteToWideChar and write the item text with LVM_SETITEMTEXTW, bypassing the ANSI code page entirely. This also keeps Chinese names readable on servers running a non-Chinese ACP. The sort key keeps the raw UTF-8 bytes: byte-wise comparison of UTF-8 equals code-point order, and no characters can be lost in conversion. |
||
|
|
d3c165de79 |
fix(feature-limits): keep flags above bit 31 on 32-bit builds
CCheckListBox keeps its own per-row state in the item data slot and exposes a DWORD_PTR user field inside it, so every flag this dialog stored travelled through a value that is only 32 bits wide in a Win32 build. On a 32-bit server, each menu and context row at bit 32 or above therefore came back as zero: 26 entries in the 主菜单 tab, from 插件请求 to DLL内嵌TLS证书, and 14 in the 右键菜单 tab, from 虚拟屏幕(插件) to 执行代码. Ticking one wrote nothing into the generated master, and reopening the dialog showed it unticked again. The narrowing never produced a warning because C4244 is listed in DisableSpecificWarnings for all four configurations, and the x64 build, where DWORD_PTR is 64 bits wide, was unaffected. Store the row's index into the tab's item vector instead of the flag itself, and have CollectFlags() look the flag up in that vector, so the value never narrows in either architecture. The vector index also survives the compile-time skips in PopulateList and needs no change when the flags grow into a second 64-bit word. Verified by building the Debug server for x64 and x86. Co-Authored-By: deepseek-flash |
||
|
|
c66f410831 |
Feature: Embed the server TLS certificate in delivered DLLs
Add a "高级 → DLL内嵌TLS证书" toggle (off by default, persisted as
[settings] EmbedTlsInDll). When it is on, ReadKernelDll patches the server's
current TLS anchor into the ServerDll and ShellCode payloads, so clients that
come online through the loaders start their own session over TLS without
waiting for an online push. The plaintext DLL loader in client/main.c is
untouched; only the DLL's fresh connection is protected. The write happens
after SetServer and before CalcMD5FromBytes, and the anchor records the host
part of the master address rather than "ip:port" because the client matches
the anchor against its configured address set. TinyRun has no anchor block and
keeps working as before.
Toggling the switch, and confirming the certificate dialog, rebuild the six
payloads in place, so no server restart is needed after a certificate change.
The payload pointers are replaced as a whole, and the network threads that read
them (SendServerDll and TOKEN_GETVERSION) now take a dedicated critical section
for the full duration of use.
COMMAND_UPDATE no longer clears the tls_disabled marker on the client. Now that
any delivered DLL may carry the anchor, "the payload has an anchor" no longer
means the operator opted this host into TLS, and clearing the marker would
silently flip a host that was explicitly set to plaintext onto TLS against a
plaintext path. Re-enabling TLS stays an explicit action through
COMMAND_TLS_ENABLE and COMMAND_SET_PROTO, which still clear the marker.
Menu and notice strings were added to en_US, zh_TW and de_DE, and the embedded
TLS design document records the new switch and the revised update semantics.
The new menu entry also takes a feature-limits slot so a subordinate master
can hide it like every other 高级 item (see
|
||
|
|
8b92f32c47 |
fix(config): stop reads from creating empty registry subkeys
iniFile/binFile::GetCachedKey used RegCreateKeyExA for every access, so a plain GetStr/GetInt on a missing section materialised an empty subkey. CScreenManager's constructor calls LoadQualityProfiles() unconditionally, which reads profile0.. profile5 x4 keys, so every client start left six zero-valued subkeys behind: 126 of them on the dev box, all with zero values. The server's HKCU\SoftwareYAMA\quality key is the same artefact. Split the helper by intent: writes go through RegCreateKeyExA, reads through RegOpenKeyExA. Both still ask for KEY_READ|KEY_WRITE, because the handle cache is shared and a read-only cached handle would make a later SetStr on the same section fail. Also fixes a second bug in SaveQualityProfiles: when a level matched the default it simply continued, so a level the operator reset to default kept the old custom values in the registry and the reset never took effect. Add SectionExists() (open-only, never creates) and write the defaults back when the section already exists. |
||
|
|
454d25d37f |
fix(share): carry the transport in the share and assign payloads
The share payload was host:port:shine and carried no transport at all, so a
shared client fell back to its baked-in protoType. Share instances also skip
ApplyProtoSwitch (ClientDll.cpp:810), so a client upgraded to WSS was shared
to a TLS front end as raw TCP and looped on HTTP/1.1 400.
Extend both payloads with an optional trailing transport field:
share : host:port:shine[:transport]
assign : host:port:days:shine[:transport]
The field is omitted when the source protocol is not TCP/WS/WSS, so HTTP/UDP/
KCP hosts keep their previous behaviour instead of being silently downgraded
to plain TCP.
- server: add SelectedShareTransport(), share it between OnOnlineShare and
OnOnlineAssignTo, and accept a tcp:// ws:// wss:// prefix in the address.
- client: parse the field on both paths and persist the assigned value to
settings/master_transport, clearing it when the field is absent.
- share_list: dedup on host:port instead of the whole record, so re-sharing
a host with a different transport replaces the stale entry.
- assign: guard bToken[_MAX_PATH] against the longer payload.
- lang: translate the reworded prompt and the three new messages in en_US,
zh_TW and de_DE.
Transport is pinned at share time and does not follow a later protocol switch
on the master link; the m_bShared gate stays as-is on purpose.
|
||
|
|
951b4072e5 |
Feature: Embed the master's TLS certificate in generated clients
When the server has TLS enabled, the builder can now bake its certificate into the client it produces, so a distributed client speaks TLS on its very first connection instead of waiting for the anchor to be pushed after a plaintext login. The dialog gets a checkbox (IDC_CHECK_TLS_ANCHOR) that is only enabled for payloads and protocols where an embedded anchor makes sense; the choice is remembered even when the control flips to disabled and back, so switching protocols cannot silently undo a deliberate opt-out. Every label variant stays short enough to fit the 196 DLU field, including the German ones. A template that predates the anchor block no longer aborts generation: it warns, clears the checkbox and produces a plain client, so a master upgraded without rebuilding the ghost/ServerDll resources does not block every build. The certificate lands in a fixed 4 KiB block (magic, version, length, FNV-1a hash, master address, PEM) carved out of the payload at build time. The client reads its trust anchor from four sources in order: the tls_disabled marker, the certificate the server pushed into the registry, a PEM file next to the executable, and finally the embedded block. The embedded block only applies to a connection whose target matches the master recorded at generation time, compared as an address set: an exact string match when only one address is configured, or an intersection of resolved IPv4 addresses otherwise. A transferred, shared or parallel instance falls back to the old plaintext first-connect path instead of pinning itself to a certificate it can never verify. That decision is made per connection, not per process: shared and parallel instances are threads inside a single client process, so a process-wide flag let whichever instance connected first decide for all of them, and the first load of the TLS state cached that answer for good. The TLS layer now keeps two cached states (embedded anchor allowed, and not allowed), picks one per handshake, and reports the anchor source of that handshake for the login capability bit. Matching by resolved address also keeps parallel mode working, where the connection goes to the single IP the domain pool selected while the configured master is a domain or a list. Server side, generated and updated payloads get the block written in place; the client reports the capability bit on login so the console can tell which hosts are already TLS-only on first connect. Loading the anchor decodes every PEM block in the chain rather than just the leaf, and an anchor that exists but fails to load keeps the old fail-closed behaviour. A pushed anchor only reconnects when the transport of the live connection actually changes, judged against that connection's own target rather than the process-wide switch. This was verified end to end against a freshly generated client with an empty registry: the first connection was a TLS 1.2 ClientHello 0.2 s after start, and a four-certificate fullchain loaded all four blocks. Re-verified after the per-connection rework with the anchor block patched into a debug client: with a matching master the first bytes are a ClientHello, with a foreign master the client logs the skip and sends plaintext, and a domain master resolves to the IP it connects to and still matches. A master domain that no longer resolves falls back to plaintext within a second and is not looked up again for a minute, instead of stalling every reconnect on a DNS timeout while holding the lock the certificate verification needs. Co-Authored-By: deepseek-flash |
||
|
|
c4021e1fc9 |
Feature: Ship a built-in TLS certificate so encryption works out of the box
A fresh install used to require openssl before the server could speak TLS: two empty paths in [tls] meant the identity failed to load and every ClientHello was refused. TLS is now on by default and, when no custom certificate is configured, the server generates its own self-signed one the first time it needs it -- RSA-2048, SHA-256, CN=yama-server, CA:TRUE, valid for ten years from one day before now. Plaintext clients are untouched, since the device port still splits plaintext from TLS by sniffing the first six bytes of a connection. The certificate and its PKCS#8 private key are stored side by side in the config under [tls] BuiltinCert / BuiltinKey as single-line base64 DER. Single line, because the server has two config backends -- the registry for Release, settings.ini for a Debug master -- and only a line without newlines means the same read/write code serves both. That in turn required fixing the registry reader: iniFile::GetStr copied into a 512 byte stack buffer, so a 1.5 KB value came back as a truncated or empty string. The two-phase dynamic read now lives in common/iniFile.h as ReadRegistryValueSz / ReadRegistrySz, and the copy that client/TlsChannel.cpp had been carrying for its own trust anchor is gone. This also makes the built-in certificate self-checking: Ensure() re-reads what it just wrote and fails loudly if the round trip did not survive. Import has to go through NCRYPT_PKCS8_PRIVATE_KEY_BLOB, matching the import path in BuildIdentityFromDer. NCRYPT_PKCS8_PRIV_KEY_INFO_BLOB, which most samples reach for, is not implemented by the Microsoft Software KSP and returns NTE_INVALID_PARAMETER; a probe confirmed it, and the export type that works is the one the importer already expected. Building an identity is now split into a file front-end (PEM, fullchain, PKCS#1 hints) and a shared DER core, so the built-in and file paths cannot drift apart. That key also exposed a second problem worth fixing here. The identity binds its private key to the certificate by name -- CRYPT_KEY_PROV_INFO with pwszContainerName -- and Schannel resolves that name on every handshake through CryptAcquireCertificatePrivateKey. With the fixed name "YamaServerTlsKey", two server processes under the same Windows user shared one key slot: whichever loaded last overwrote it, and the other process's next handshake picked up a private key that does not match its certificate. That is exactly the debug-plus-release pairing used here, and defaulting to a built-in certificate is what makes it reachable, since the debug instance no longer points at the same PEM as the release instance. The name is now the base name plus the first six bytes of the certificate's SHA-1 thumbprint, e.g. YamaServerTlsKey-c0d469eae8a4: different certificates get different keys, instances sharing one certificate still share one key. MCP picks this up too. The effective name goes to the trace log so a collision is visible without a debugger. A stale key from an older build may still sit in the key store under the old name; nothing references it and it is not deleted automatically, since a running instance of an older build could be using it. The trust anchor still has to be pushed. The client pins exactly one root through an exclusive-root chain engine and checks no host name, so a self-signed CA:TRUE leaf chains cleanly to itself -- but only if the client is told about it. That is the existing 启用 TLS / 切换到 WSS command, which now takes the PEM from ServerTlsIdentity::AnchorPem instead of re-reading the configured cert file, so it reports the same certificate the server actually serves for both sources. Losing the stored certificate (cleared registry, new Windows user) regenerates it, and every client must be re-pushed the anchor. Two places that used to fall back to [tls] CertPath now skip that fallback while the built-in certificate is active: the MCP HTTPS front end at startup and the prefill in its settings dialog. A self-signed certificate cannot pass validation at a public MCP client, and the retained CertPath is only a leftover from switching back to a custom certificate, so pretending to use it would fail later with a worse message. MCP HTTPS with empty paths already fails closed with a log line. The TLS dialog gains a 内置证书 checkbox, ticked by default and unticked when certificate paths are present; ticking it greys out the path rows without clearing them, and shows either "generated on first use" or the expiry date read back from the stored certificate. Saving writes four keys -- Enabled, UseBuiltIn, CertPath, KeyPath -- and an explicit UseBuiltIn keeps the paths from being used as an implicit switch. Every reader of [tls] Enabled now defaults to 1, so the menu check, the dialog and the loader agree on a fresh install. The status bar panes on 无 / 有 grew a third state, 内置, and the pane width is measured across all three. Translations were added to en_US, zh_TW and de_DE; skipping the German file would have left the new dialog text in Chinese there, as de_DE is loaded from disk rather than embedded. Verified with the debug server against openssl s_client. Both the generated built-in certificate (CN=yama-server) and an existing custom one (CN=localhost) complete a TLS 1.2 handshake with the pinned certificate, and their log lines show distinct key names, c0d469eae8a4 and 272f2adfb19c. An unmodified client still runs in plaintext without an anchor, an existing custom certificate deployment behaves exactly as before, and client and server both build clean at Debug x64. Co-Authored-By: deepseek-flash |
||
|
|
4f9bfb0fdc |
fix(server): stop two remote-input paths from killing the server
Both bugs let a remote peer terminate the server process: the first needs no credentials at all, the second needs only a malicious client. 1) cpp-httplib 0.14.3 -- unauthenticated DoS via Content-Length Content-Length was parsed with strtoull, which accepts a leading sign, so "-1" wrapped around to ULLONG_MAX. read_content then treated that as an oversized body and called skip_content_with_length(strm, ULLONG_MAX), a loop that only exits after consuming 18 EB -- a client trickling bytes never trips the read timeout, so the worker thread is stuck forever. With ThreadPool(32) that is 32 connections to wedge the whole server. Body parsing runs before the MCP token check, so no token is required. Backported from upstream 0.51.0/0.64.0 as parse_content_length_strict(): only plain decimal digits are accepted and overflow is rejected. Upgrading the library instead is not possible -- 0.25.0+ requires _WIN32_WINNT >= 0x0A00 (Win10) while this project targets 0x0602 (Win8), and the last Win8-compatible release (0.20.0) predates the fix. Verified: negative, leading-plus, overflow and trailing-garbage values now all return 400; 40 concurrent "-1" requests are rejected in under 50 ms with the thread pool still healthy; plain and chunked requests are unaffected. 2) HideScreenSpyDlg::JPG_BMP -- malformed JPEG terminated the process The decoder was set up with libjpeg's default error_exit, which calls exit(EXIT_FAILURE). Since the input is a JPEG stream sent by the remote client, one structurally invalid frame killed the whole server. Replaced with a setjmp/longjmp handler that turns fatal errors into "return false", matching this function's existing failure paths. Warnings still go through emit_message, so truncated-but-recoverable images behave exactly as before. Verified against 36 malformed samples: 19 used to terminate the process, none do now (the same 19 return false), and valid JPEGs decode identically. 3) Drop the dead file_server.h An older HTTP file-serving implementation, superseded by WebService.cpp and referenced by nothing: no include anywhere, no instantiation, no entry in the vcxproj or any build script. Removing it keeps the real HTTP attack surface -- httplib's /mcp plus WebService -- unambiguous for anyone auditing this code. |
||
|
|
8807321f1d |
Feature: Bring feature limits in line with the current menus
The "feature limits" dialog offered by 主控生成 had drifted well behind the UI: a whole 高级 menu, five toolbar buttons and a couple of dozen context menu entries could not be restricted at all, and several items were listed under names that no longer appear anywhere. The three tabs now follow the real resources. Menu items are listed in the order of IDR_MENU_MAIN and carry the same text minus accelerators; the toolbar covers all 19 IDR_TOOLBAR_MAIN buttons; the context menu lists the nested 实验功能 / 客户管理 / 远程控制 / 机器管理 / 客户代理 / 执行程序 entries individually and the two runtime-built ones (协议切换, 执行代码) as groups. That makes 57 / 19 / 46 items, each with its own bit; new bits were added at the end of each field so the existing positions stay put. Enforcement was extended to match, and while wiring it up one long-standing bug surfaced: DeleteMenu(MF_BYCOMMAND) only reaches items of the menu it is called on, so hiding an entry of a nested popup had always been a no-op. Nested items are now deleted through their own submenu handle, and a popup whose items are all hidden is removed together with its parent entry, so no empty popup is left behind. 协议切换 is inserted relative to where 实验功能 ended up, which keeps it next to it either way; 执行代码 is simply skipped when restricted. The missing labels were added to en_US, zh_TW and de_DE. Co-Authored-By: deepseek-flash |
||
|
|
559681ea01 |
Feature: Show TLS and MCP state in the server status bar
The main window's status bar now carries two short panes between the host count and the FRP address. The first reports whether the server identity is loaded, using the same ServerTlsIdentity::IsReady() check the rest of the UI uses, so a menu that claims TLS is on cannot leave the bar saying otherwise when the certificate failed to load. The second reports whether MCP is enabled and, while it is, which protocol the endpoint speaks: (HTTP) or (HTTPS) according to McpHttps. Both panes follow the existing 60 second statistics tick, and toggling either switch in its dialog refreshes them at once instead of leaving the bar stale until the next tick. Pane widths are measured from the widest text each pane can show in the current language instead of hardcoded pixels, and the measurement selects the status bar's own font: DEFAULT_GUI_FONT is about 8% narrower than the Segoe UI the bar paints with, which would have clipped "MCP: ... (HTTPS)" at higher display scaling. Switching HTTP/HTTPS keeps the column width steady, and turning MCP off lets it shrink again. The MCP settings dialog was also missing translations for several of its labels, the file write switch among them, which is why they stayed Chinese in the English UI. Those keys, together with the status bar ones, are added to all three language files. Co-Authored-By: deepseek-flash |
||
|
|
e99092ca70 | Release v1.4.2 | ||
|
|
ebc2d03290 |
fix(web): keep the IME bar still and the pointer honest in portrait
Two separate faults showed up once the "I" shortcut was in use in portrait: the
phone input bar would not stay put, and the pointer stopped being where it
claimed to be.
#ime-bar was the last flex child of #screen-page, so it sat at the bottom of the
page, and the only thing keeping it above the keyboard was adjustImeBar()
writing padding-bottom on #screen-page -- the bar chased the keyboard height
frame by frame through visualViewport. The keyboard animation is asynchronous
and the events lag behind it, so while it rose the bar was still low with the
keyboard already covering everything from y=544. A later attempt clamped it
against keyboardTopY() and reserved the last measured keyboard height before the
keyboard arrived. That kept it visible, but the bar still moved whenever the
keyboard changed height -- switching input method, the QuickType row, the
AutoFill Contact chip appearing or going away -- and that is what "the input box
keeps getting pushed up" actually was.
The bar is now a fixed overlay at the bottom edge of the picture, placed by the
same formula the shortcut row already used: picture bottom + 4px. In portrait
adjustImeBar() has nothing left to chase -- it only clears the padding that
landscape may have left behind, and recomputes when the keyboard top changes.
That recompute is idempotent and the style is only written when the value
differs, so in the normal case it produces no movement at all. lastKbHeight,
KB_HEIGHT_GUESS, noteKeyboardHeight() and the old keyboard-top tracking are gone
with it.
One clamp survives, as a safety net: if the picture bottom is itself inside the
keyboard block -- a remote machine that is portrait, where the picture is taller
than the space above the keyboard -- the bar falls back to the keyboard top,
because there is nowhere else to put it. That case also has to follow the
keyboard, which is why the recompute above still exists. For a landscape/16:9
remote the clamp never fires and the position is a constant.
Getting that constant right needed a coordinate fix. #ime-bar hangs off
#screen-page while #input-shortcuts lives inside .canvas-container, so the two
have different containing blocks. Reusing the shortcut formula
(canvas.offsetTop + ...) put the bar a whole toolbar height too high -- 279
against a picture that ends at 319 -- which is why it always looked like it was
floating above the shortcut row. The bar's position now comes from the canvas
rect minus the #screen-page rect, so the containing block is whatever the bar
actually resolves against; that subtraction also cancels the translateY
compensation, since both rects are inside the translated element. It lands at
323..382, 4px under the picture.
Landscape keeps the flex behaviour via (orientation: landscape). That is not
just tidiness: an absolutely positioned child does not take padding into
account, because bottom: 0 resolves against the padding box, which includes the
padding. Left as an overlay, the bar would have stayed at the very bottom of the
screen and been covered by the keyboard instead of being pushed up by
padding-bottom.
Opening the keyboard must not move the picture either, and two things were
moving it:
- #screen-page had no overflow guard. #term-page already carries one for exactly
this reason ("stop iOS from quietly adding a scroll to body and lifting the
whole page"). Without it iOS hands the page a scroll and then scrolls it once
the keyboard comes up.
- Even with the page locked, iOS moves the *visual* viewport up when the keyboard
appears (visualViewport.offsetTop > 0). #screen-page is position: fixed and is
therefore pinned to the layout viewport, so the entire page -- picture
included -- was pushed off the top of the screen.
So #screen-page gets overflow: hidden + overscroll-behavior: contain, and
syncVisualOffset() translates it by exactly visualViewport.offsetTop to cancel
the shift. It is driven by the IME rAF loop and the viewport scroll event, and
clears the transform once the offset returns to 0. Nothing downstream has to
compensate for it: the picture, the pointer overlay and the bar are all
descendants of #screen-page, so they move with it.
The pointer overlay was the one thing that did not accept that. .cursor-overlay
was position: fixed, placed by taking the canvas's getBoundingClientRect() and
then subtracting whatever translateY the page currently carried -- two
independent sources of truth that have to agree exactly, the browser's idea of
where the canvas is and our own idea of how far we moved it. They do agree in
desktop Chrome, which is why the harness never saw the fault, but on the phone
they did not: once the IME was open the overlay was drawn off by the
compensation amount while taps still landed correctly, and closing the input box
-- offsetTop back to 0, transform gone -- put it back. The overlay is now
position: absolute inside .canvas-container, the same containing block the canvas
resolves against, and style.left/top hold canvas-local CSS pixels (bx/kx, by/ky).
No viewport rect, no compensation term: whatever an ancestor does to the picture,
it does to the pointer. pageShiftY() is gone with it.
The overlay also has to follow a re-fit, not just a move. resizeScreenCanvas()
keeps the last remote coordinate the overlay was placed at and replays it once
the bitmap has been resized, so the keyboard shrinking the layout viewport, a
rotation or a fullscreen toggle no longer leaves the pointer where the previous
geometry put it.
The touch mapping and the drawing path have to stay exact inverses --
positionCursorOverlay() turns remote coordinates into a position on the canvas,
screenToCanvas() turns a finger position back into remote coordinates -- otherwise
the cursor is drawn where nobody tapped. It was only after the keyboard had been
up for a while that this broke: switching the input method changes the keyboard
height, iOS pans the visual viewport to keep the focused textarea visible, and
from then on offsetTop is non-zero.
iOS also stacks a row of its own directly above the keyboard: the QuickType
predictions and, when Safari decides the field looks like it can take contact
info, an "AutoFill Contact" chip. The textarea gets the full set of suppression
attributes (autocomplete, autocorrect and autocapitalize off, spellcheck off,
inputmode text). That lowers the odds of the chip showing up at all, but iOS
does not promise to honour it -- the only guaranteed off switch is Settings >
Safari > Autofill > Use Contact Info, which is a per-device setting.
With the bar no longer able to hide under the keyboard, the shortcut row below
the picture is only in the way: that row exists to be tapped *before* the IME
opens, and while the IME is open the bar takes its place. Opening the IME now
hides it, so the bar sits 4px under the picture instead of queuing up below the
row. The class lives on #screen-page rather than being stripped off .visible,
because updateUIForOrientation() recomputes .visible from keyboardOpen and would
put the row straight back. Closing the IME -- the bar's own collapse button does
that -- or disconnecting restores it. The key buttons it holds stay reachable by
reopening the mobile keyboard, which is what showed the row in the first place.
The bar also has to exist only while the keyboard does. Tapping it is what wakes
the keyboard in the first place, and iOS then scrolls the page to keep the
focused field visible -- which is the "tap the input box and it shoves itself up"
report. updateImePresence() runs in the IME rAF loop and puts .ime-waiting on the
bar the moment the keyboard is not up -- opacity 0, so it is not there to touch
-- and closeIme() 450ms later once the keyboard has really gone. Two deliberate
choices in that CSS: it is opacity, not display or visibility, because the
textarea has to stay in the document and focusable or the keyboard never comes
up at all; and there is no pointer-events: none, because that would let touches
on that strip fall through to the canvas and become stray clicks on the remote
machine. The wait for the keyboard to appear is capped at 3000ms, after which the
IME is abandoned rather than left invisible forever. It is generous on purpose:
iOS sometimes does not update visualViewport until something scrolls, and a short
timeout would close a perfectly good IME on a slow device.
The RDP reset button redraws the whole frame, but it left the IME open. The bar
stayed on screen, so touching its textarea brought the keyboard back up -- and the
page got shoved again, with the pointer going with it. Reset now closes the IME
first. Since "close the IME" was being spelled out in three places (the I button,
the keyboard toggle, disconnect) and each copy had drifted a little, it is now one
closeIme() that toggleIme(), toggleKeyboard(), sendRdpReset() and disconnect()
all call. The cleanup half runs unconditionally -- imeMode and the DOM can fall out
of sync and a half-closed state is exactly what leaves a bar that pops the
keyboard -- while updateKeyboardButtons(false) is guarded by whether the IME was
actually open, so resetting with only the mobile keyboard up does not close it.
disconnect() additionally keeps its own updateKeyboardButtons(false), because
there the keyboard should close regardless, and it no longer needs to reset
imeMode by hand -- which also stops imeWatcher's rAF loop from spinning on after
a disconnect.
Deselecting the mouse (the control toggle) now drops the keyboard and the IME as
well, for the same reason: leaving the bar on screen means the next touch on its
textarea brings the keyboard back up and shoves the page. Closing only the IME
would not be enough here -- the mobile keyboard is a separate focus -- so
closeKeyboardAndIme() blurs both and is what the control toggle and disconnect()
now share.
Verified with visualViewport.height mocked so the keyboard arrives after the bar
has been placed, on 390x844 and 375x667, with a 16:9 and a portrait remote, at
keyboard heights 0/216/260/300/304/344. For the 16:9 remote the bar is 323..382
at every single step -- zero jump across the whole sweep, where the portrait
remote used to jump 300px. For a portrait remote it tracks the keyboard top
(485..544 at 300px), the only position available to it. No case leaves the bar
under the keyboard, and every measured position equals min(picture bottom + 4,
keyboard top - bar height) to 0.0px.
The bar is present exactly when the keyboard is, checked at every step: on tap
(before the keyboard rises) opacity 0; keyboard up, opacity 1; keyboard down 60ms,
opacity 0 again; 580ms, imeMode false and display none. Reopening with the keyboard
never arriving keeps it at opacity 0 and gives up after 3s. No page errors.
Picture placement across all five layouts is byte-identical to before the change.
Cursor accuracy is dx=dy=0 over portrait/landscape x scale 1/2/3 x offsetTop
0/150/200/300, and the round-trip test -- positionCursorOverlay() asked where to
draw, that screen position fed back through screenToCanvas() -- returns the
original remote point for all nine cases; before the inverse fix six of them were
off, by exactly offsetTop scaled into remote pixels (739 at offsetTop 150 for the
(1800,1000) point).
Tapping RDP reset with the IME open (keyboard mocked at 544, visualViewport
offsetTop at 200) leaves imeMode false, the bar display:none, the transform
cleared, visualOffsetY 0 and the watcher stopped, with the picture still at
y=100..319.4 instead of being shoved up; disconnect() from the same state clears
it identically. Deselecting the mouse from that same state (control on, mobile
keyboard focused, IME open, keyboard mocked at 544 and offsetTop at 180) leaves
controlEnabled false, imeMode false, neither element focused, the bar
display:none, the transform cleared and the watcher stopped, with the picture
still at y=100..319.4. Opening the IME moves the bar from the shortcut row's slot
to 323..382 and closing it puts the row back at 321..369, through both toggleIme()
and a direct class toggle. In landscape the flex path still works: with a 200px
padding the bar goes from 331..390 to 131..190, i.e. just above the keyboard.
The pointer was a second, unrelated bug, and a worse one. screenToCanvas() added
visualViewport.offsetTop on top of a clientX/clientY that is
already expressed in the same coordinate space as getBoundingClientRect(), i.e.
after the translateY compensation. Both quantities include the pan, so subtracting
them already cancels it; adding offsetTop counted it twice. That pushed every
computed remote y down by offsetTop scaled into remote pixels -- 492 remote pixels
at offsetTop 100 on a 16:9 remote -- so everything below the middle of the picture
overshot streamH and was clamped to streamH-1. The symptom is exactly what it
looks like: the pointer can only be moved in the upper part of the picture, a
fixed horizontal band cannot be crossed downwards, and clicking inside that band
lands on the remote taskbar. At offsetTop 300 the whole picture mapped past the
bottom, so every touch landed on the taskbar. The pinch origin had the same
mistake, and so did the cursor recomputation at the end of a pinch, which fed the
overlay's style.top -- a pre-compensation coordinate -- back into screenToCanvas.
Neither direction may add the compensation, and neither does: clientX/clientY and
getBoundingClientRect() are already in the same space, and the overlay no longer
works in screen coordinates at all. The round-trip test had been written against
the wrong premise -- it fed style.top straight into screenToCanvas() -- so it
kept passing while the absolute mapping was wrong. It now converts the overlay's
style values back through the canvas rect on the way in.
Verified against the picture's own rect rather than against the other function:
for points at 10/30/50/70/90/99% of the picture height, screenToCanvas() must
return the remote pixel that sits under that point. At offsetTop 0/100/300 all
eighteen cases are exact (error 0,0); before the fix, offsetTop 100 was off by
+492 on every point and the lower half clamped to 1079, and offsetTop 300 clamped
the entire picture to 1079. The overlay still renders where it should -- for a
pointer driven to the remote bottom it lands 4px above the picture's bottom edge,
the constant hotspot offset, at offsetTop 0 and 300 alike -- and the round-trip
test still returns the original remote point for all nine cases once the
transform is accounted for. With the overlay anchored to the canvas it holds that
alignment through the whole IME lifecycle: dx=dy=0 at offsetTop 0, 200 and 300, on
both a 16:9 remote in portrait and after rotating to landscape and back, and the
pointer lands back on the picture after the IME closes. The rotation case also
covers the re-fit path: the container changes size, the canvas is resized, and
the overlay is replayed at the new geometry instead of staying where the old one
put it.
Co-Authored-By: deepseek-flash
|
||
|
|
0a6cbbbf06 |
fix(web): draw the remote screen inside a fixed canvas to kill the iOS ghost lines
On an iPhone in landscape, panning the picture to the left with two fingers left
a stack of 1px vertical lines along the right edge. It only showed up after
zooming in, and every pan added more lines.
The cause is the old render model, not the panning code. #screen-canvas was
sized to the remote resolution and then moved/scaled with a CSS transform
(`canvas.style.transform = scale(s) translate(tx, ty)`). iOS Safari caches the
raster of a transformed canvas layer and does not repaint the strip the layer
uncovers when it moves, so whatever sat at the old right edge -- one column of
the picture -- got stretched across the newly exposed band. Pan again and the
next column repeats it: the lines accumulate.
An earlier attempt clamped the pan range so the uncovered band could not appear.
That was wrong twice over: it did not remove the ghosting (the clamp still moved
the layer, so the edge was still repainted from a stale raster), and it put hard
limits on dragging, which is not how the page is used.
So the canvas element now never moves. It is pinned to the container
(bitmap = viewport x devicePixelRatio, driven by a ResizeObserver), and every
frame is drawn into it with ctx.setTransform. There is no CSS transform, no CSS
scaling, and no layer movement left to cache, so there is nothing to leave a
stale edge behind.
- renderFrame(): paints black, then draws the latest frame with the fit-to-view
and pinch-zoom/pan transform applied via setTransform.
- initDecoder(): keeps the remote-resolution frame in an offscreen frameCanvas.
The isTopDown flip is applied to that canvas only, so the visible canvas is
always upright and no longer needs a flipped transform.
- positionCursorOverlay() / screenToCanvas(): rewritten as exact inverses of the
new transform chain, so the cursor overlay and touch coordinates still land on
the right remote pixel.
- applyZoomTransform(): drops the CSS transform and every pan clamp. Dragging
past the picture just shows the canvas' own black background, with no boundary
at all -- the free panning feel is unchanged.
- Touch/mouse deltas are converted with remotePerScreenPx() instead of assuming
the old element size.
The picture also has to land exactly where it used to. In the old model the
canvas element *was* the picture, so the flex container positioned it: portrait
CSS sets `.canvas-container { align-items: flex-start; padding-top: 56px }` to
pin it to the top and keep the on-screen keyboard off it, landscape leaves it
centred. Now that the picture is drawn inside a full-bleed canvas, flex no
longer positions it, and hard-coding "centre" dropped it 262px in portrait --
straight into the keyboard's path. So renderFrame takes its vertical placement
from the container's computed align-items and padding-top, and the canvas covers
the padding box so a zoomed picture panned upwards still reaches the top of the
container the way it used to.
The zoom anchor had the same problem: originX/originY were read as percentages
of the canvas, while the old transform-origin sat on the canvas element, i.e. on
the picture. They are percentages of the picture now, so pinch-zoom keeps the
point under the fingers fixed instead of drifting towards the canvas centre.
Two smaller details have to be right for the mapping to stay exact, and both are
fixed here rather than left for later:
- resizeScreenCanvas() takes its scale factor from the bitmap it just allocated
divided by the measured CSS width, not from devicePixelRatio. The bitmap is
rounded, so with a fractional CSS width or a non-integer ratio the two drift
apart -- 843.5px at dpr 2.625 lands 2.2e-3 apart -- and translateX, which
reaches a few hundred px, turns that into a ~1px mismatch between the picture
and the cursor overlay. getViewMetrics().d is now identically equal to the
kx reported by canvasPixelRatio().
- updateInputShortcutsPosition() divides the picture height out of streamH, which
is 0 before the first frame; it now bails out instead of placing the shortcuts
bar in the middle of the canvas box.
Nothing else reads the canvas dimensions, so the semantic change from "remote
resolution" to "viewport x dpr" does not reach any other feature: there is no
toDataURL/getImageData anywhere, the wall tiles own their own canvases and go
through wallHandleFrame, the cursor overlay is a fixed 24x24 element that never
scaled with the old CSS transform either, and the wheel/dblclick handlers only
forward coordinates. The overlays that sit on top of the canvas (quick controls
100, shortcuts 101, android navbar 102, cursor 1002) all carry a z-index, so
making the canvas positioned does not push it over them.
Verified in a browser harness built from the same functions the page uses:
drawing position vs cursor position over 90 fully-visible cases is off by at
most 0.42px, the screen->remote->screen round trip over 1500 points is exact to
0.000px, a real two-finger gesture chain (scale 1 -> 2.5, translateX -145) moves
the picture correctly with no page errors, and across dpr 1.5/2/2.625/2.75/3 the
bitmap ratio matches the CSS ratio exactly (round-trip error 7e-4px, float
noise). Picture placement was diffed against the previous build in five layouts
(portrait, portrait fullscreen, Android immersive, landscape, landscape
fullscreen) and matches to 0.0px in every one; a portrait zoom of 2x panned up
by 150px shows the same visible band (y 44..128) as before; with the viewport
shortened to simulate the keyboard the picture stays at y 100..319 and is not
covered; pinch anchors at 25%/50%/80% of the picture stay put to 0px across
scale 1.5/2/3. The user confirmed on the device that the lines are gone.
Co-Authored-By: deepseek-flash
|
||
|
|
36ae4b3057 |
fix(client): stop the reconnect loops from spinning when the master restarts
On a master restart the client receives SERVER_EXIT and KernelManager sets
g_bExit = S_SERVER_EXIT. IsClientAppRunning() compares against S_CLIENT_NORMAL,
so it flips to false immediately and the worker starts tearing down -- but
g_bThreadExit is only cleared at the very end of StartClient. Throughout that
window TestRun() still sees IsThreadRun() == TRUE and takes its early-return
path.
The loader's reconnect loop deliberately does not wait in the S_SERVER_EXIT case
("reconnect immediately, do not wait for share instances"), and its else branch
was empty, so it re-entered TestRun() with no delay whatsoever. Measured on a
live host: 919 identical "TestRun SetServer[91.99.165.207:443]" lines inside a
single second, 960 on its second instance. The client ring buffer holds 1000
lines, so that burst erased the entire history -- which is why nothing from
before the restart could be inspected afterwards. IsStoped() cannot gate this:
it returns true unconditionally while g_bExit == S_SERVER_EXIT, conflating
"worker exited" with "master restarted".
- test.cpp: sleep 20ms in the S_SERVER_EXIT branch. The sleep runs concurrently
with the worker's teardown rather than after it, so reconnecting is delayed by
at most one 20ms tick.
- ClientDll.cpp TestRun(): log only when SetServer() reports the address really
changed. It returns false for a null address, which also silences AutoRun's
TestRun(NULL, 0) calls. Nothing is lost: the restart itself is already logged
as "======> Server exit" in KernelManager.
- ClientDll.cpp AutoRun(): its do/while had no sleep either. Gate it on "still
in S_SERVER_EXIT and a worker is still running" so the normal path stays
zero-delay.
Together these turn a burst that wiped the log buffer into silence, and cap the
loop at 50 iterations per second instead of roughly 900. A worker that hangs
during teardown still burns a core; curing that needs the thread-alive state
exposed separately from IsStoped(), which is an interface change and is left out.
Co-Authored-By: deepseek-flash
|
||
|
|
cbb84809d8 |
fix(server): bind context-menu commands to the hosts the menu was opened for
The host list is a virtual list (LVS_OWNERDATA), so its selection is stored as row indices. m_HostList is reordered underneath those indices: ApplySort() sorts it in place on every TIMER_REFRESH_LIST tick, and RemoveFromHostList() erases entries as hosts go offline. TrackPopupMenu runs its own modal loop, which keeps dispatching WM_TIMER, so by the time the user clicks an item the row numbers have already shifted. Every command handler resolves its targets at click time with GetFirstSelectedItemPosition() + GetContextByListIndex(), a pure row lookup (m_HostList[m_FilteredIndices[row]]), so a menu opened for host A could act on whichever host now occupied that row. Snapshot the selected clientIDs before the popup and restore the selection to their current rows when it returns, dispatching the command ourselves through TPM_RETURNCMD so the restore happens first. CMenu::TrackPopupMenu is not used for this because its return type is BOOL, which would truncate the command ID. Restoring the selection alone is not enough. A dozen handlers pop a confirmation or input dialog before resolving their targets, and that modal pumps WM_TIMER too, so the selection drifts a second time. Keep the same clientID snapshot in m_CtxMenuTargets for the duration of the dispatch and let ResolveCommandTargets() prefer it over re-reading the selection. Every lookup revalidates GetClientID() against the row it landed on, so a stale index skips the host instead of acting on a different one, and hosts that went offline while the menu was open are dropped rather than guessed at. The snapshot is saved and restored around the dispatch so a nested popup cannot clobber the outer one. SendSelectedCommand, ShouldRemoteControl, SwitchSelectedProtocol, OnOnlineDelete, OnOnlineUninstall, OnOnlineHostnote, OnOnlineRunAsAdmin, MachineManage and ProxyClientTcpPort now resolve through it. Handlers that show no dialog before resolving (OnMainProxy, OnOnlineAddWatch, OnOnlineInjNotepad, OnOnlineLoginNotify, OnOnlineActiveWnd) keep reading the selection directly. Co-Authored-By: deepseek-flash |
||
|
|
96f1bacd43 |
fix(client): use GDI capture when the session has no interactive desktop
A host whose DXGI initialisation hangs never opens the remote desktop window at all. WorkThreadProc runs InitScreenSpy() and SendBitMapInfo() back to back, so a capturer that never finishes constructing means TOKEN_BITMAPINFO is never sent, and the master - which only opens the window on that token - waits forever. On the affected Server 2022 box the screen thread stopped right after logging its type and algorithm, printing neither the DXGI init summary nor the existing "DXGI SPY init failed" fallback, so it was stuck inside the capturer constructor; a healthy machine on the same build reaches the summary in under a second. Six clicks left six stuck threads, each holding a D3D device. DXGI desktop duplication needs a display to duplicate. With no interactive desktop it can return no frames at best, and on some drivers it never returns from the initialisation calls at all. BitBlt has no such dependency and keeps working, which is why switching the screen type to GDI made the same host connect. Detect that up front and pick GDI instead of relying on a hang to be survivable: - IsWorkstationLocked() - the input desktop is Winlogon. Moved out of CKernelManager into Manager.cpp so the capturer can use it too; the manager keeps its private wrapper for the "Locked:"/"Inactive:" activity string. - IsCurrentSessionDisconnected() - the process's own session is WTSDisconnected. That is the state the reported host was actually in: its client runs in session 2, which was disconnected, and the desktop only came back after the master's "RDP session reset" ran tscon. Session 0 has no disconnected state and is left alone. Either condition means the same thing for capture, so both route to the plain GDI capturer. An active session keeps DXGI untouched, so hosts that work today are unaffected; the new log line names which condition fired. Co-Authored-By: deepseek-flash |