v1.4.3
453
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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 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 |
||
|
|
6a3d536d38 |
fix(server): keep the build dialog's default protocol at TCP
Commit
|
||
|
|
389de9d456 |
fix(client): fall back to GDI capture when DXGI duplication yields no frames
Some environments never deliver a frame from IDXGIOutputDuplication::AcquireNextFrame: headless or virtual displays, Session 0 desktops, and drivers that do not push duplication notifications. It returns DXGI_ERROR_WAIT_TIMEOUT forever, even while the desktop is changing. Consequences: - The first screen could not be captured, so the server kept showing "Please wait..." because m_bIsFirst was never cleared. - Adding a GDI fallback for the first screen alone was not enough: the picture appeared but then froze, because ScanNextScreen still polled DXGI and always got nothing back, leaving the encoder without input. Fixes: - Add CaptureByGDI(), which grabs a frame with GetDC(NULL) + CreateDIBSection + BitBlt. GDI does not depend on desktop changes, which is why the plain GDI capture path always worked in these environments. - When the first screen cannot be obtained from DXGI, capture it with GDI and mark the whole session as GDI (m_bGDIFallback = true), releasing the duplication object. All later frames then go through GDI so the picture keeps updating. - Normal machines are unaffected: if DXGI delivers the probe frame or the first screen, the flag stays false and the GDI path is never entered. This also avoids mis-detecting a momentarily static desktop as a broken duplication, which a plain timeout counter would do. - Create the GDI offscreen DIB lazily and reuse it (m_hGdiMemDC, m_hGdiBmp, m_pGdiBits). The fallback is a per-frame path, so allocating and freeing about 15MB every frame would cause visible jitter. - Reuse m_BitmapInfor_Full for CreateDIBSection instead of building a second BITMAPINFO: it is already 32bpp BI_RGB with a positive height (bottom-up) and matches the surface size. - Guard the GDI buffer readiness check. If CreateCompatibleDC or SelectObject fails, drop the bitmap so the next call does not mistake a half-initialized state for a usable one; otherwise BitBlt would silently write nowhere and memcpy would read uninitialized memory. - Restore the previous bitmap before DeleteDC and check for HGDI_ERROR, otherwise DeleteObject on the still-selected bitmap fails and leaks it. The fallback matches the plain GDI capture path (full-size BitBlt plus ScaleBitmap), so a downgraded session performs the same as GDI mode. The only added cost versus DXGI is one BitBlt per frame. |
||
|
|
bc75e1ae99 |
fix(client): fix DXGI black screen on rotated displays and slow first frame
1. Black screen on rotated displays Root cause: with DXGI Desktop Duplication on a rotated output, DXGI_OUTDUPL_DESC.ModeDesc reports the logical desktop size (e.g. 1440x2560) while the surface returned by AcquireNextFrame is the unrotated landscape bitmap (2560x1440). The old code created cpuTexture from the ModeDesc size. On a mismatch ID3D11DeviceContext::CopyResource returns void and silently copies nothing, leaving the destination texture all zeros, so the first screen and every H.264 frame were fully black (IDR was only 5KB). The GDI path does not go through DXGI and was unaffected; the web client uses the DIFF algorithm and was hit too, but looked different. Fixes: - Create cpuTexture from the real D3D11_TEXTURE2D_DESC; when the probe fails, derive the real surface size from Rotation instead of falling back to ModeDesc, which would reintroduce the black screen - Add BlitRotated() to upright the image for ROTATE90/180/270, with a whole-row memcpy fast path for IDENTITY; m_ulFullWidth/Height now hold the upright logical size - Treat DXGI_ERROR_WAIT_TIMEOUT as "no new frame" instead of a failure, so a static desktop reuses the previous frame instead of always returning nullptr - GetFirstScreenData: fix the write offset (start at +1, previously the color channels were all wrong) and report the scaled size instead of the full size, which used to send about 8.5MB of garbage - Validate the frame format against a whitelist; fall back to BGRA and warn for formats that are not 4 bytes per pixel 2. Slow first frame (the probe frame consumed the initial frame) Root cause: the probe frame AcquireNextFrame(500), added to read the real texture description, was released right after use and therefore discarded. But the frame DXGI pushes after DuplicateOutput is often the only frame available on a static desktop. After discarding it, the first-screen AcquireNextFrame always timed out (and that timeout was 1000ms at the time), ScreenManager had already set m_SendFirst = TRUE so it never retried, and the encoder had no input to produce an IDR, so the picture only appeared once the desktop changed. Symptom: MDLL/EXE builds with this fix took a long time to show the remote desktop, while the old build without the probe frame was fast. Fixes: - Keep the probe frame: stash it in m_probeRes without calling ReleaseFrame and let the new ConsumeProbeFrame() fill the first screen once the buffers are allocated, so the first screen no longer depends on the desktop changing - Probe timeout 500 -> 200ms; verify both size and format of the probe frame against cpuTexture and skip consumption on mismatch, otherwise a silently failed CopyResource would be taken as a valid all-black first screen - CaptureFrame: drop "reuseOk ? 100 : 1000" and use a fixed 100ms timeout. The AcquireNextFrame timeout is an upper bound rather than a fixed wait, and blocking on a static desktop only slowed the capture loop down to 1Hz - Retry the first screen up to 3 times on "no new frame" (100ms timeout plus a 20ms gap); skip the capture entirely when the probe frame already filled it - Release m_probeRes in CleanupDXGI and ReinitDuplication so the duplication object can be released 3. Incomplete picture - Add ScreenCapture::FitDefaultSendSize(), which scales proportionally so the long edge stays at or below 1920 and the short edge at or below 1080, for both landscape and portrait. The old min(1920,w) and min(1080,h) clamped the axes independently and broke the aspect ratio: a 1440x2560 portrait desktop was squeezed to 1440x1080, keeping only 42% of the height - Use the same helper for both the GDI and DXGI paths; common landscape resolutions (1920x1080, 2560x1440, 3840x2160, 1280x720) are unchanged 4. Incidental fixes - CaptureFrame leaked desktopResource when QueryInterface failed, one DXGI resource per failure - Drop the frame and warn when the surface size changes, for example after the user changed the resolution, so BlitRotated does not read out of bounds using stale sizes |
||
|
|
46f4bf2dfb |
Fix: Make the WebSocket transport reachable and bounded on every platform
The POSIX clients were built without a connection config - Linux, macOS and Android all construct IOCPClient without the injected CONNECT_ADDRESS - so ConnectServer saw protoType -1 and quietly dialled the master port in plain TCP. Setting protoType to WS in their settings did nothing and logged nothing, and since CLIENT_CAP_PROTO_SWITCH is Windows-only the server could not move them either. Give the client a SetDefaultProto() for that construction path and call it from all three mains before the reconnect loop, with a one-shot log when neither a conn nor a default protocol is available so the silent fallback becomes visible next time. Bound what a peer can make the client read. ReadHeader accepted the 8-byte extended length and rejected only the sign bit, so a frame length of nearly 2^63 kept the connection streaming into a frame that would never end - alive but never delivering another packet. Cap single frames at 256 MB, the same value ServerWsSession already applies to client frames, and drop the connection past it; real traffic is far below that. Stop Reset() from writing the receive thread's frame state. Disconnect() can run from the heartbeat or command thread, not just the receive thread, so Reset() now only flips the atomic ready flag and a new ResetFrames() clears m_remaining, m_masked and m_maskPos from Handshake() alone, before the receive thread starts reading the socket. Those fields keep a single owner without adding a lock to the receive hot path. Finish a dead WS session instead of leaving it to the keepalive timer. When the session had closed but wsState was still WS_Ready, sends were dropped and nothing woke the pending recv, so a peer that closed and then went quiet held the context for the 3-minute keepalive. shutdown() the socket there so the recv returns zero bytes and the normal -2 teardown runs; RemoveStaleContext would deadlock against the caller's own IoRefCount and can hand back a reused context. That shutdown only finishes the connection if a zero-byte read still tears it down, and on the plain path it no longer did. DispatchPlain answers an empty buffer with "handled", so a peer's FIN left the connection in CLOSE_WAIT until keepalive - holding an IOCP context, a pending WSARecv and a rate-limit slot - where the pre-WS code called ParseReceivedData and tore down at once. Restore that teardown on the TLS_Plain branch, matching the other two. Checked against a Debug server: a plain socket that half-closes used to sit in CLOSE_WAIT with the peer's recv timing out, and now disappears immediately with recv returning zero. Two smaller cleanups from the same review. Give the WS upgrade its own prefix buffer (wsPreClassify) instead of borrowing the TLS sniffer's, which was serially reused for two state machines and read as if it were one. And stop deriving the build dialog's protoType from the combo box index: items now carry the protocol value as item data, keyed off the index AddString returns, so inserting an option in the middle can no longer write the wrong number into the generated client without any error. ApplyProtoSwitch loses its bool return, which contradicted its own side effects and was ignored by every caller. Co-Authored-By: deepseek-flash |
||
|
|
50a489e316 |
Fix: Close the gaps the WebSocket transport review found
Three of the findings only bite in deployment. First, the client's TLS and WebSocket handshakes run synchronously on the reconnect thread with no socket timeout, so a peer that accepts TCP and then goes quiet (black-holed proxy upstream, middlebox that only receives) blocks recv() forever and stalls the reconnect loop until the process is restarted. Set a 15 s SO_RCVTIMEO and SO_SNDTIMEO for the handshake window - the same value both server handshake threads use - and clear them once the connection is up so the worker thread's select plus blocking recv keeps working as before. Second, per-IP rate limiting counted the getpeername address before the real device was known. Behind a same-host reverse proxy that address is loopback, which IPWhitelist always trusts, so WS traffic was neither counted nor banned; behind a remote proxy every device shares one bucket, and tripping the threshold disconnected all of them. Count and ban by the forwarded device IP once the upgrade resolves it, mirroring the Go server's limitDirectPeer and handleConnection split. Direct connections keep their accept-time count and are not counted twice. Third, the protocol switch disarmed its five-minute auto-revert as soon as the new entry connected, which only proves TCP/TLS/WS handshaking finished. If login is never accepted there (wrong backend, reverse proxy pointing at some other WS service), the revert could never fire and the client would keep retrying a dead entry. Disarm on the first CMD_MASTERSETTING instead, which the server only sends after adding the host to its online list, and re-check it on every heartbeat so a late one still counts. The smaller items came along: free the handshake parameter when CreateThread fails in both handshake starters, move the WS_Handshaking fail-closed guard ahead of the TLS branch so it also covers WSS (where tlsState is already TLS_Ready), generate the frame mask from a per-channel PRNG inside the send lock instead of an unseeded global rand(), make the transport flags and the WS session's ready flag atomic, drop rather than send unframed application bytes when a WS session has closed, and abort a protocol switch whose PEM fails to load instead of moving to an entry that cannot connect. The Go server now bounds the upgrade sniff even when ReadTimeout is zero, and the design doc records the two-stage limiter, the login-based disarm and the review items that stay as known limits. The protocol switch's input prompt is cut down to "reverse-proxy entry (host:port)" - the label static is only 81 dialog units wide, and the old sentence ran to roughly three times that. The three language files follow: en_US and zh_TW gain the shortened prompt and drop the long key it replaced, the German file gains the protocol-switch block it never had, and its WebSocket tip key is corrected - it had picked up a Go-server clause the source string never carried, so the tip was never translated at all. Co-Authored-By: deepseek-flash |
||
|
|
99db28e2e2 | Feature: Let the operator switch a live client's transport from the online list | ||
|
|
cc891e3670 | Feature: Sniff WebSocket upgrades on the MFC server's device port | ||
|
|
d4f312c9d8 | Feature: Tunnel the device protocol through a reverse proxy over WebSocket | ||
|
|
de621aa555 |
Compliance: Audit third-party dependencies and complete the license notices
Dependencies.md only covered compress/ and the injection libraries. Everything
else in the tree was undocumented, and LICENSE-THIRD-PARTY.txt was missing
three components that Dependencies.md already listed.
Added to Dependencies.md (23 entries):
vendored source KCP/ikcp, xxHash 0.8.3, tiny-AES-c, skCrypter,
cpp-httplib 0.14.3
runtime / data OpenSSL (Linux/macOS TLS and libsign.a HMAC), FRP
(Bin/res/frpc.dll, frps.dll), ip2region xdb v4, QQWry,
Microsoft DirectX SDK headers
server-go jwt 5.3.1, gorilla/websocket 1.5.3, klauspost/compress
1.18.2, zerolog 1.34.0, x/sync, x/text, lumberjack 2.2.1
plus 3 indirect modules
android androidx core-ktx 1.13.1, appcompat 1.7.0, Kotlin stdlib
2.1.21
test GoogleTest 1.14.0 (CMake FetchContent)
LICENSE-THIRD-PARTY.txt grows from 278 to 633 lines and 22 sections. Full text
is embedded for the short licenses (MIT, BSD, zlib, Unlicense); the Apache,
LGPL and GPL entries follow the file's existing style of terms + obligations +
where to obtain the text, rather than reproducing legal text by hand.
Three findings worth recording:
- x264 is GPL-2.0 and is linked statically (client/X264Encoder.cpp). The old
file only stated that FFmpeg was built without GPL plugins, and never
mentioned that x264 is linked separately. Section 21 now spells out the
consequence: a binary containing x264 is a GPL-2.0 work unless covered by a
commercial x264 license.
- FFmpeg is linked STATICALLY, not dynamically as the old text claimed. There
is no av*.dll anywhere in the tree; the pragmas reference libavcodec_x64.lib
and friends. Section 19 is rewritten around LGPL-2.1 section 6 and quotes the
configure line recovered from libavutil, which also shows the build is
decode-only (--disable-encoders). That means x264 is the product's only
H.264 encoder, so DISABLE_X264_FOR_TEST=1 leaves no encoder at all and the
client degrades to RGB565.
- The FRP binaries report buildinfo v0.69.2-...+d58c00d0332c+dirty. The "+dirty"
means the FRP sources were modified locally, and Apache-2.0 section 4(b)
requires modified files to carry a prominent change notice.
|
||
|
|
82f59b2469 |
Fix: Make the x264 opt-out real, and unchain libyuv from it
DISABLE_X264_FOR_TEST never actually removed the x264 dependency. Two separate reasons: 1. X264Encoder.h included <x264/x264.h> unconditionally and only pulled in common/config.h afterwards, so the macro was not even visible at the point where it mattered. The class also carried x264_t / x264_picture_t / x264_param_t members, so the header was required to compile regardless of the switch. Moving the config.h include to the top and splitting the class declaration in two fixes it: with the switch on, the class is a stub with no x264 types at all, and open() returns false so EncoderFactory falls through. The open(x264_param_t*) overload is dropped in that branch; it had no callers outside X264Encoder.cpp. 2. libyuv was collateral damage. Its only #pragma comment(lib) lived inside the #else branch of the x264 switch, but CFFmpegAV1Encoder.cpp and CFFmpegH264Encoder.cpp both call libyuv::RGB24ToI420 / ARGBToNV12 / I420ToNV12 without carrying a pragma of their own. Turning x264 off therefore dropped libyuv too and the link failed with LNK2001 on those three symbols. libyuv is BSD-3 and unrelated to x264: the pragma is now unconditional in X264Encoder.cpp, and CFFmpegH264Encoder.cpp declares it alongside its ffmpeg libs so the encoder pair is self-sufficient. Verified with Release x64 builds of both ServerDll and ghost: switches 0/0, compress/ intact -> builds switch x264=1, compress/x264 deleted -> builds (was LNK2001 before) switches 1/1, both dirs deleted -> builds So a compliant build needs neither the x264 library nor its headers. Note for anyone flipping these switches: do a full rebuild, not an incremental one. config.h reaches X264Encoder.cpp indirectly through X264Encoder.h, which the .tlog dependency tracking does not record, so an incremental build happily links a stale object against a freshly compiled one and reports bogus LNK2001 errors. |
||
|
|
1d875ddbd1 |
Feature: Add a "Copy Name" item to the online host context menu
The online list already lets an operator copy everything about a host through "Copy Client Info", but there was no quick way to grab just the names, which is what people actually paste into a chat or a ticket. The new menu item sits directly below "Edit Group" and copies the names of all selected hosts to the clipboard, separated by semicolons. "Name" means what the first column of the list shows: the remark when one has been set, otherwise the computer name. The column text is CP_ACP, so the handler decodes it the same way OnGetdispinfo does; that keeps the copied text identical to what is on screen, including for Chinese remarks. Clipboard writing reuses the existing UTF-8 based SetClipboardText helper instead of growing a third copy of the same CF_UNICODETEXT code. The item also gets its own 16x16 icon (two stacked cards with text bars, drawn on the usual 240,240,240 background) loaded into a newly added m_bmOnline[75] slot, and translations were added for English, German and Traditional Chinese so the item does not fall back to simplified Chinese when another UI language is active. The user manual and the resource README were updated to match. Co-Authored-By: deepseek-flash |
||
|
|
dcb5ae25c6 |
Fix: Paginate get_activity_history results
The tool was the only list-type tool without pagination. The client keeps ACTIVITY_HISTORY_MAX=500 records and Dump() prepends the in-progress window, so a single call returned up to 501 lines of "[time] [title] duration" -- enough to blow up the caller's context, especially since titles carry personal browsing history. Records come back newest-first (m_records uses push_front and the current window is prepended), so the standard limit/offset window applies directly: offset=0 is the most recent page, no need to read total first and count backwards. That ordering is now stated in the tool description so the model can rely on it. - inputSchema: BuildGetHostDetailInputSchema -> BuildPagedHostListInputSchema (adds limit, default 100 / max 1000, and offset) - outputSchema: append AppendPageOutputProps plus truncated - implementation: rename the full split to `all`, slice via ResolvePageWindow and ApplyPageWindow, write back with WritePageFields - activityHistory is rebuilt from the window instead of returning the whole Dump() text -- otherwise the raw copy would bypass pagination entirely - 64 KB byte budget (same as get_client_log), trimmed from the end so the newest records survive; hasMore is computed as offset+kept < total rather than hardcoded true, since a single oversized tail record must not claim there is another page Batch calls need no extra work: the tool is already in IsBatchReadOnlyTool, and BuildBatchCall forwards limit/offset to each host, so ids + limit means "the latest N records of every host". Compiles clean; not yet exercised against a running server (the exe was locked by the live instance). Verification cases are listed in docs/Mcp_Test_Report_2026-10-29.md section 8. |
||
|
|
56a937fabb |
Fix: Three blocking defects found by the MCP tool survey
The survey in docs/Mcp_Test_Report_2026-10-29.md turned up three P0s, each
of which stopped a whole capability rather than degrading it. Two of them
were the same mistake: the input schema promised something the output
schema then rejected. The third was an output with no size limit, plus a
client that never implemented the command at all.
Batch calls could never succeed. A call carrying ids[] goes through
BuildBatchCall, which returns {tool, total, succeeded, failed, skipped,
results[]}; every tool declares only the single-host shape. The client
validates structuredContent against that declaration, so any batch call
failed with -32602: data must have required property 'host' - the input
schema advertises ids, the output schema kills it. Tools/call cannot fix
this one call at a time, so ApplyBatchOutputSchema runs at the end of
tools/list, next to ApplyToolAnnotations, and rewrites the schema of every
tool in the batch list to {type: object, anyOf: [single, batch]}. Placing
it at the end is what makes it cover all three registration points
(inline, McpMachine, McpChat) and any tool added later. IsBatchReadOnlyTool
moved from McpServer.cpp to McpInternal.cpp for the same reason: the list
is now read by tools/call and tools/list, and the two must not drift.
list_registry failed whenever path was omitted. The root-key branch
returns keys only, while the output schema listed values in required as
well, so the first usage the documentation describes - omit path, get the
five root keys - could not work. values is no longer required and the
schema says it is absent in that branch. The root branch also returns
path: "" now, so both branches carry the same field set and callers need
not branch.
get_client_log was unusable on both platforms, for two unrelated reasons.
Windows returned the whole 1000-line ring buffer, 90,473 characters, over
the client's result limit: fetched, then not deliverable. Linux and macOS
timed out because their clients never handled COMMAND_QUERY_LOG at all -
only client/ClientLogManager.cpp does - so TOKEN_REPORT_LOG never arrived.
Adding a limit alone would have left Linux broken; fixing the client alone
would have left Windows over the limit.
The server now takes limit (default 200, max 2000) and filter, and reads
backwards from the end: troubleshooting wants the last thing that happened,
not the first line after boot. A 64 KB byte budget sits under the line
count, because one line can be a stack dump; when the final line alone
exceeds it, the tail is returned and truncated says so. Responses carry
lines_total, lines_matched, lines_returned and truncated. The timeout
message now names the likely cause and two ways around it instead of
saying only "Timeout waiting for client log".
The POSIX clients get common/ClientLogHandler.h, a counterpart to the
Windows CClientLogManager, and one line each in linux/main.cpp and
macos/main.mm. It must open a sub-connection: MessageHandle's
TOKEN_REPORT_LOG branch takes the first packet and then calls CancelIO on
that connection, so answering on the main connection would close the main
connection and drop the client offline.
Verified against a server built at 21:17:21 with both clients rebuilt. A
batch get_host_detail over the two A6 records returns succeeded=2 with
per-host data; host_list_processes with ids returns 2 of 2, which exercises
the McpMachine registration point rather than the inline one; a mixed
Windows/Linux batch of get_client_log returns 2 of 2. list_registry with
no path returns the five root keys and path ""; with a path it still
returns its values. get_client_log on Windows goes from 1000 lines to 200
with truncated=true, and limit=3 with filter=ConnAuth yields 28 matched and
3 returned. On Ubuntu 24.04 it returns logs at all, and the client's own
log shows Enter ClientLogThread, TOKEN_REPORT_LOG, then Leave about a
second later when the server cancels the connection - paired, no leak.
The connector still caches an old input schema for get_client_log, so
limit and filter are rejected locally until it reconnects; the defaults
already cover the P0, and this is the same cache problem as the
copy_files_c2c.overwrite entry in the report's P1 list.
docs/Mcp_Design.md section 18 records the implementation and the reasoning;
section 7 of the test report carries the verification table.
Co-Authored-By: deepseek-flash
|
||
|
|
dc4fd792f6 |
Feature: Implement the Linux screen preview response
The Linux client now answers COMMAND_SCREEN_PREVIEW_REQ, so a host with an X11 desktop gets a thumbnail when it is double-clicked in the online list, a frame in the list's Preview column, and an image from the MCP get_screenshot tool. Previously only Windows clients advertised the capability and Linux hosts showed "预览不可用" after a four second wait. The client does not encode JPEG. Stock desktops ship libjpeg.so.8 whose struct layout is the distribution's ABI (JPEG_LIB_VERSION 80), while the in-tree jpeglib.h is libjpeg-turbo 3.1.1 (62), and libturbojpeg is not installed by default; dlopening the system library against that header fails with "Wrong JPEG library version: library is 80, caller expects 62". Instead the client sends raw pixels in a new screen preview format, SCREEN_PREVIEW_FMT_BGRX: top-down rows of B,G,R,X with no row padding, already scaled to the requested width. The server re-encodes to JPEG at the single ingress point, so the preview popup, the list thumbnail cache and the MCP tool keep consuming JPEG only. Capture follows the path ScreenHandler already uses: root window copied into an offscreen pixmap with an IncludeInferiors GC, then XGetImage, which avoids BadMatch under compositing window managers. The X11 type declarations and the dlopen loader moved out of ScreenHandler.h into linux/X11Loader.h so both users share one dlsym table. The full-size image is never materialized: a box filter reads straight from the XImage rows (honouring bytes_per_line) into the output buffer, scales to maxWidth without upscaling, and clamps the height to 1080 so a portrait 4K desktop cannot produce a 26 MB packet. Rows and columns come out even, which they are for JPEG anyway. The capability bit is now honest about the runtime. LOGIN_INFOR grows DefaultCaps()/SetCaps(), and the client recomputes the bits before every login and re-login: CLIENT_CAP_SCREEN_PREVIEW is set only when DISPLAY is present and the X server actually opens. A headless host therefore gets -32005 "Host does not support screen preview" from MCP instead of a timeout, and a host whose session appears after boot picks it up on the next reconnect. Requests are handled on a detached worker thread behind a single-flight guard (matching the Windows client), so a slow XGetImage never stalls the receive thread and a burst of requests degrades to "no preview" rather than queueing. If the worker thread cannot be created, the guard is released again, so one failure cannot leave every later request rejected as busy until the client restarts. The MCP design note claimed the capability was declared by Windows only, and the get_screenshot tool description said the same; both now say what the code does (Windows always, Linux when a display is reachable). Server side, NormalizeScreenPreviewPacket runs in MessageHandle before the MCP handoff and the PostMessage to the UI thread. It validates that width/height are within the values the server itself can ask for and that bytes equals width*height*4, converts with a stack Gdiplus::Bitmap over the packet's own pixels (no copy, and no DEBUG_NEW trouble), and rewrites the header to JPEG. The encoder output is read back by seeking the stream rather than GlobalSize, so the packet carries no heap-block padding after the EOI marker. Malformed packets are dropped; failure statuses pass through untouched so the existing code can report them. Tested against a Debug server with the WSL Ubuntu 24.04 build as the client. get_screenshot returned valid JPEGs at max_width 480 (480x142, 1.7 KB) and 1920 (1920x570, 17.9 KB), repeatably; the list showed a thumbnail for the GUI client and N/A for a second copy started without DISPLAY, which also answered -32005. The box filter and the BGRX to JPEG conversion were checked separately with quadrant fixtures: the browser over the synthetic B,G,R,X buffer recovers red/green/blue/white in the right channels and the downscale averages, handles non-integer ratios and row padding, and rejects 24bpp and upscaling. The captured frames come out black under WSLg because Xwayland keeps no root pixmap there; that is the compositor, not this code, and Xorg sessions capture normally. Co-Authored-By: deepseek-flash |
||
|
|
5bff9df3fc |
Improve: Harden the self-implemented SOCKS5 proxy listener
Follow-up to the HP-Socket replacement: the four items the first pass deliberately left out, plus two defects that the new tests turned up. The listener now binds 127.0.0.1 instead of INADDR_ANY. The dialog only ever points the user (and the Chrome shortcut) at 127.0.0.1, and an unauthenticated SOCKS5 port open on every interface is an open proxy. The SOCKS5 handshake is parsed as a byte stream. The previous code assumed one callback carried exactly one message, which happens to hold for curl and Chrome but not in general: a greeting split across segments was answered twice, and a CONNECT request followed by tunnel data in the same read dropped the trailing bytes. Each connection now keeps a pending buffer and a four-state machine (greeting, request, connecting, tunnel), and bytes that arrive before CONNECT_RESULT are replayed to the client once the tunnel opens, after the SOCKS5 reply. Flow control: the listener takes a PROXYCANRECVPROC callback that is consulted before each recv. The dialog answers it from the main connection's send queue, so a download that outruns the client link pauses the local read instead of growing the server's buffer. A 300MB transfer through the tunnel peaks 150KB above the idle working set. Handshake watchdog: sessions that stall in greeting/request/connecting are dropped after 30 seconds; established tunnels are left alone. Two defects in the log path, both surfaced by the watchdog test. Logging every 32KB chunk produced roughly 9000 posted messages for a 300MB transfer, which starved the UI thread's timers (the first watchdog run never fired) and could overflow the message queue; and every line re-set the whole 256KB text into the read-only edit. Transfers now log cumulative progress once per second and a per-connection total at teardown, panes are refreshed at most every 100ms from a dirty flag, and a failed PostMessage no longer leaks its CString. Localization: the new session-log strings were also added to en_US.ini, zh_TW.ini and de_DE.ini (16 keys each, GBK, kept in the existing FormatL section). Two of the lines were reworded instead of translated as-is: the close notice now says what happened (the client asked to close, or the downlink send failed) rather than printing the protocol token name, and the throughput arrows are now << and >> because CIniParser splits an entry at the first '=', so the old <== and ==> could never have served as keys. Testing: curl IPv4 and hostname tunnels, 4MB and 300MB transfers byte-identical, byte-at-a-time and pipelined handshakes, refused target (REP=5), SOCKS client killed mid-transfer, client process killed mid-transfer (dialog closes, port released), 20 parallel connections, five open/close cycles with no handle or thread growth, and the 30s handshake timeout. The dialog log was checked at runtime with Language=en_US and renders in English only. Co-Authored-By: deepseek-flash |
||
|
|
45e1dd9f6c |
Feature: Implement the proxy mapping listener without HP-Socket
The proxy mapping dialog ("代理映射") depended on HP-Socket: three vendored
SDK headers (4787 lines) plus #pragma comment(lib) lines pulling in four
prebuilt lib/DLL variants, all guarded by ENABLE_HPSOCKET, which has been 0
since the initial commit -- so the feature was dead code that only answered
"This feature is unavailable due to HPSocket disabled" and no build of this
repository ever ran it.
Replace that dependency with a small listener built on blocking sockets and
select, which is the same approach the client's CProxyManager and the
server's own SimpleWebSocket already take. The accept loop polls every
200 ms so Shutdown can return without closing a socket another thread is
selecting on, and each accepted connection gets a relay thread that only
has to recv and hand bytes to the dialog. Connection sockets are closed by
their relay thread alone; Disconnect only raises a stop flag and calls
shutdown() under the same lock the relay thread takes before closesocket,
so a recycled handle is never shut down by mistake. Finished threads are
parked in a graveyard and joined by the accept thread, which keeps the
thread handle count flat across open/close cycles.
ProxyMapDlg keeps the SOCKS5 state machine it had, but now stores its
per-connection state in a map keyed by the connection id instead of
relying on HP-Socket's GetConnectionExtra, and it logs through a posted
window message rather than touching CEdit from worker threads. The two log
panes in IDD_PROXY are ES_READONLY, so EM_REPLACESEL was silently ignored
(the original code had the same latent bug); the dialog now keeps the pane
text itself and writes it with SetWindowText, bounded to 256 KB per pane.
The vcxproj and filters lose the three SDK headers, and the dialog gate in
OnOpenProxyDialog loses its ENABLE_HPSOCKET check.
Tested against a Debug server with a Debug Windows client on the same
host: curl through the listener succeeds over both the IPv4 and the
hostname ATYP paths, a 4 MB transfer arrives byte-identical, a refused
target maps to SOCKS5 reply 5, killing the client mid-transfer closes the
dialog and releases the port, and five open/close cycles leave the server's
handle and thread counts unchanged.
Co-Authored-By: deepseek-flash
|
||
|
|
13c02fe50b |
Feature: Skip already-present targets in copy_files_c2c
The destination writes every chunk unconditionally, so a second call with the same arguments re-sent the whole file and returned exactly the same result as the first. Measured on an 11 MB log: the target's mtime moved and the entry count did not, and the caller had no way to tell a real transfer from a repeat. upload_file and download_file already answer this with overwrite/skipped; copy_files_c2c was the one that did not. The skip decision has to be made on the server, because the receiving end does not check whether the file exists. Before opening the transfer, a default call now lists one level of dst_dir through ListRemoteTopLevelNames - the helper upload_file already uses - and drops the paths whose basename is already there. If everything is dropped the call returns success without creating a transfer id at all, so no host is occupied and nothing is sent. overwrite=true restores the old unconditional behaviour. Name comparison follows the destination filesystem: folded on Windows, exact on POSIX. That needed a foldCase parameter on the helper, defaulted to true so upload_file keeps its behaviour. dst_dir is handed to the listing without its trailing separator, because the client concatenates "%s\*.*" and a trailing one produces "C://*.*", which FindFirstFile rejects. search_file hit the same thing. No protocol change and no client change: the packet layout, the receiver and both client platforms are untouched. Verified against a real server (build 2026-10-29 14:34:33) with a Windows 11 source and both an Ubuntu 24.04 and a Windows 11 destination. A second default call returns file_count=0, skipped=1, an empty transfer_id and skip_check_failed=false with the target's mtime unchanged; overwrite=true advances the mtime (1793276909 -> 1793281657) and reports skipped=0; a call into a non-existent directory creates it and lands the file flat; a Windows destination folds case, so a placeholder SETTINGS.INI makes a later settings.ini skip, while a POSIX destination leaves both files side by side. One documented case does not hold, and the expectation was mine rather than the code's. "Destination occupied by another tool" was supposed to fail the pre-check and still transfer with skip_check_failed=true, but BeginC2CTransfer consults the same m_Pending registry for src_id and dst_id, so the transfer is refused with -32003 before the fallback can carry it. The other door - a directory that can be written but not listed - showed the pre-check succeeding instead of failing: the Linux client reports EACCES as an empty directory rather than TOKEN_FILE_LIST_ERROR, so the call goes on to overwrite. skip_check_failed is therefore a timeout backstop that is hard to reach deliberately; the field stays, and 14.9.2 no longer claims that a busy host reaches the fallback. Section 14.9 of the design doc records the contract, those results, and one wrong turn worth keeping: an earlier round concluded that single-file C2C nested the whole absolute path under dst_dir, and added receiver-side hardening for it. The nesting came from the ad-hoc JSON-RPC test harness, which passed JSON on the command line where the shell folded \\ into \/ before Python parsed it, so the source client received a path with no backslashes left and its basename fallback - which looks for a backslash - returned the whole path. The same file sent through the real MCP client produces a clean basename. That hardening has been reverted; the defect was in the test, not the product. Co-Authored-By: deepseek-flash |
||
|
|
cd10d0cc1b |
Docs: Bring the MCP plan up to date after P10 and P11
The plan was written when the server had 54 tools in eight families, and every batch since then changed the facts it states: P10-B added the three file-write tools, P10-C the input lock, P11 the two session tools and the protocol work. Read as-is, the plan would send the next person looking for work that is already done, so the numbers, the family table and the batch table now describe the 60 tools that actually exist. The family table was rebuilt from the registration sites rather than from the previous table: nine families, and the gating column now separates "appears in tools/list" from "callable", which the old table conflated. That distinction also fixes the default-config figure - 19 tools, not the 20 stated earlier: get_keylog needs McpKeylog, download_file needs McpFileTransfer, and list_network_connections lives in the McpMachine family, so with a default of read-only and every switch off only the nine server-local read tools, eight read tools on the host and the two remark/watch tools remain. Section 5.10's field list for mcp_list_sessions was a guess written before the tool existed; it now carries the eight fields that D.5 actually returns, with the original guess kept so the change is visible. The two stale rows in 5.14 and the outdated header comment in 5.13 are marked done against the commits that did them - |
||
|
|
1c832ff7f2 |
Feature: Add MCP cancellation, progress notifications and dry runs
P11 closes the plan's last batch, entirely on the server side: no client change is required for any of it. Long-running tools now expose a cancellation flag that every wait loop checks in 500 ms slices. A cancelled tool returns through the cleanup branch it already had (late first packets still get absorbed, sub connections still get closed, pending entries still get deleted), so there is no second cleanup path to keep in sync, and the host is released within a second. Three sources set the flag: notifications/cancelled (matched on the exact JSON-RPC id, with a fallback to the display form so a request_id copied out of the session list round-trips), mcp_cancel_session (by request_id, host id or session id), and a failed SSE write when the client has gone away. The dispatcher rewrites a cancel-induced failure to -32800 so callers do not mistake it for a host fault. tools/call requests carrying _meta.progressToken are answered as text/event-stream on the same POST: the tool runs on its own thread and both the notifications/progress events and the final JSON-RPC response go out through one chunked provider. Requests without a token are unchanged. download_file reports files done vs. expected, upload_file reports bytes sent vs. total. Two new local-only tools, mcp_list_sessions and mcp_cancel_session, list and cancel in-flight sessions (calls, pending one-shots, terminal, remote control, file transfer, chat). They are deliberately not gated by the feature switches or readonly mode, since that is the only way out of a stuck request. The -32003 busy message now names the occupier: "Device busy: ... (tool=download_file, elapsed=12s)". power_action gains wait/wait_ms to verify the result against the main connection's presence (went_offline, came_back, elapsed_ms); not seeing the transition is reported as ok, not as a failure. kill_process, operate_window and the four host_control_* tools accept dry_run, which validates the target against one fresh snapshot and returns what would be affected without sending anything. Validation rejections now use -32012; -32008 stays as documented historical alias. One implementation note worth recording: the per-thread call context uses FLS, not thread_local. Any static thread_local in this server crashes the process about a second after start, because some threads come from shellcode/MemoryModule images that never ran PE TLS initialisation. Verified against a real Debug server and a real Windows client over MCP: the smoke test now passes 104 checks with 0 failures, including cancellation releasing the host in under a second, the cancelled request returning -32800, notifications/cancelled returning 202, 63 progress events with exact byte counts for a 64 MB upload, and a cleanly terminated SSE stream. Not exercised in this pass: power_action's wait=true path (it would take the test host down) and the -32006 readonly/switch-off section (every switch was on during the run). Co-Authored-By: deepseek-flash |
||
|
|
3d388f8e45 |
Feature: Add remote_block_input to MCP remote control
A GUI automation run is interrupted the moment a person at the host touches the mouse, and locking the host's keyboard and mouse is the standard answer. The client already implements COMMAND_SCREEN_BLOCK_INPUT and the MFC screen window already sends it, so the tool needs no client change: it puts the same two-byte packet [COMMAND_SCREEN_BLOCK_INPUT][0|1] on the hidden screen sub-connection that remote_open established. The gate is remote_open's own - McpRemoteControl=1 and McpReadonly=0 - because the ability to lock someone out deserves exactly the same door as the ability to drive their desktop, and Linux and Android clients are refused with -32005: they have no branch for this packet at all and would silently ignore it. Locking a host out is only acceptable if every way back in is closed, so the session now carries its own lock state and three paths release it. block=false releases it directly. block=true always carries a deadline (max_block_ms, default 300000, clamped to 1000..3600000) and a watchdog thread started with the MCP server sweeps every 500ms for expired locks, sends the release and records it; the next remote_block_input reports it as auto_unblocked so the model learns that its lock lapsed instead of assuming it is still held. remote_close and the idle reclaim both send block=false before they tear the sub-connection down, because once that connection is gone the server has no channel left and a live client process stays blocked - all three release paths write an audit line, since none of them is something a person can see. The send happens outside the MCP lock, and the watchdog takes the session's busy flag while it releases, so it cannot interleave with an injection or race a close; a failed send keeps the lock marked and retries five seconds later rather than hammering a dead connection every tick, and a session that dies under the watchdog is erased the same way an injection would erase it. Verified against a real Windows client over MCP on a Debug x64 build: block then unblock, block with a 1.5-2s deadline left to expire and reported back as auto_unblocked with the watchdog audit entry at the expected second, block with a ten-minute deadline then remote_close with "(input lock forced off)" in the audit, and the five refusals (missing block, non-boolean block, max_block_ms out of range, unknown session, offline host). The smoke test gained [4d] for those refusals; 54 checks pass. Two limits are worth stating plainly. BlockInput only works when the calling process is elevated (or UIAccess), the client ignores the API's return value, so on an ordinary client the lock silently does nothing and the tool can only promise that the command was delivered - both the tool description and the server instructions say so. And the idle-reclaim release, like the two verified paths, is only exercised at a 300s idle timeout; it shares the same send helper and was reviewed rather than timed out live. Bin/settings.ini was restored byte-exact and the Release instance was left alone. Co-Authored-By: deepseek-flash |
||
|
|
27b5431130 |
Feature: Add the file-write tools behind their own switch
P10-B adds delete_path, move_path and create_folder, and the switch they need. Reusing McpFileTransfer would have been wrong: uploading overwrites a file, deleting destroys a tree, and an operator who wants one may well not want the other. McpFileWrite is therefore a separate key, off by default, wired the way every other switch is - read from settings.ini at startup, reported as get_server_status.switches.file_write, and exposed with its own checkbox in the MCP settings dialog. The tools additionally require readonly to be off: a read-only server has no business modifying a host. No client change was needed: COMMAND_DELETE_FILE, COMMAND_DELETE_DIRECTORY, COMMAND_CREATE_FOLDER and COMMAND_RENAME_FILE already existed in the Windows file manager. The chain reuses the file-manager sub-connection and adds a phase - the main connection asks for the drive list, the sub-connection's first packet hands it to OnDriveList which sends the write command, and the client's TOKEN_*_FINISH ack moves the pending request from phase 0 to 1, where the tool sends COMMAND_LIST_FILES for the parent so the ack and the confirmation share one timeout. Only the IO thread touches the sub-connection; the tool thread just waits on the shared condvar, which keeps the sub-connection's lifetime out of its reach. The confirmation exists because the client answers unconditionally: it ignores the return values of DeleteFile, MoveFile and MakeSureDirectoryPathExists and there is no error token. ok therefore only means "the command arrived", and verified is the real answer - true when the parent listing shows the expected post-state, false when it shows the opposite, null when the listing itself did not come back (timeout or disconnect), since reporting that as false would be a lie. Linux, macOS and Android hosts are refused outright: those clients decode these paths as GBK while the server speaks UTF-8 to them for list_files, so a non-ASCII path would corrupt rather than fail. Paths are validated as UTF-8, converted to GBK exactly once, and reject %VAR%, relative paths, drive and share roots, and - for delete_path and for move_path's source - the Windows, Program Files, ProgramData, $Recycle.Bin and System Volume Information trees. create_folder gets no system-directory ban, because writing there is the same permission upload_file already has. Two defects surfaced while exercising this against a real client: create_folder's wire path has to end with a backslash, because MakeSureDirectoryPathExists treats a non-terminated last component as a file name and only creates the intermediate levels; and ResolveFileOpVerified(LookupInListing(...), isDir, ...) read isDir before the lookup ever set it - argument evaluation order is unspecified and MSVC evaluates right to left - so every create_folder reported verified=false even when the directory existed. Verified on a Debug x64 build against a Windows client over MCP: nested create_folder, upload, rename, delete, delete a tree, the failure shapes (delete with recursive=false on a directory, create_folder onto an existing file name, delete of a non-existent target) and every refusal (drive root, C:\Windows\Temp, C:\Users, %TEMP%, relative, empty, over-long, from==to, offline host, non-numeric id), with a Chinese-named directory created, renamed and deleted end to end; no file-manager window appeared in the server process during any of it. The smoke test gained section [4c], opt-in through -FileWriteDir, which asserts verified and never ok and walks a sandbox through the same path; two runs passed 69 checks with the sandbox removed afterwards. Bin/settings.ini was restored byte-exact and the Release instance was left alone. Co-Authored-By: deepseek-flash |
||
|
|
bb55f52b29 |
Feature: Add instructions, capability reporting and filters to MCP
P10-A is the first batch of the next MCP phase: the server now tells a model
how it expects to be driven instead of leaving the rules to be inferred from
per-tool descriptions.
initialize carries the instructions field that MCP 2025-06-18 defines, in
five sections: where host ids come from, which switch hides which tool, what
each error code implies for the next action, typical orchestrations, and
safety. Every statement was checked against the implementation rather than
derived from the tool descriptions, and four did not survive: the host_*
family only supports name/pid filters in part (named per tool now), read-only
mode does not hide host_set_remark and host_set_watch_level (they touch only
the local host store and are refused with -32006 when called), -32003 is one
lock keyed by device id rather than one per capability, and there is no
"screen stream" tool to pick instead of get_screenshot. The string is built
from u8 literals because the project compiles with /execution-charset:.936.
get_host_detail returns a capabilities object (platform, screenPreview,
remoteControl, fileTransferV2, c2cPaths, registry), each flag tied to a gate
that already exists in the dispatcher, so a model no longer discovers a
host's limits by calling and reading -32005. remoteControl mirrors the two
conditions remote_* actually applies (Windows or Linux, and not
multi-monitor), not the preview bit. Making the flags honest exposed
list_registry rejecting only LNX and MAC, so an APK host passed and then
waited out the timeout; it now uses the same is-Windows predicate the bit is
computed from. That predicate existed as identical local copies in
McpMachine.cpp and McpChat.cpp and now lives in McpInternal.
list_processes and list_windows take an optional name and pid, filtered on
the server before the page window is applied, with total counting matches
and totalAll still reporting the unfiltered count. The two tools get their
own schema builder so list_services does not advertise a filter it would
silently ignore, and the pid descriptions differ because a pid means the
process itself for one tool and its owner for the other.
get_keylog gains set_offline and clear, the two commands the client already
implements on the keyboard sub-connection but nothing on the MCP side ever
sent, plus offlineRecord from the ready packet's byte 1. Both writes are
gated on McpReadonly=0 and validated before COMMAND_KEYBOARD goes out, so a
refused call cannot leave a running keyboard session behind; the tool's
annotations change from read-only to writable and destructive, and the
server instructions gain the matching sentence.
Four capabilities are exposed twice through two different sub-connection
chains, so each pair's descriptions now say which one to reach for first and
when the other is the only option: the host_* trio carries more fields and
filters on the server, the list_* trio is the McpMachine=0 fallback, and
operate_window is the only one that can close a window. No tool was merged:
the split is what lets McpMachine be switched off on its own. search_file's
description drops the stale MAX_PATH-overflow warning (fixed in
|
||
|
|
4a3cded174 |
Docs: Plan the next MCP phase, with its claims checked against the code
Mcp_Next_Plan.md lays out what the MCP surface can still gain and how the
existing tools can be improved: a full client-command coverage matrix, a
file-system write batch, a remote-control gap, and a list of protocol-level
blanks. Every conclusion is tied to a file and line so the next step can be
implemented without re-deriving the analysis.
The first draft was written from a read of the code but not verified against
it. Auditing it turned up four claims that would have sent the work in the
wrong direction, and they are corrected here rather than left to be discovered
during implementation:
- The draft wanted a mode=offline for get_keylog because "the tool only sees a
1-15s live window". That premise is false. CKeyboardManager1 builds its
CircularBuffer from the on-disk record file, and SendData replays the whole
buffer from position zero on every (re)connect, so the existing tool already
returns the persisted history whenever kbrecord=Yes. What is actually missing
is only the on/off switch, the clear command, and reporting the state the
client already sends in TOKEN_KEYBOARD_START byte 1.
- Unlike P7, the file-write tools do not plug into OnSystemReady: their ready
packet is TOKEN_DRIVE_LIST, which lands in OnDriveList, where an empty path
is currently read as "list drives" and consumed. Worse, the three finish
tokens have no case at all in the top-level dispatch, so on the MCP path
(hDlg == NULL) they fall into default: and the sub-connection is never
closed. Appendix C now spells out the three wiring layers that every
sub-connection write tool has to touch.
- -32008 carries two meanings, not four: both remaining sites are argument
validation, and the multi-monitor rejection was already moved to -32005.
Dropping the proposed -32013 removes a whole error-code split.
- The draft put server gate state into get_host_detail, duplicating the
switches object that get_server_status already returns; monitors and most
per-host facts are already there too, so capabilities shrinks to the
client's own ability bits.
It also records what the audit added: delete_path inherits the client's
unbounded wsprintf when recursing (the search path got a length guard in
|
||
|
|
106ac2ff0f |
Fix: Resolve the Desktop, Downloads and home shortcuts on Unix clients
The file manager's remote shortcut buttons send "%USERPROFILE%\Desktop\" and friends, which the Windows client expands with ExpandEnvironmentStringsA. Unix clients had no such expansion, so the literal %USERPROFILE% was taken as a directory name: opendir() failed and the Desktop, Downloads and home buttons listed nothing at all. Add common/UnixPath.h, which expands the variables the server can send (%USERPROFILE%, %HOME%, %HOMEDRIVE%%HOMEPATH%, %USERNAME%) and maps $HOME/Desktop to the localized folder named in ~/.config/user-dirs.dirs (for example ~/桌面), falling back to the plain $HOME/<Name> path when that folder does not exist. Unknown %VAR% tokens are left untouched, so paths that really contain a percent sign behave as before. FileManager and the two Windows-to-Unix converters in FileTransferV2 now share that one conversion. Besides the listing itself, this fixes downloads into a shortcut directory, which used to be created under a literal %USERPROFILE% tree instead of the user's real desktop. Co-Authored-By: deepseek-flash |
||
|
|
6bfa4294cc |
Feature: Switch a Linux client's transport TLS at runtime
The server's TLS menu already wrote the trust anchor into the Windows client's registry and expected a restart. The Linux client grew the same command handling (166/167) but, like Windows, only read the anchor once at startup, so enabling or disabling TLS still meant restarting it. Both handlers now take effect immediately. TlsChannelLinux.cpp no longer initialises through std::call_once. The process-level state (context, enabled, load error) lives behind a mutex and TlsReload() rebuilds it from whatever anchor file is on disk, so TlsEnabled() reflects the new transport as soon as the anchor is written or removed. In-flight sessions survive the swap because SSL_new increments the SSL_CTX reference count; the unit test pins that down by keeping an established TLS connection open across a reload that frees the old context. A reload that hits a bad anchor keeps the previous state and only logs: one bad push should not brick a working client, and the next start is still fail-closed. The pushed PEM is parsed before it is written for the same reason -- a corrupt anchor on disk would lock the client out of the server with no way to correct it remotely. Only a real transport flip (plaintext <-> TLS) asks for a reconnect. An anchor swap alone, as in a certificate rotation, leaves the current session alone and applies to the next connection. The receive thread never closes the socket itself; it sets g_needReconnect and the main heartbeat loop disconnects so the outer reconnect loop can re-handshake, matching how the heartbeat timeout path already works. IOCPClient now latches the transport per connection (m_useTls) at handshake time instead of consulting TlsEnabled() on every send and receive. Without the latch, the second or so between the reload and the reconnect would push plaintext into an established TLS session, or the reverse, producing protocol errors for no reason. RES_TLS (szReserved[19]) is refreshed right before each login, including the resend after a group change, so the TLS column on the server flips with the transport instead of showing the value from process start. The confirmation dialogs now say what each platform does, with translations in en_US, zh_TW and de_DE; the keys carry the literal \n escape the INI parser understands. Ending a sub-connection is not an error. OpenSSL 3 classifies a peer that closes without close_notify as an unexpected-EOF protocol error, so every terminal or file transfer session logged an SSL_read failure on the real servers even though Recv promises 0 for a plain close and neither side sends close_notify. SSL_OP_IGNORE_UNEXPECTED_EOF restores the intended semantics. Verified with the reload unit test (RELOAD-OK, covering the in-flight connection across a context swap, garbage payload rejection and a broken anchor keeping TLS alive), an abrupt-close test (recv now returns 0 instead of SOCKET_ERROR) and end to end against a protocol-faithful fake server that signs MasterSettings with libsign: plaintext login, 166, TLS reconnect with RES_TLS=1, 167, plaintext reconnect with RES_TLS=0. The Linux client, the Debug Windows client and the Debug MFC server all build. The cost is inherent to taking effect immediately: a remote session in progress is dropped when the transport changes, and the MFC server briefly shows the client as a duplicate login until the old connection is reaped and the standby entry is promoted. Co-Authored-By: deepseek-flash Co-Authored-By: Claude Code <noreply@anthropic.com> |
||
|
|
c11df75225 |
Fix: Report the real runtime instead of a timezone skew in host info
The host info popup showed a constant "7h" runtime for every Linux host. szStartTime carries no timezone marker and the two sides disagree: the Windows client sends its own wall clock (client/LoginServer.cpp getProcessTime), while the Linux and Android clients send Beijing time unconditionally (linux/main.cpp and common/commands.h ToPekingTimeAsString hardcode UTC+8). GetElapsedTime then built the base time with CTime as local time and subtracted it from the local clock, so on any server that is not at UTC+8 the start time landed in the future; the absolute value turned that skew into a plausible-looking duration (UTC+1 gives exactly 7h). GetElapsedTime now picks the reference "now" by client type: LNX and APK are compared against the current Beijing time, everything else keeps using the local clock. A start time in the future now clamps to 0 instead of being mirrored, so a clock disagreement shows as unknown rather than as a fake runtime. The Linux client also reported the wrong thing entirely: it sent the current time at login, not the process start time, so the value was always about zero whenever the timezones happened to agree. It now records its own wall clock once at load and reports Beijing time built from it, matching the semantics of the Windows client. An upgrade forks a new process, so the counter restarts after an upgrade as expected. The first implementation read /proc/self/stat starttime plus /proc/stat btime, which looked like the exact equivalent of the Windows call, but btime is computed from the wall clock at boot and never corrected when NTP later steps the clock, so on WSL2 it drifted by 1.8h. Recording the value in the process itself has no such failure mode. Verified against a Debug server with a WSL Ubuntu 24.04 client and a Windows client: the popup now reports "2.3m" for a Linux process started 2.3 minutes earlier (previously 7h), the startup timestamp is the process load time in Beijing time, and the Windows host still reports 14s right after it connects. Co-Authored-By: deepseek-flash |
||
|
|
4d2abf34d0 |
Feature: Support the Tier 1 MCP tools on Linux clients
All of these tools already had a working wire protocol on the Linux
client (SystemManager.h, common/PTYHandler.h, ScreenHandler.h); only the
server-side client-type gates rejected LNX hosts. kill_process,
exec_command, terminal_open/exec/close and remote_open/close/mouse/
keyboard/clipboard now accept LNX and reject only MAC (plus APK where it
applied). No client change, no capability bit.
exec_command and terminal_exec needed platform-aware plumbing because a
POSIX shell understands none of the Windows constructs: the sentinel is
now "PS1=" / the command / "echo __MCP_DONE_<nonce>__$?" over the Linux
PTY, with output decoded as UTF-8. The PS1= line exists because
interactive bash prints its prompt after every line it reads, which
otherwise leaks into stdout; its echo sits ahead of the command echo and
is removed together with it. The Windows ConPTY and legacy non-PTY forms
are unchanged.
The default command whitelist is now platform-specific: identically named
POSIX commands can write files or change system state (find -exec,
sort -o, hostname), so kDefaultCmdWhitelistPosix only lists commands that
stay read-only even with arguments. env is deliberately excluded, since
"env <program>" runs arbitrary programs and would defeat the whitelist
entirely. An explicit McpCmdWhitelist still overrides both platforms. The
forbidden metacharacter set is split the same way: on Linux it covers
& | < > ; backtick and $( / ${ / !, where ! triggers history expansion in
interactive bash. ^ is not a POSIX metacharacter, so read-only commands
like "grep -v ^# /etc/hosts" are accepted on Linux while Windows keeps
rejecting them.
Input injection had to be sent one MSG64 per COMMAND_SCREEN_CONTROL
packet. The protocol allows batching and the Windows client handles it,
but linux/ScreenHandler.h only processes the first message of a packet,
so a batch left key_press stuck down (X11 autorepeat), click
half-pressed and type emitting only its first character. Splitting the
packets is equivalent for Windows, which processes one message at a time
anyway, and keeps already-deployed Linux clients working without an
upgrade.
Verified on a Debug server against a WSL Ubuntu 24.04 client and a
Windows client: exec_command returned real exit codes (0/1/2) with clean
output, -32007/-32008 negatives, and the POSIX-only ^ allowance;
persistent terminals kept cwd and environment, returned 1 for false and
the last exit code for ";" chains, and closed idempotently; kill_process
killed a test process, returned an empty remaining list and skipped
pid 1; remote_open reported 3840x1140, remote_mouse mapped (0.5,0.5) to
(1920,570), xev showed balanced press/release pairs for keys and buttons,
and a Chinese clipboard round-trip came back as UTF-8. The Windows
regression of the same tools was unchanged, including the multi-monitor
gate on remote_open.
Co-Authored-By: deepseek-flash
|
||
|
|
3a158a241c |
Feature: Support upload_file and download_file on Linux and macOS hosts
Both tools used to reject LNX/MAC targets outright. The server now gates on the target client type instead: a POSIX target must pass an absolute POSIX remote path without a backslash or a ".." segment (-32602 otherwise), while Windows targets keep their exact previous behaviour. upload_file needed no new client command; the POSIX receiver already handles COMMAND_SEND_FILE_V2 and derives the destination from the packet name. It now also reports a real receiver_ack: the upload session records dstClientID/transferID, and OnC2CRecvResult matches the 176 acknowledgement from Linux targets, so a destination write failure becomes -32011 and a missing ack (with bytes in flight) becomes -32001. download_file needed two pieces on the POSIX side, both shared by Linux and macOS through common/FileTransferV2.h: a FileCompletePacketV2 per file with a streaming SHA-256 (new self-contained common/sha256_posix.h, since BCrypt is Windows-only) so the server can count completed files and verify digests, and a TOKEN_DOWNLOAD_ERROR reply when the requested paths do not exist or are denied, which the server maps to -32009/-32010 within milliseconds instead of waiting for the stall watchdog. Zero-byte files were lost when uploading to POSIX targets because the worker sends no data chunk for them and the complete packet carries no path, so the receiver had nothing to create. The server now injects a zero-length final chunk for each empty file, only for POSIX targets; Windows targets keep their existing behaviour. Also fixes a download completion edge case found while testing: the client decides entry order, so a directory may arrive after all files (an empty subdirectory, for example), and the directory branch only completed when the directory count alone covered totalFiles. The check is now filesDone + directoryCount >= totalFiles. Verified end to end against a WSL Linux client and a Windows client: upload and download of a tree with a 3 MB binary, a Chinese filename, an empty file and an empty subdirectory all round-trip with matching SHA-256; the documented error paths (-32602, -32009, -32011, -32001) and the Windows upload/download/C2C regressions were exercised as well. Co-Authored-By: deepseek-flash |
||
|
|
4146c73657 |
Feature: Make Linux a copy_files_c2c destination
The C2C file transfer tool required both ends to be Windows clients. A Linux client can already land the files: the Windows source worker builds every entry name by plain string concatenation of dst_dir and the relative path, so a POSIX dst_dir such as /tmp/recv arrives as "/tmp/recv\sub\file", which the POSIX receiver normalizes to "/" and writes below an absolute path. What was missing was the server gate and any way to tell whether the writes succeeded. The server now accepts LNX/MAC destinations instead of rejecting them, and validates dst_dir by destination type: an absolute Windows path for Windows targets, an absolute POSIX path without backslashes for POSIX targets. The paths and dst_dir arguments also reject embedded NULs, and a POSIX dst_dir is converted to CP936 exactly so unencodable characters fail loudly instead of silently becoming '?'. To make receiver_ack meaningful, a Linux client that receives a C2C transfer now reports what it wrote. It tracks the outcome per transferID, counting a directory entry, the last chunk of a file and the completion packet of an empty file as the three ways an item is settled, with done sets so that source retries and the trailing completion packet never double count. When every item is settled it sends one C2CSendResultPacket back on its main connection under the new TOKEN_C2C_RECV_RESULT (176), with the first errno in the win32err field and the mapped FEV2_* status. A dedicated token is used instead of reusing 175 because a host can be the destination of one transfer while being the source of another, and a destination result must never latch the source side's done flag. The server waits up to five seconds for that acknowledgement after the source reports success, and only for destinations advertising the new CLIENT_CAP_C2C_RECV_ACK capability bit (Linux only, macOS reports nothing). A failed acknowledgement becomes -32011 with the status, errno and received file count; a missing acknowledgement stays an error only for transfers that actually moved bytes, since a transfer of empty files alone gives the receiver nothing to learn totalFiles from. Windows destinations are unchanged and skip the wait entirely. Verified on the debug instance: Windows to Linux (WSL Ubuntu 24.04) with subdirectories, an empty directory, a Chinese file name and a 3 MB binary lands with matching SHA-256 and receiver_ack true; a Windows-style dst_dir returns -32602; an unwritable POSIX destination returns -32011; the existing Windows to Windows cases still pass with receiver_ack false and the same latency. Co-Authored-By: deepseek-flash |
||
|
|
4c0e86dcc5 |
Feature: Upgrade a Linux client from the server
The Linux client is a standalone ELF with no in-memory loader and no COMMAND_UPDATE handler, so the server's upgrade menu silently did nothing for an LNX host. It can now push a new binary and have the client replace and restart itself. The server grows an LNX branch next to EXE/DLL/SC. It takes the ELF from an explicit settings.ini LinuxClientPath, then ghost_linux_amd64 in the program directory, then res\ghost_linux, then IDR_LINUX_GHOST, the copy the server has always embedded for the client-build dialog, so a server with nothing on disk can still upgrade; a configured path that cannot be read is an error rather than a silent fallback. Only x86_64 ELF64 is accepted. The payload adds a 32-byte MD5 trailer to the existing [cmd][size:8][payload] layout, which the Windows branches keep unchanged. linux/ghost in the tree is still the build from before this change and is not updated here. It has to be refreshed before release: the embedded default is copied from it at build time, and a stale copy would install a client with no COMMAND_UPDATE handler, which can never be upgraded remotely again. The client verifies the declared size, elf magic, e_machine against its own ELF header and the MD5 before touching anything, so a miscopied or corrupted file never lands on disk. It then writes a same-directory temp file with fsync and 0755 (a running executable cannot be truncated in place), renames it over its own path atomically, keeps the replaced inode as .old, removes the PID file, forks a detached child that waits for the old process to exit and execs the new binary with the original argv, and finally exits with S_CLIENT_UPDATE. Doing the rename and the exec in that order avoids ETXTBSY, double connections under one client id, and a new instance that isAlreadyRunning() would refuse to start. Any failure (unwritable install directory, bad payload, fork) leaves the client running on the old version; the reason goes to the client log and to the server's message log through TOKEN_CLIENT_MSG, which required moving that struct out of the Windows-only block in common/commands.h. The shared client source had also stopped compiling off Windows: the unknown-header diagnostic in IOCPClient::OnServerReceiving printed TlsEnabled() and m_tls.IsReady() unconditionally, but TlsChannel and m_tls only exist on Windows. That diagnostic now keeps the TLS details where the channel exists and prints just the buffer dump everywhere else. Verified end to end in WSL against the Debug server, foreground and -d daemon: the PID changes, the installed file matches the pushed MD5, the host reconnects, and ghost.old holds the previous binary. A read-only install directory reports "cannot create ...: Permission denied" in the server log with the client still online. With an invalid file at ghost_linux_amd64 the server refuses it and names that path, which shows the disk source wins; with nothing on disk the update goes through from the embedded ELF. Co-Authored-By: deepseek-flash |
||
|
|
bfb17d0d25 |
Feature: Draw the remote cursor in the web desktop out of control mode
Screen frames are captured without the pointer composed in (GDI SRCCOPY, DXGI), so browsers only ever knew the cursor's shape index and could show a cursor just in control mode, where the local pointer stands in for the remote one. Both servers now relay the cursor position that every per-frame header already carries: shape changes go out immediately, position changes at most every 50 ms, and an unchanged cursor is re-sent once a second so a viewer that joins while the pointer is idle still learns where it is. The page hides the local pointer and draws the remote cursor at its true position while out of control mode; entering control mode restores exactly the old behaviour (remote-shaped CSS cursor on desktop, touchpad pointer on touch). A server that never sends x/y leaves the page on its previous fallback. The C++ server broadcasts from the per-frame path, so header-only frames keep a static desktop's cursor fresh; the Go hub dedups and throttles before fanning out. Tests cover the throttle/refresh rules and the relayed payload. Co-Authored-By: deepseek-flash |
||
|
|
6236ed1eb4 |
Fix: Make the Go web console wheel scroll correctly
The Go web server's mouse handler read deltaY as an int, so json.Unmarshal rejected the entire mouse message whenever the browser reported a fractional delta (Chrome's smooth scrolling splits one 100px notch into 33.33 + 33.33 + 33.34), and the wheel was dead while clicks and moves kept working. Treating every event as one notch was wrong the other way: it scrolled three to four times too far, and sub-pixel deltas from a touchpad truncated to zero. The server now accumulates the delta in notch units per client and injects WM_MOUSEWHEEL only once a whole notch is reached. The remainder is rounded, not truncated, so a float sum of 99.99px still lands on exactly one notch and the first notch fires halfway through a physical one, like native scrolling. The page forwards e.deltaMode so line and page based deltas convert correctly, and touchpad flings are capped at 20 notches per event. Verified against a live Go server with a connected client: 100px sends one packet, three 33.33px events send one, 53.33px sends one, sub-pixel events accumulate to none, and the wParam is -120 down / +120 up with SendToScreen returning no error. The MFC web console is untouched. Co-Authored-By: deepseek-flash |
||
|
|
c271911fcb |
Feature: Add copy_files_c2c to transfer files between clients directly
Adds the 54th MCP tool, copy_files_c2c, which asks the source client to push a set of files straight to another online client. Previously the only way to move files between two clients was to download them to the server machine and upload them again, so the data crossed the wire twice and needed free disk on the server. With C2C the server only relays packets and never parses or stores the payload. Protocol. Two new ids in common/commands.h: COMMAND_C2C_SEND_FILES (174), carrying the destination directory followed by a NUL-separated path list, and TOKEN_C2C_SEND_RESULT (175), a fixed 45-byte result packet sent back over the same sub-connection the transfer used. Clients advertise support with the LOGIN_INFOR capability bit CLIENT_CAP_C2C_PATHS (0x0008), exposed server side as Context::SupportsC2CPaths(). File transfer V2 already knew how to push to dstClientID, so the destination side needed no change at all; existing V2 receive paths keep working, and older clients simply do not advertise the bit and are rejected with a clear error instead of hanging. Client. OnC2CSendFiles expands environment variables, collects directories recursively, opens its own sub-connection (with sub-connection auth), and runs FileBatchTransferWorkerV2 in a detached thread, then reports the result on that same connection. Every early exit now reports a structured failure rather than staying silent. The worker needs the process-level InitFileUpload call that the receive path performs lazily, and a source client may never have opened a file manager or received an upload, so the initialization is factored into EnsureV2TransferInited() and called from both paths. Server. copy_files_c2c mirrors the existing upload tool: gates, id parsing, capability checks, path validation, then a session keyed on the source host that WaitC2CDone polls until the result packet arrives. The C2C relay branch used to attach a CDlgFileSend progress dialog to the source's sub-connection; NotifyProc then routed every later packet on that connection to the dialog, which parsed the result packet as a V1 file chunk and dropped it, so the tool always timed out even though the files had arrived. IsC2CTransferPending() now suppresses dialog creation for MCP-driven transfers only, leaving manual Ctrl+V transfers untouched. Errors map to -32001 for a source-side transfer failure, -32010 for access denied, -32009 for a missing path and -32002 for an offline destination. Both hosts must be Windows: the destination is restricted too, because the source embeds dst_dir in each V2 chunk name as an absolute Windows path and only the Windows receiver applies it literally. A Linux or macOS receiver never gets a target directory here (the clipboard flow sets one with COMMAND_C2C_PREPARE, which this path does not send), so it would strip the drive letter and write under / instead. Supporting that needs a prepare packet carrying an explicit path plus an upgrade of those clients, so for now the tool rejects them with -32005 rather than writing somewhere wrong. Verified end to end on the Debug build: three files including a non-ASCII name, an empty directory and a 3 MB binary arrived with matching SHA-256 in 3.2 s, a non-existent destination directory was created, and the negative cases returned the documented codes. mcp_smoke.ps1 passes 41/41 with two new assertions and 27/27 in -SkipHost mode. Design notes, error table and limitations are in docs/Mcp_FileTransfer_Design.md section 14 and docs/Mcp_Design.md section 15. Co-Authored-By: deepseek-flash |
||
|
|
27d40f5678 |
Fix: Expose tool payloads in the content text block
List and query tools put only a human summary in content and kept the real payload in structuredContent. Clients that hand just content to the model (WorkBuddy does) therefore never saw a host id: search_hosts answered "1 host matched" and every follow-up tool was out of reach, and guessed ids 1-3100 could never work because host ids are 64-bit snowflake values. BuildResult now appends the serialized structuredContent as a second text block, as the MCP spec recommends for tools with structured output. The append sits in the single result choke point, so every tool in McpServer, McpMachine and McpChat gains it, including future ones; empty action results such as remote_mouse keep their bare "ok". Tools whose text already carries the payload expose only the difference: exec_command and terminal_exec add exit_code, get_keylog adds counters, get_activity_history exposes records without the duplicated raw dump, and the hosts file reader drops its copy of the content. The override rides in a $ key that BuildResult consumes and removes, so responses change only by the extra block. Verified on a Debug instance: list_all_hosts, search_hosts, get_server_status and list_registry return parseable JSON in content[1] with ids intact, and tools/mcp_smoke.ps1 -SkipHost passes 27/27 with four new assertions. Co-Authored-By: deepseek-flash |
||
|
|
a7dd86ff0f |
Feature: Terminate TLS for the MCP endpoint inside YAMA
MCP was served by a plain httplib::Server, so remote clients could only use cleartext HTTP. YAMA now terminates TLS itself: a small front-end owns the MCP port, sniffs the first byte and either runs a Schannel handshake and forwards the decrypted bytes or passes plaintext through, with httplib moving to a loopback-only internal port. No OpenSSL, no frp change, existing local HTTP clients keep working, and an unusable certificate fails closed instead of falling back to cleartext. The identity loader grew the two things a public certificate needs. ECDSA (P-256/P-384/P-521) keys are persisted by importing PKCS#8 with an NCRYPTBUFFER_PKCS_KEY_NAME parameter, the only route MS Software KSP supports for Schannel; RSA keeps its old export-and-repersist path. Fullchains are accepted, and the intermediates are added to the current user's CA store so Schannel, which builds chains only from system stores, actually sends them. The shared handshake also now buffers a full TLS record before the first AcceptSecurityContext, which a partial ClientHello would otherwise poison (SEC_E_UNKNOWN_CREDENTIALS). Session resumption exposed a second trap: when a client resumes a session, ChangeCipherSpec, Finished and the first application record arrive in one segment and AcceptSecurityContext leaves the application record pending in the session. Nothing drained it, because both callers only decrypt when new ciphertext arrives, so the request waited until the peer gave up (the MCP front-end saw no request at all and the client reported "fetch failed (other side closed)"; the device port had the same hole behind its occasional login timeouts). Decrypt now drains pending data on len == 0, and both the front-end and the device port's handshake thread use it before entering their receive loops. Configuration is McpHttps, McpCertPath, McpKeyPath and McpInternalPort, the first three editable in the MCP settings dialog (the certificate rows stay greyed out until HTTPS is enabled and saving rejects missing files). Verified with a real Let's Encrypt ECDSA fullchain (53 tools over TLS, 401 with no or bad token), a local three-level chain whose intermediate was absent from the store, Node 24's fetch on a resumed session (initialize, notifications/initialized and tools/list all complete), and the device port's RSA handshake as a regression check. Details in docs/Mcp_Design.md section 13. Co-Authored-By: deepseek-flash |
||
|
|
b4cb34fea9 |
Fix: Stop MCP tool timeouts from popping MFC dialogs
A sub-connection's first packet doubles as the readiness packet: the file, service, registry, process, log and terminal tools all get answered that way. Once a tool has given up (timeout or failure) its pending entry is gone, so if the client only gets around to sending that first packet afterwards, MessageHandle cannot tell it apart from a human click and opens the matching modeless dialog - a File Manager window appeared while timeouts were being exercised on this machine. The wait paths now record, per device, which first-packet token the abandoned tool would have sent (MarkLateFirstPacketForTool from WaitPending, WaitPendingRegistry, WaitPendingWrite, WaitFileTransferDone and WaitTerminalReady), and every dialog-opening case consumes that marker before falling back to the MFC path. The marker is one-shot, expires after five minutes and is never set on the success path, so normal use is unaffected; the worst case is that a single manual open on a host that just had an MCP timeout is swallowed. ClientMsg packets are dropped with a log line while a tool is pending for that host: new clients still send the legacy popup message alongside the structured failure token, which would otherwise put a modal box on the server UI during an MCP call. Co-Authored-By: deepseek-flash |
||
|
|
1456882f16 |
Docs: Record the structured failure protocol and -32010
Spell out the new token layout and who sends it, add -32010 to the error table, and narrow -32008 to parameter validation now that capability limits report -32005. Document McpToolTimeoutMs as an ini-only key and correct the note about where the list_files 500-entry cap is applied. Update the remote-control design and the test report so P2, P6 and P8 show as fixed with the measured evidence. Co-Authored-By: deepseek-flash |
||
|
|
3b1626f415 |
Feature: Turn client failure reports into branchable MCP errors
Wire the four new failure tokens into MessageHandle and translate them in the tool builders, so the three previously silent failures now return a code an agent can branch on: list_services on a non-elevated client is -32010 in well under a second instead of a 20 s timeout, list_files and list_registry distinguish a missing path or key (-32009) from an empty one, and download_file no longer waits for the stall watchdog when the remote path does not exist. Access denied gets its own code, -32010, and the win32 code is kept in the message for every case. TakeRegError fills both registry wait flags in one packet because a failing client sends no subkey or value packet at all. OnDownloadError sets the session error without cancelling the file-manager sub-connection, which stays owned by ClearFileTransfer. ListRemoteTopLevelNames treats "not found" as "directory not created yet" so uploading into a fresh directory keeps working now that the client reports it. Also converge the error codes that were overloaded: a multi-monitor host is a capability limit, not a parameter mistake, so remote_open reports -32005 instead of -32008. The tool wait timeout moves from a compile-time constant to McpToolTimeoutMs in settings.ini (default 20000, clamped to 1-600 s), which makes it possible to tune without a rebuild. The smoke test gains the three reproducible negatives. Co-Authored-By: deepseek-flash |
||
|
|
315a0855dc |
Feature: Let the client report structured failures for MCP tools
Four new client-to-server tokens carry a win32/LSTATUS code when a command fails instead of returning empty data: TOKEN_SERVICE_ERROR (170), TOKEN_FILE_LIST_ERROR (171), TOKEN_REG_ERROR (172) and TOKEN_DOWNLOAD_ERROR (173). They sit on byte values that were unused, so existing numbering is untouched. The three data paths that used to collapse "failed" and "empty" into the same packet now distinguish them: OpenSCManager failures, directory enumeration failures and RegOpenKeyEx failures all report the code that was actually returned, and UploadToRemoteV2 reports why it found no file to transfer before the transfer sub-connection is ever created. Every failure branch still sends the packet the old server expects (TOKEN_FILE_LIST, the empty TOKEN_REG_PATH/KEY pair, the ClientMsg popup), so a new client talking to an old server degrades to exactly today's behaviour instead of timing out. Success paths are byte-for- byte unchanged. Co-Authored-By: deepseek-flash |
||
|
|
eaa10cc7d3 |
Fix: Make the MCP command sentinel robust and fail stalled downloads fast
Re-verified every finding of the 2026-10-25 MCP test report against the source and then end-to-end on the Debug instance, and fixed the ones that live on the server. P1/P3/P4 share one root cause: the sentinel was appended to the command line, so any command that swallows the rest of its line (rem, cmd /c, if, for) swallowed the sentinel too and the call always timed out. On ConPTY clients the command and the sentinel are now sent as two lines, the sentinel prints %errorlevel% (whose echoed text is a literal template, not digits) so folding echo can no longer be mistaken for the sentinel, and FindSentinel returns the real exit code (9009, 1, 0, ...) instead of 0/1. Old non-PTY clients keep the single-line form, since their echo skipping depends on the write length. ConPTY also returns a rendered screen stream rather than a byte stream, so stripped VT sequences leave duplicate text behind; output cleaning now cuts through the echoed command line, strips the echoed sentinel line and erases any leftover sentinel text by its per-command nonce. StripAnsi no longer leaves the backslash of an OSC terminated by ST. A terminal session destroyed by a timeout used to report the same "not found" text as a typo in the session id; a 600s tombstone now says what happened instead. download_file gets a stall watchdog: no data for 60s fails with a clear message and releases the host, where a missing remote path used to hold the whole host for the full 600s default timeout. Also corrects the get_activity_history annotation (it does reach the remote host), completes the -32007/-32008/-32009 error table, documents the sentinel design in Mcp_Design.md 12.1, and corrects the report's claim that the tools blocked during a transfer are local DB reads -- they are remote machine-manager fetches, and purely server-local tools are unaffected. Co-Authored-By: deepseek-flash |
||
|
|
1c5fab1645 |
Fix: Stop the client dropping chat messages that begin with e
CChatManager::OnReceive opened with the same heartbeat guard the other managers use, `if (szBuffer[0] == TOKEN_HEARTBEAT) return;`, before it looked at the length. TOKEN_HEARTBEAT is 101, which is also the letter e, and this channel carries free text rather than command bytes, so every message starting with e -- "echo", "error", anything -- was silently discarded. The sender never learned: the server's chat dialog had already written the text into its own log, so the two sides disagreed about what was said. The guard is dead code here. Heartbeats travel on the main connection only, as a multi-byte [101][Heartbeat] packet consumed by the main dispatcher; the server never sends one on a chat sub-connection. Delete it and keep the length check that follows. The server keeps prepending a space when the GBK payload starts with 101, because already-deployed clients still carry the guard and losing the message outright is worse than an invisible leading space. Note the same guard, harmless today, still sits in the machine, file, proxy and screen-hide managers. Verified with the Debug instance and a local Debug client: with the server's space temporarily disabled, chat_send "echo test" and "second line" both showed up verbatim in the client dialog (read back with WM_GETTEXT); with the space restored the first arrives as " echo test". Details in docs/Mcp_Chat_Design.md section 5. Co-Authored-By: deepseek-flash |
||
|
|
cc3e11d30d |
Improve: Cover protocol and policy error codes in the MCP smoke test
The suite only exercised the happy paths, so a regression in the negative paths -- unknown method, unknown tool, a missing required argument, an oversized batch or a policy refusal -- would have gone unnoticed. Add those checks alongside a section that reads the switches from get_server_status, picks a feature that is actually turned off and asserts its tool answers -32006; with every switch on it skips rather than guessing, and with -AuditLog it also asserts the refusal shows up as CALL_DENIED. Document the full error-code table in section 12, including which codes mean "retry with different arguments" and which mean "this is a policy decision, retrying is pointless", and note that a batch call never fails as a whole for per-host errors. Verified against the Debug instance with McpKeylog temporarily set to zero: get_keylog refused with -32006 and the audit log gained the matching CALL_DENIED line, 34 checks passing; with the switch restored 32 pass, and 37 with a search path. Co-Authored-By: deepseek-flash |
||
|
|
7c5bf3e73d |
Feature: Filter search_file results by size, mtime and slim fields
Add four optional arguments to search_file that narrow the match list after the client has returned it: min_size and max_size in bytes, modified_after in either YYYY-MM-DD or YYYY-MM-DD HH:MM:SS form, and name_only to keep just path and name per entry. The client still runs the same name-matched recursive search, so these filters cut the response size and the reasoning work on our side, not the scan time on the host -- the summary sentence says so and totalAll keeps the pre-filter count so a too-narrow condition is obvious. Invalid values (negative sizes, an inverted range, a malformed timestamp) are rejected with -32602 before any packet goes out. The timestamp validator only accepted the ten-character form because its shape loop never allowed the two colons, which rejected every nineteen-character value; the loop now whitelists them. Smoke tests cover the unchanged totalAll under a size filter, the slim name_only payload and a rejected timestamp, for 33 checks when the search path is supplied. Design notes are in section 11.4. Co-Authored-By: deepseek-flash |