@vibecontrols/vibe-plugin-desk-windows 2026.1203.1 → 2026.1203.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -4
- package/dist/backend.d.ts +41 -1
- package/dist/helper.d.ts +14 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -3
- package/helper/DeskWindowsHelper.cs +581 -3
- package/package.json +1 -1
- package/vibe-plugin.sig.json +9 -9
package/README.md
CHANGED
|
@@ -21,7 +21,13 @@ vibe plugin install @vibecontrols/vibe-plugin-desk-windows
|
|
|
21
21
|
|
|
22
22
|
Desk plugins are never trusted by default, so each install asks for confirmation (`--yes` confirms in a non-interactive run). The agent loads a desk plugin only when its `vibe-plugin.sig.json` verifies against a key in the agent's trust root; a changed or unsigned package is refused.
|
|
23
23
|
|
|
24
|
-
**Turn remote control on.** It stays off after the install. The person at the PC turns it on with `vibe config --set desk.remote-control=on`, and can stop everything at any time with `vibe desk kill
|
|
24
|
+
**Turn remote control on.** It stays off after the install. The person at the PC turns it on with `vibe config --set desk.remote-control=on`, and can stop everything at any time with `vibe desk kill`, the kill hotkey **Ctrl+Alt+Shift+K**, or **Stop Steward** in the tray icon's menu.
|
|
25
|
+
|
|
26
|
+
## While a Steward is in control
|
|
27
|
+
|
|
28
|
+
- **Indicator.** An orange border around every screen and a label at the top of the main screen, "Steward <name> is in control. Stop: Ctrl+Alt+Shift+K". Both let clicks through, never take the focus and never appear in a snapshot. A tray icon (a shield) carries the same text and a **Stop Steward** menu item. The indicator comes back by itself if the helper restarts.
|
|
29
|
+
- **Kill hotkey.** Ctrl+Alt+Shift+K works for as long as the agent runs, also while an action is running, and presses the desk meta's kill switch (source `windows-hotkey`; `windows-tray` for the tray menu). Releasing the kill switch stays with the person, on the CLI. If another program already holds the hotkey, the agent log says so and the tray menu and `vibe desk kill` still work.
|
|
30
|
+
- **App allow list.** The plugin tells the desk meta which app is in front (the process name, such as `notepad`, and the executable, `notepad.exe`), so the person's per-app allow list is enforced on every action.
|
|
25
31
|
|
|
26
32
|
**Status.** The package is published and signed, but it is not offered yet: it is not in the agent's plugin catalog, and it is not in the desk meta's `DESK_PROVIDERS`, so neither the agent nor the meta installs it for anyone. Installed by hand as above, it registers as a desk provider and the meta routes actions to it like any other. Offering it is a separate change that:
|
|
27
33
|
|
|
@@ -92,10 +98,10 @@ Starting PowerShell costs one to three seconds, so it happens once. A helper tha
|
|
|
92
98
|
|
|
93
99
|
**What Windows does not allow.**
|
|
94
100
|
|
|
95
|
-
- Input to windows of programs running as administrator is blocked by Windows (UIPI).
|
|
96
|
-
- Nothing can be driven while the screen is
|
|
101
|
+
- Input to windows of programs running as administrator, or as another user, is blocked by Windows (UIPI). Windows drops such input without an error, so the helper compares the target's integrity level with its own first: a click, scroll or typing aimed at such a window, and keys or text while such a window is in front, are refused.
|
|
102
|
+
- Nothing can be seen or driven while a UAC prompt or the lock screen (the secure desktop) is showing. The helper checks the input desktop before every screen action.
|
|
97
103
|
|
|
98
|
-
Both return `DESK_OFFLINE`; they are not silently ignored.
|
|
104
|
+
Both return `DESK_OFFLINE`; they are not silently ignored, and nothing is reported as done that did not happen. The agent never elevates: it runs as the signed-in person, so a UAC prompt is the person's to answer.
|
|
99
105
|
|
|
100
106
|
**What the helper and commands inherit.** The helper and `shell` commands get a short allow-list of the agent's environment (`SystemRoot`, `PATH`, `TEMP`, `USERPROFILE`, ...), never the agent's own tokens.
|
|
101
107
|
|
package/dist/backend.d.ts
CHANGED
|
@@ -26,11 +26,20 @@
|
|
|
26
26
|
* - Coordinates are physical pixels of the screenshot: (0, 0) is its top
|
|
27
27
|
* left corner, which is the virtual screen's, also with several monitors.
|
|
28
28
|
*
|
|
29
|
+
* Own-machine safety hooks for the desk meta (BOFF-16567): `activeApp`
|
|
30
|
+
* names the app in front, so the meta can enforce the person's app allow
|
|
31
|
+
* list (without it the meta refuses every screen action on this desk), and
|
|
32
|
+
* `showIndicator` shows or hides the "Steward in control" indicator: an
|
|
33
|
+
* orange border around every screen, a label naming the Steward and a tray
|
|
34
|
+
* icon with "Stop Steward". The helper also holds the kill hotkey
|
|
35
|
+
* Ctrl+Alt+Shift+K; the hotkey and the tray menu arrive as helper events
|
|
36
|
+
* (`onEvent`), and the plugin presses the meta's kill switch.
|
|
37
|
+
*
|
|
29
38
|
* There is one screen, so every desk id served by one backend shares it.
|
|
30
39
|
*/
|
|
31
40
|
import type { ConfinedPaths, DeskAction, DeskActionType, DeskBackend, DeskBackendResult } from "@vibecontrols/plugin-sdk/desk";
|
|
32
41
|
import { type ShellLauncher } from "./files.js";
|
|
33
|
-
import { type HelperInfo, type HelperOptions, WindowsHelper } from "./helper.js";
|
|
42
|
+
import { type HelperEvent, type HelperInfo, type HelperOptions, WindowsHelper } from "./helper.js";
|
|
34
43
|
export declare const WINDOWS_ACTIONS: readonly ["screenshot", "snapshot", "click", "type", "key", "scroll", "focus_window", "shell", "read_file", "write_file"];
|
|
35
44
|
/** Mirrors the limits in helper/DeskWindowsHelper.cs. */
|
|
36
45
|
export declare const WINDOWS_LIMITS: {
|
|
@@ -51,6 +60,21 @@ export interface WindowsDeskOptions {
|
|
|
51
60
|
abortGraceMs?: number;
|
|
52
61
|
/** Replaces cmd.exe for `shell`. Tests only. */
|
|
53
62
|
shell?: ShellLauncher;
|
|
63
|
+
/** Kill hotkey, tray "Stop Steward" and notices from the helper. */
|
|
64
|
+
onEvent?: (event: HelperEvent) => void;
|
|
65
|
+
}
|
|
66
|
+
/** The app in front, as the desk meta's app allow list reads it. */
|
|
67
|
+
export interface WindowsAppInfo {
|
|
68
|
+
/** Process name without `.exe`, e.g. "notepad" (what `focus_window` takes). */
|
|
69
|
+
name: string;
|
|
70
|
+
/** The executable's file name, e.g. "notepad.exe". */
|
|
71
|
+
bundleId?: string;
|
|
72
|
+
}
|
|
73
|
+
/** What the desk meta asks the indicator to show; null hides it. */
|
|
74
|
+
export interface WindowsIndicatorState {
|
|
75
|
+
stewardId: string;
|
|
76
|
+
stewardName: string;
|
|
77
|
+
since: string;
|
|
54
78
|
}
|
|
55
79
|
/** The `screenshot` warning when secret fields could not be masked. */
|
|
56
80
|
export declare const UNMASKED_WARNING = "secret fields were not masked: UI Automation is unavailable";
|
|
@@ -62,6 +86,9 @@ export declare class WindowsDeskBackend implements DeskBackend {
|
|
|
62
86
|
private starting;
|
|
63
87
|
private closed;
|
|
64
88
|
private readonly env;
|
|
89
|
+
/** The indicator the meta last asked for; a restarted helper shows it again. */
|
|
90
|
+
private indicator;
|
|
91
|
+
private helperStarts;
|
|
65
92
|
constructor(options?: WindowsDeskOptions);
|
|
66
93
|
/** The helper command line. */
|
|
67
94
|
get helperCommand(): readonly string[];
|
|
@@ -76,6 +103,19 @@ export declare class WindowsDeskBackend implements DeskBackend {
|
|
|
76
103
|
signal: AbortSignal;
|
|
77
104
|
paths: ConfinedPaths;
|
|
78
105
|
}): Promise<DeskBackendResult>;
|
|
106
|
+
/**
|
|
107
|
+
* The app of the window in front, for the desk meta's app allow list.
|
|
108
|
+
* Null when no window is in front (the desktop, or a UAC prompt). Throws
|
|
109
|
+
* when the helper cannot tell; the meta then refuses the action.
|
|
110
|
+
*/
|
|
111
|
+
activeApp(signal: AbortSignal): Promise<WindowsAppInfo | null>;
|
|
112
|
+
/**
|
|
113
|
+
* Show the "Steward in control" indicator, or hide it with null. Does not
|
|
114
|
+
* wait for the helper, and starts it if it is not running, so the person
|
|
115
|
+
* sees who is in control before the first action.
|
|
116
|
+
*/
|
|
117
|
+
showIndicator(state: WindowsIndicatorState | null): void;
|
|
118
|
+
private sendIndicator;
|
|
79
119
|
/** Stop the helper. Safe to call twice; later actions are refused. */
|
|
80
120
|
close(): Promise<void>;
|
|
81
121
|
private ensureHelper;
|
package/dist/helper.d.ts
CHANGED
|
@@ -22,6 +22,18 @@ export interface HelperInfo {
|
|
|
22
22
|
uiaError?: string;
|
|
23
23
|
}
|
|
24
24
|
export type HelperReply = Record<string, unknown>;
|
|
25
|
+
/** A line the helper sends on its own, not as an answer. */
|
|
26
|
+
export type HelperEvent = {
|
|
27
|
+
event: "kill";
|
|
28
|
+
/** The kill hotkey, or "Stop Steward" in the tray menu. */
|
|
29
|
+
source: "hotkey" | "tray";
|
|
30
|
+
} | {
|
|
31
|
+
/** Something the person should know, for example a taken kill hotkey. */
|
|
32
|
+
event: "notice";
|
|
33
|
+
message: string;
|
|
34
|
+
};
|
|
35
|
+
/** The event in a protocol line, or null when the line is not one. */
|
|
36
|
+
export declare function parseHelperEvent(line: Record<string, unknown>): HelperEvent | null;
|
|
25
37
|
export interface HelperOptions {
|
|
26
38
|
/** The command that starts the helper, e.g. [powershell.exe, "-NoProfile", ..., "-File", script]. */
|
|
27
39
|
command: readonly string[];
|
|
@@ -31,6 +43,8 @@ export interface HelperOptions {
|
|
|
31
43
|
startTimeoutMs?: number;
|
|
32
44
|
/** After an abort, how long to wait for the late answer before killing the helper. */
|
|
33
45
|
abortGraceMs?: number;
|
|
46
|
+
/** Called for every event line (kill hotkey, tray menu, notices). */
|
|
47
|
+
onEvent?: (event: HelperEvent) => void;
|
|
34
48
|
}
|
|
35
49
|
export declare const HELPER_LIMITS: {
|
|
36
50
|
/** Windows PowerShell compiles the helper at start: allow for a cold disk. */
|
package/dist/index.d.ts
CHANGED
|
@@ -27,7 +27,7 @@ export interface DeskWindowsPluginOptions {
|
|
|
27
27
|
export declare function createDeskWindowsPlugin(options?: DeskWindowsPluginOptions): VibePluginFactory;
|
|
28
28
|
export declare const createPlugin: VibePluginFactory;
|
|
29
29
|
export default createPlugin;
|
|
30
|
-
export { UNMASKED_WARNING, WINDOWS_ACTIONS, WINDOWS_LIMITS, WindowsDeskBackend, } from "./backend.js";
|
|
30
|
+
export { UNMASKED_WARNING, WINDOWS_ACTIONS, WINDOWS_LIMITS, type WindowsAppInfo, WindowsDeskBackend, type WindowsIndicatorState, } from "./backend.js";
|
|
31
31
|
export { defaultPowerShell, deskEnv, helperCommand, PASSED_ENV, } from "./env.js";
|
|
32
|
-
export { HelperError, type HelperInfo, WindowsHelper, WindowsUnavailableError, } from "./helper.js";
|
|
32
|
+
export { HelperError, type HelperEvent, type HelperInfo, parseHelperEvent, WindowsHelper, WindowsUnavailableError, } from "./helper.js";
|
|
33
33
|
export { type KeyStroke, parseKeys } from "./keys.js";
|
package/dist/index.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
import{existsSync as existsSync2,readFileSync}from"fs";import{dirname as dirname3,join as joinPath,win32 as win322}from"path";import{fileURLToPath as fileURLToPath2}from"url";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
|
|
3
3
|
`);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(context)=>{if(onShutdown)await onShutdown(context)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}var BoundLogger=class{logger;source;constructor(logger,source){this.logger=logger,this.source=source}info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};import{win32}from"path";var PASSED_ENV=["SystemRoot","SystemDrive","windir","ComSpec","PATH","PATHEXT","TEMP","TMP","USERPROFILE","USERNAME","USERDOMAIN","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA","PROGRAMDATA","ProgramFiles","ProgramFiles(x86)","ProgramW6432","CommonProgramFiles","CommonProgramFiles(x86)","CommonProgramW6432","PUBLIC","ALLUSERSPROFILE","COMPUTERNAME","OS","PROCESSOR_ARCHITECTURE","NUMBER_OF_PROCESSORS","PSModulePath","LANG","TZ"],DEFAULT_SYSTEM_ROOT="C:\\Windows";function deskEnv(env){let byLowerName=new Map;for(let[key,value]of Object.entries(env))if(value!==void 0)byLowerName.set(key.toLowerCase(),value);let out={};for(let key of PASSED_ENV){let value=byLowerName.get(key.toLowerCase());if(value!==void 0)out[key]=value}if(!out.SystemRoot)out.SystemRoot=DEFAULT_SYSTEM_ROOT;return out}function systemRoot(env){let root=env.SystemRoot;return root&&win32.isAbsolute(root)&&!root.includes('"')?root:DEFAULT_SYSTEM_ROOT}function defaultPowerShell(env){return win32.join(systemRoot(env),"System32","WindowsPowerShell","v1.0","powershell.exe")}function defaultCmd(env){return win32.join(systemRoot(env),"System32","cmd.exe")}function defaultTaskkill(env){return win32.join(systemRoot(env),"System32","taskkill.exe")}function helperCommand(powershell,script){return[powershell,"-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",script]}import{spawn}from"child_process";import{constants}from"fs";import{lstat,mkdir,open}from"fs/promises";import{dirname}from"path";var FILE_LIMITS={maxShellOutput:65536},NO_FOLLOW=constants.O_NOFOLLOW??0,fail=(code,message)=>({ok:!1,error:{code,message}});function errnoOf(err){return typeof err==="object"&&err!==null&&"code"in err?String(err.code):void 0}function fileFailure(err,verb){switch(errnoOf(err)){case"ENOENT":return fail("TARGET_NOT_FOUND",`cannot ${verb}: no such file`);case"ELOOP":return fail("OUTSIDE_WORKSPACE_FOLDER",`cannot ${verb}: the path is a link`);case"EISDIR":return fail("TARGET_NOT_FOUND",`cannot ${verb}: the path is a folder`);case"EACCES":case"EPERM":case"EBUSY":return fail("TARGET_NOT_FOUND",`cannot ${verb}: access denied`);default:return fail("DESK_OFFLINE",`cannot ${verb}: ${errnoOf(err)??"file error"}`)}}async function refuseLink(path){try{if((await lstat(path)).isSymbolicLink())throw Object.assign(Error("the path is a link"),{code:"ELOOP"})}catch(err){if(errnoOf(err)==="ENOENT")return;throw err}}async function readConfinedFile(path,maxBytes){if(!path)return fail("OUTSIDE_WORKSPACE_FOLDER","no confined path was given");let handle;try{await refuseLink(path),handle=await open(path,constants.O_RDONLY|NO_FOLLOW)}catch(err){return fileFailure(err,"read the file")}try{let info=await handle.stat();if(!info.isFile())return fail("TARGET_NOT_FOUND","cannot read the file: not a regular file");let size=Math.max(0,Math.min(maxBytes,info.size)),buffer=Buffer.alloc(size),offset=0;while(offset<size){let{bytesRead}=await handle.read(buffer,offset,size-offset,offset);if(bytesRead===0)break;offset+=bytesRead}return{ok:!0,text:new TextDecoder("utf-8").decode(buffer.subarray(0,offset))}}catch(err){return fileFailure(err,"read the file")}finally{await handle.close()}}async function writeConfinedFile(path,content){if(!path)return fail("OUTSIDE_WORKSPACE_FOLDER","no confined path was given");let handle;try{await mkdir(dirname(path),{recursive:!0,mode:448}),await refuseLink(path),handle=await open(path,constants.O_WRONLY|constants.O_CREAT|constants.O_TRUNC|NO_FOLLOW,384)}catch(err){return fileFailure(err,"write the file")}try{let data=Buffer.from(content,"utf8");return await handle.writeFile(data),{ok:!0,text:`${data.length} bytes written`}}catch(err){return fileFailure(err,"write the file")}finally{await handle.close()}}var windowsShell={spawnSpec(command,env){return{file:defaultCmd(env),args:["/d","/s","/c",`"${command}"`],verbatim:!0}},killTree(pid,env){try{spawn(defaultTaskkill(env),["/PID",String(pid),"/T","/F"],{env,stdio:"ignore",windowsHide:!0}).on("error",()=>{})}catch{}}};function runShell(request){if(!request.cwd)return Promise.resolve(fail("OUTSIDE_WORKSPACE_FOLDER","no confined working folder was given"));if(request.signal.aborted)return Promise.resolve(fail("TIMEOUT","the action was aborted before it started"));let launcher=request.launcher??windowsShell,spec=launcher.spawnSpec(request.command,request.env);return new Promise((resolve)=>{let chunks=[],kept=0,truncated=!1,timedOut=!1,settled=!1,child=spawn(spec.file,spec.args,{cwd:request.cwd,env:request.env,stdio:["ignore","pipe","pipe"],windowsHide:!0,windowsVerbatimArguments:spec.verbatim}),stop=()=>{if(child.pid!==void 0)launcher.killTree(child.pid,request.env)},collect=(chunk)=>{if(kept>=FILE_LIMITS.maxShellOutput){truncated=!0;return}let room=FILE_LIMITS.maxShellOutput-kept;if(chunk.length>room)truncated=!0;let part=chunk.subarray(0,room);chunks.push(part),kept+=part.length};child.stdout?.on("data",collect),child.stderr?.on("data",collect);let timer=setTimeout(()=>{timedOut=!0,stop()},request.timeoutMs),onAbort=()=>stop();request.signal.addEventListener("abort",onAbort,{once:!0});let finish=(result)=>{if(settled)return;settled=!0,clearTimeout(timer),request.signal.removeEventListener("abort",onAbort),resolve(result)};child.on("error",(err)=>{finish(fail("DESK_OFFLINE",`cannot run the command: ${err.message}`))}),child.on("close",(code,signal)=>{if(timedOut){finish(fail("TIMEOUT",`the command did not finish in ${request.timeoutMs}ms`));return}if(request.signal.aborted){finish(fail("TIMEOUT","the command was stopped"));return}let output=Buffer.concat(chunks).toString("utf8"),status=code!==null?`exit ${code}`:`signal ${signal??"unknown"}`;finish({ok:code===0,text:`${status}
|
|
4
4
|
${output}${truncated?`
|
|
5
|
-
[output truncated]`:""}`})})})}import{spawn as spawn2}from"child_process";import{existsSync}from"fs";import{dirname as dirname2,join}from"path";import{fileURLToPath}from"url";class HelperError extends Error{code;constructor(code,message){super(message);this.code=code;this.name="HelperError"}}class WindowsUnavailableError extends Error{constructor(message){super(message);this.name="WindowsUnavailableError"}}var HELPER_LIMITS={startTimeoutMs:30000,abortGraceMs:2000,maxStderr:2000,maxLineBytes:67108864},HELPER_FILES={script:"desk_windows_helper.ps1",source:"DeskWindowsHelper.cs"};function helperScriptPath(from=dirname2(fileURLToPath(import.meta.url))){let candidates=[join(from,"..","helper",HELPER_FILES.script),join(from,"helper",HELPER_FILES.script)];return candidates.find((p)=>existsSync(p))??candidates[0]}var isRecord=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value);class WindowsHelper{options;child=null;nextId=1;pending=new Map;buffered=[];bufferedBytes=0;stderr="";exited=!1;infoValue=null;onReady=null;constructor(options){this.options=options}static async start(options){let helper=new WindowsHelper(options);return await helper.launch(),helper}get info(){if(!this.infoValue)throw Error("the helper has not started");return this.infoValue}get alive(){return!this.exited}launch(){let[command,...args]=this.options.command;if(!command)return Promise.reject(new WindowsUnavailableError("no helper command"));let startTimeoutMs=this.options.startTimeoutMs??HELPER_LIMITS.startTimeoutMs;return new Promise((resolve,reject)=>{let done=!1,finish=(err)=>{if(done)return;if(done=!0,clearTimeout(timer),this.onReady=null,err)this.kill(),reject(err);else resolve()},timer=setTimeout(()=>finish(new WindowsUnavailableError(`the Windows desk helper did not start within ${startTimeoutMs}ms`)),startTimeoutMs);this.onReady=(line)=>{if(typeof line.fatal==="string"){finish(new WindowsUnavailableError(line.fatal));return}if(line.ready!==!0){finish(new WindowsUnavailableError("the Windows desk helper sent no ready line"));return}this.infoValue={width:Number(line.width),height:Number(line.height),left:Number(line.left??0),top:Number(line.top??0),uia:line.uia===!0,...typeof line.uiaError==="string"?{uiaError:line.uiaError}:{}},finish()};let child;try{child=spawn2(command,args,{env:this.options.env,stdio:["pipe","pipe","pipe"],windowsHide:!0})}catch(err){finish(new WindowsUnavailableError(`cannot start the Windows desk helper: ${err instanceof Error?err.message:String(err)}`));return}this.child=child,child.stdout?.on("data",(chunk)=>this.onData(chunk)),child.stderr?.on("data",(chunk)=>{this.stderr=(this.stderr+chunk.toString("utf8")).slice(-HELPER_LIMITS.maxStderr)}),child.stdin?.on("error",()=>{}),child.on("error",(err)=>{this.exited=!0,finish(new WindowsUnavailableError(`cannot start the Windows desk helper (${command}): ${err.message}`)),this.failAll("the Windows desk helper failed")}),child.on("exit",(code,signal)=>{this.exited=!0;let reason=this.stderr.trim().split(`
|
|
6
|
-
`).pop()?.trim();finish(new WindowsUnavailableError(`the Windows desk helper exited (${signal??`code ${code}`})${reason?`: ${reason.slice(0,300)}`:""}`)),this.failAll("the Windows desk helper stopped; it restarts on the next action")})})}onData(chunk){let start=0,newline=chunk.indexOf(10);while(newline!==-1){this.buffered.push(chunk.subarray(start,newline));let line=Buffer.concat(this.buffered).toString("utf8");this.buffered=[],this.bufferedBytes=0,this.onLine(line),start=newline+1,newline=chunk.indexOf(10,start)}if(start<chunk.length){if(this.buffered.push(chunk.subarray(start)),this.bufferedBytes+=chunk.length-start,this.bufferedBytes>HELPER_LIMITS.maxLineBytes)this.buffered=[],this.bufferedBytes=0,this.failAll("the Windows desk helper sent an oversized reply"),this.kill()}}onLine(line){if(!line.trim())return;let parsed;try{parsed=JSON.parse(line)}catch{return}if(!isRecord(parsed))return;if(this.onReady){this.onReady(parsed);return}let id=parsed.id;if(typeof id!=="number")return
|
|
5
|
+
[output truncated]`:""}`})})})}import{spawn as spawn2}from"child_process";import{existsSync}from"fs";import{dirname as dirname2,join}from"path";import{fileURLToPath}from"url";class HelperError extends Error{code;constructor(code,message){super(message);this.code=code;this.name="HelperError"}}class WindowsUnavailableError extends Error{constructor(message){super(message);this.name="WindowsUnavailableError"}}function parseHelperEvent(line){if(line.event==="kill")return{event:"kill",source:line.source==="tray"?"tray":"hotkey"};if(line.event==="notice"&&typeof line.message==="string")return{event:"notice",message:line.message.slice(0,500)};return null}var HELPER_LIMITS={startTimeoutMs:30000,abortGraceMs:2000,maxStderr:2000,maxLineBytes:67108864},HELPER_FILES={script:"desk_windows_helper.ps1",source:"DeskWindowsHelper.cs"};function helperScriptPath(from=dirname2(fileURLToPath(import.meta.url))){let candidates=[join(from,"..","helper",HELPER_FILES.script),join(from,"helper",HELPER_FILES.script)];return candidates.find((p)=>existsSync(p))??candidates[0]}var isRecord=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value);class WindowsHelper{options;child=null;nextId=1;pending=new Map;buffered=[];bufferedBytes=0;stderr="";exited=!1;infoValue=null;onReady=null;constructor(options){this.options=options}static async start(options){let helper=new WindowsHelper(options);return await helper.launch(),helper}get info(){if(!this.infoValue)throw Error("the helper has not started");return this.infoValue}get alive(){return!this.exited}launch(){let[command,...args]=this.options.command;if(!command)return Promise.reject(new WindowsUnavailableError("no helper command"));let startTimeoutMs=this.options.startTimeoutMs??HELPER_LIMITS.startTimeoutMs;return new Promise((resolve,reject)=>{let done=!1,finish=(err)=>{if(done)return;if(done=!0,clearTimeout(timer),this.onReady=null,err)this.kill(),reject(err);else resolve()},timer=setTimeout(()=>finish(new WindowsUnavailableError(`the Windows desk helper did not start within ${startTimeoutMs}ms`)),startTimeoutMs);this.onReady=(line)=>{if(typeof line.fatal==="string"){finish(new WindowsUnavailableError(line.fatal));return}if(line.ready!==!0){finish(new WindowsUnavailableError("the Windows desk helper sent no ready line"));return}this.infoValue={width:Number(line.width),height:Number(line.height),left:Number(line.left??0),top:Number(line.top??0),uia:line.uia===!0,...typeof line.uiaError==="string"?{uiaError:line.uiaError}:{}},finish()};let child;try{child=spawn2(command,args,{env:this.options.env,stdio:["pipe","pipe","pipe"],windowsHide:!0})}catch(err){finish(new WindowsUnavailableError(`cannot start the Windows desk helper: ${err instanceof Error?err.message:String(err)}`));return}this.child=child,child.stdout?.on("data",(chunk)=>this.onData(chunk)),child.stderr?.on("data",(chunk)=>{this.stderr=(this.stderr+chunk.toString("utf8")).slice(-HELPER_LIMITS.maxStderr)}),child.stdin?.on("error",()=>{}),child.on("error",(err)=>{this.exited=!0,finish(new WindowsUnavailableError(`cannot start the Windows desk helper (${command}): ${err.message}`)),this.failAll("the Windows desk helper failed")}),child.on("exit",(code,signal)=>{this.exited=!0;let reason=this.stderr.trim().split(`
|
|
6
|
+
`).pop()?.trim();finish(new WindowsUnavailableError(`the Windows desk helper exited (${signal??`code ${code}`})${reason?`: ${reason.slice(0,300)}`:""}`)),this.failAll("the Windows desk helper stopped; it restarts on the next action")})})}onData(chunk){let start=0,newline=chunk.indexOf(10);while(newline!==-1){this.buffered.push(chunk.subarray(start,newline));let line=Buffer.concat(this.buffered).toString("utf8");this.buffered=[],this.bufferedBytes=0,this.onLine(line),start=newline+1,newline=chunk.indexOf(10,start)}if(start<chunk.length){if(this.buffered.push(chunk.subarray(start)),this.bufferedBytes+=chunk.length-start,this.bufferedBytes>HELPER_LIMITS.maxLineBytes)this.buffered=[],this.bufferedBytes=0,this.failAll("the Windows desk helper sent an oversized reply"),this.kill()}}onLine(line){if(!line.trim())return;let parsed;try{parsed=JSON.parse(line)}catch{return}if(!isRecord(parsed))return;if(this.onReady){this.onReady(parsed);return}let id=parsed.id;if(typeof id!=="number"){let event=parseHelperEvent(parsed);if(event)this.options.onEvent?.(event);return}let entry=this.pending.get(id);if(!entry)return;if(this.pending.delete(id),entry.settled)return;if(entry.settled=!0,parsed.ok===!0){let reply={...parsed};delete reply.id,delete reply.ok,entry.resolve(reply);return}let code=parsed.code==="TARGET_NOT_FOUND"?"TARGET_NOT_FOUND":"DESK_OFFLINE",message=typeof parsed.message==="string"?parsed.message.slice(0,500):"the Windows desk helper refused the request";entry.reject(new HelperError(code,message))}failAll(message){for(let[id,entry]of this.pending)if(this.pending.delete(id),!entry.settled)entry.settled=!0,entry.reject(new HelperError("DESK_OFFLINE",message))}request(op,args={},signal){let child=this.child;if(this.exited||!child?.stdin)return Promise.reject(new HelperError("DESK_OFFLINE","the Windows desk helper is not running"));if(signal?.aborted)return Promise.reject(new HelperError("DESK_OFFLINE","the action was aborted"));let id=this.nextId++;return new Promise((resolve,reject)=>{let onAbort,detach=()=>{if(onAbort)signal?.removeEventListener("abort",onAbort)},entry={resolve:(reply)=>{detach(),resolve(reply)},reject:(err)=>{detach(),reject(err)},settled:!1};if(this.pending.set(id,entry),signal)onAbort=()=>{if(entry.settled)return;entry.settled=!0,reject(new HelperError("DESK_OFFLINE","the action was aborted")),setTimeout(()=>{if(this.pending.has(id))this.failAll("the Windows desk helper stopped answering"),this.kill()},this.options.abortGraceMs??HELPER_LIMITS.abortGraceMs).unref?.()},signal.addEventListener("abort",onAbort,{once:!0});child.stdin?.write(`${JSON.stringify({...args,op,id})}
|
|
7
7
|
`)})}kill(){this.exited=!0,this.failAll("the Windows desk helper was stopped");let child=this.child;if(child&&child.exitCode===null&&child.signalCode===null)child.stdin?.end(),child.kill("SIGTERM"),setTimeout(()=>{if(child.exitCode===null&&child.signalCode===null)child.kill("SIGKILL")},1000).unref?.()}}var KEY_LIMITS={maxCombos:32,maxKeysPerCombo:6},vk=(code,ext=!1)=>({vk:code,ext}),NAMED_KEYS={enter:vk(13),return:vk(13),escape:vk(27),esc:vk(27),backspace:vk(8),tab:vk(9),delete:vk(46,!0),del:vk(46,!0),insert:vk(45,!0),home:vk(36,!0),end:vk(35,!0),pageup:vk(33,!0),page_up:vk(33,!0),pagedown:vk(34,!0),page_down:vk(34,!0),arrowup:vk(38,!0),up:vk(38,!0),arrowdown:vk(40,!0),down:vk(40,!0),arrowleft:vk(37,!0),left:vk(37,!0),arrowright:vk(39,!0),right:vk(39,!0),space:vk(32),control:vk(162),ctrl:vk(162),controlleft:vk(162),controlright:vk(163,!0),shift:vk(160),shiftleft:vk(160),shiftright:vk(161),alt:vk(164),altleft:vk(164),altright:vk(165,!0),altgraph:vk(165,!0),meta:vk(91,!0),metaleft:vk(91,!0),metaright:vk(92,!0),super:vk(91,!0),win:vk(91,!0),windows:vk(91,!0),cmd:vk(91,!0),command:vk(91,!0),capslock:vk(20),numlock:vk(144,!0),scrolllock:vk(145),printscreen:vk(44,!0),print:vk(44,!0),pause:vk(19),contextmenu:vk(93,!0),menu:vk(93,!0)},notFound=(message)=>new HelperError("TARGET_NOT_FOUND",message),quoted=(value)=>JSON.stringify(value).slice(0,40);function splitCombo(combo){if(combo==="+")return["+"];if(combo.endsWith("++")){let head=combo.slice(0,-2);return[...head?head.split("+"):[],"+"]}let parts=combo.split("+");if(parts.some((p)=>p===""))throw notFound(`malformed key combination ${quoted(combo)}`);return parts}function keyStroke(name){let named=NAMED_KEYS[name.toLowerCase()];if(named)return named;let fn=/^[Ff]([1-9]|1[0-9]|2[0-4])$/.exec(name);if(fn)return vk(111+Number(fn[1]));if([...name].length===1){let code=name.codePointAt(0)??0;if(code<32||code===127)throw notFound(`cannot press control character U+${code.toString(16).toUpperCase().padStart(4,"0")}`);if(/^[A-Za-z]$/.test(name))return vk(name.toUpperCase().charCodeAt(0));if(/^[0-9]$/.test(name))return vk(name.charCodeAt(0));return{char:name}}throw notFound(`unknown key ${quoted(name)}`)}function parseCombo(combo){let parts=splitCombo(combo);if(parts.length>KEY_LIMITS.maxKeysPerCombo)throw notFound(`key combination ${quoted(combo)} has more than ${KEY_LIMITS.maxKeysPerCombo} keys`);let strokes=parts.map(keyStroke);if(parts.length===1&&/^[A-Z]$/.test(parts[0]))return[NAMED_KEYS.shift,strokes[0]];return strokes}function parseKeys(keys){if(keys.length===0)throw notFound("no keys were given");if(keys.length>KEY_LIMITS.maxCombos)throw notFound(`more than ${KEY_LIMITS.maxCombos} key combinations`);return keys.map(parseCombo)}function checkTypedText(text){for(let char of text){let code=char.codePointAt(0)??0;if(code<32&&char!==`
|
|
8
8
|
`&&char!=="\r"&&char!=="\t"||code===127)throw notFound(`cannot type control character U+${code.toString(16).toUpperCase().padStart(4,"0")}`)}return text.replace(/\r\n?/g,`
|
|
9
|
-
`)}var SCROLL_STEP_PIXELS=100,MAX_SCROLL_NOTCHES=100;function scrollNotches(pixels){if(!Number.isFinite(pixels)||pixels===0)return 0;let notches=Math.round(pixels/SCROLL_STEP_PIXELS),atLeastOne=notches===0?Math.sign(pixels):notches;return Math.max(-MAX_SCROLL_NOTCHES,Math.min(MAX_SCROLL_NOTCHES,atLeastOne))}var WINDOWS_ACTIONS=["screenshot","snapshot","click","type","key","scroll","focus_window","shell","read_file","write_file"],WINDOWS_LIMITS={maxElements:500,maxText:20000},fail2=(code,message)=>({ok:!1,error:{code,message}});function targetArg(target){switch(target.by){case"ref":return{by:"ref",ref:target.ref};case"point":return{by:"point",x:target.x,y:target.y};case"window":return target.title===void 0?{by:"window",app:target.app}:{by:"window",app:target.app,title:target.title}}}var UNMASKED_WARNING="secret fields were not masked: UI Automation is unavailable";class WindowsDeskBackend{options;kind="windows";actions=WINDOWS_ACTIONS;helper=null;starting=null;closed=!1;env;constructor(options={}){this.options=options;this.env=deskEnv(options.env??process.env)}get helperCommand(){return this.options.helperCommand??helperCommand(this.options.powershell??defaultPowerShell(this.env),helperScriptPath())}async connect(){return(await this.ensureHelper()).info}async act(action,context){if(this.closed)return fail2("DESK_OFFLINE","the Windows desk is stopped");try{switch(action.type){case"read_file":return await readConfinedFile(context.paths.path,action.maxBytes);case"write_file":return await writeConfinedFile(context.paths.path,action.content);case"shell":return await runShell({command:action.command,cwd:context.paths.cwd,timeoutMs:action.timeoutMs,env:this.env,signal:context.signal,...this.options.shell?{launcher:this.options.shell}:{}});default:return await this.screenAction(action,context.signal)}}catch(err){if(err instanceof HelperError)return fail2(err.code,err.message);if(err instanceof WindowsUnavailableError)return fail2("DESK_OFFLINE",err.message);return fail2("DESK_OFFLINE",(err instanceof Error?err.message:String(err)).slice(0,200))}}async close(){this.closed=!0;let starting=this.starting;if(this.starting=null,this.helper?.kill(),this.helper=null,starting)try{(await starting).kill()}catch{}}ensureHelper(){if(this.closed)return Promise.reject(new WindowsUnavailableError("the Windows desk is stopped"));if(this.helper?.alive)return Promise.resolve(this.helper);if(this.helper=null,!this.starting){let start=this.options.start??WindowsHelper.start;this.starting=start({command:this.helperCommand,env:this.env,...this.options.startTimeoutMs!==void 0?{startTimeoutMs:this.options.startTimeoutMs}:{},...this.options.abortGraceMs!==void 0?{abortGraceMs:this.options.abortGraceMs}:{}}).then((helper)=>{if(this.closed)throw helper.kill(),new WindowsUnavailableError("the Windows desk is stopped");
|
|
9
|
+
`)}var SCROLL_STEP_PIXELS=100,MAX_SCROLL_NOTCHES=100;function scrollNotches(pixels){if(!Number.isFinite(pixels)||pixels===0)return 0;let notches=Math.round(pixels/SCROLL_STEP_PIXELS),atLeastOne=notches===0?Math.sign(pixels):notches;return Math.max(-MAX_SCROLL_NOTCHES,Math.min(MAX_SCROLL_NOTCHES,atLeastOne))}var WINDOWS_ACTIONS=["screenshot","snapshot","click","type","key","scroll","focus_window","shell","read_file","write_file"],WINDOWS_LIMITS={maxElements:500,maxText:20000},fail2=(code,message)=>({ok:!1,error:{code,message}});function targetArg(target){switch(target.by){case"ref":return{by:"ref",ref:target.ref};case"point":return{by:"point",x:target.x,y:target.y};case"window":return target.title===void 0?{by:"window",app:target.app}:{by:"window",app:target.app,title:target.title}}}var UNMASKED_WARNING="secret fields were not masked: UI Automation is unavailable";class WindowsDeskBackend{options;kind="windows";actions=WINDOWS_ACTIONS;helper=null;starting=null;closed=!1;env;indicator=null;helperStarts=0;constructor(options={}){this.options=options;this.env=deskEnv(options.env??process.env)}get helperCommand(){return this.options.helperCommand??helperCommand(this.options.powershell??defaultPowerShell(this.env),helperScriptPath())}async connect(){return(await this.ensureHelper()).info}async act(action,context){if(this.closed)return fail2("DESK_OFFLINE","the Windows desk is stopped");try{switch(action.type){case"read_file":return await readConfinedFile(context.paths.path,action.maxBytes);case"write_file":return await writeConfinedFile(context.paths.path,action.content);case"shell":return await runShell({command:action.command,cwd:context.paths.cwd,timeoutMs:action.timeoutMs,env:this.env,signal:context.signal,...this.options.shell?{launcher:this.options.shell}:{}});default:return await this.screenAction(action,context.signal)}}catch(err){if(err instanceof HelperError)return fail2(err.code,err.message);if(err instanceof WindowsUnavailableError)return fail2("DESK_OFFLINE",err.message);return fail2("DESK_OFFLINE",(err instanceof Error?err.message:String(err)).slice(0,200))}}async activeApp(signal){let app=(await(await this.ensureHelper()).request("active_app",{},signal)).app;if(typeof app!=="object"||app===null)return null;let record=app,name=typeof record.name==="string"?record.name:"";if(!name)return null;return{name,...typeof record.exe==="string"&&record.exe?{bundleId:record.exe}:{}}}showIndicator(state){if(this.indicator=state,this.closed)return;this.sendIndicator().catch(()=>{})}async sendIndicator(){await(await this.ensureHelper()).request("indicator",{state:this.indicator?{stewardName:this.indicator.stewardName,since:this.indicator.since}:null})}async close(){this.closed=!0;let starting=this.starting;if(this.starting=null,this.helper?.kill(),this.helper=null,starting)try{(await starting).kill()}catch{}}ensureHelper(){if(this.closed)return Promise.reject(new WindowsUnavailableError("the Windows desk is stopped"));if(this.helper?.alive)return Promise.resolve(this.helper);if(this.helper=null,!this.starting){let start=this.options.start??WindowsHelper.start;this.starting=start({command:this.helperCommand,env:this.env,...this.options.startTimeoutMs!==void 0?{startTimeoutMs:this.options.startTimeoutMs}:{},...this.options.abortGraceMs!==void 0?{abortGraceMs:this.options.abortGraceMs}:{},...this.options.onEvent?{onEvent:this.options.onEvent}:{}}).then((helper)=>{if(this.closed)throw helper.kill(),new WindowsUnavailableError("the Windows desk is stopped");if(this.helper=helper,this.helperStarts+=1,this.helperStarts>1&&this.indicator)helper.request("indicator",{state:{stewardName:this.indicator.stewardName,since:this.indicator.since}}).catch(()=>{});return helper}).finally(()=>{this.starting=null})}return this.starting}async screenAction(action,signal){let keys=action.type==="key"?parseKeys(action.keys):null,text=action.type==="type"?checkTypedText(action.text):null,helper=await this.ensureHelper(),call=(op,args={})=>helper.request(op,args,signal);switch(action.type){case"screenshot":{let reply=await call("screenshot"),png=typeof reply.png==="string"?reply.png:"";if(!png)return fail2("DESK_OFFLINE","the screenshot was empty");return{ok:!0,screenshotPng:new Uint8Array(Buffer.from(png,"base64")),...typeof reply.unmasked==="string"?{text:UNMASKED_WARNING}:{}}}case"snapshot":{let reply=await call("snapshot");return{ok:!0,snapshot:reply.snapshot,text:typeof reply.text==="string"?reply.text:""}}case"click":return await call("click",{target:targetArg(action.target),button:action.button??"left",count:action.count??1}),{ok:!0};case"type":return await call("type",{text,...action.target?{target:targetArg(action.target)}:{}}),{ok:!0};case"key":return await call("key",{combos:keys}),{ok:!0};case"scroll":return await call("scroll",{notchesX:scrollNotches(action.dx),notchesY:scrollNotches(action.dy),...action.target?{target:targetArg(action.target)}:{}}),{ok:!0};case"focus_window":{let reply=await call("focus_window",{app:action.app,...action.title!==void 0?{title:action.title}:{}});return{ok:!0,...typeof reply.title==="string"?{text:reply.title}:{}}}default:return fail2("DESK_OFFLINE",`a Windows desk cannot ${action.type}`)}}}var PLUGIN_NAME="desk-windows",PLUGIN_PACKAGE_NAME="@vibecontrols/vibe-plugin-desk-windows",PLUGIN_VERSION=getPluginVersion(),DESK_PROVIDER_TYPE="desk",DESK_WINDOWS_CONFIG={powershell:"desk-windows.powershell"};function getPluginVersion(){try{let dir=dirname3(fileURLToPath2(import.meta.url));for(let i=0;i<10&&dir&&dir!==dirname3(dir);i++){let pkgPath=joinPath(dir,"package.json");if(existsSync2(pkgPath))try{let pkg=JSON.parse(readFileSync(pkgPath,"utf8"));if(pkg.name===PLUGIN_PACKAGE_NAME&&typeof pkg.version==="string")return pkg.version}catch{}dir=dirname3(dir)}}catch{}return"0.0.0"}class NotWindowsError extends Error{constructor(platform){super(`desk-windows runs only on Windows (this is ${platform})`);this.name="NotWindowsError"}}function parsePowerShell(value){if(!value)return;if(!win322.isAbsolute(value)||value.includes('"'))return;return/(^|\\)powershell\.exe$/i.test(value)?value:void 0}function describeScreen(info){let accessibility=info.uia?"UI Automation on":`UI Automation off: ${info.uiaError??"unavailable"}`;return`${info.width}x${info.height} at (${info.left}, ${info.top}), ${accessibility}`}function createDeskWindowsPlugin(options={}){return(ctx)=>{let log=new BoundLogger(ctx.logger,PLUGIN_NAME),backend=null,lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"desk-windows.ready",onInit:async(host)=>{let platform=options.platform??process.platform;if(platform!=="win32"){let err=new NotWindowsError(platform);throw log.error(err.message),err}let configured=(await host.getConfig?.(DESK_WINDOWS_CONFIG.powershell))?.trim(),powershell=parsePowerShell(configured);if(configured&&!powershell)log.warn(`${DESK_WINDOWS_CONFIG.powershell} is not an absolute path to powershell.exe; using the default`);let candidate=new WindowsDeskBackend({onEvent:(event)=>{if(event.event==="notice"){log.warn(event.message);return}let kill=host.serviceRegistry?.getService?.("desk","kill");if(!kill){log.error("Stop Steward was pressed but the desk plugin is not loaded; run `vibe desk kill`");return}log.warn(`kill switch pressed on this PC (${event.source})`),kill.kill(`windows-${event.source}`)},...powershell?{powershell}:{},...options.env?{env:options.env}:{},...options.start?{start:options.start}:{},...options.helperCommand?{helperCommand:options.helperCommand}:{}}),info;try{info=await candidate.connect()}catch(err){await candidate.close();let reason=err instanceof Error?err.message:String(err);throw log.error(`Windows desk not started: ${reason}`),Error(`desk-windows cannot start: ${reason}`,{cause:err})}if(backend=candidate,host.serviceRegistry?.registerProvider?.(DESK_PROVIDER_TYPE,candidate,PLUGIN_NAME),log.info(`Windows desk registered (${describeScreen(info)})`),!info.uia)log.warn("snapshots and refs are unavailable without UI Automation; screenshots are returned unmasked with a warning")},onShutdown:async(context)=>{let current=backend;backend=null,await current?.close(),log.info(`Windows desk stopped (${context?.reason??"shutdown"})`)}});return{name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"Steward desk provider: a Windows desktop driven through the desk API with UI Automation",tags:["backend","provider"],capabilities:{telemetry:!0},onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop}}}var createPlugin=createDeskWindowsPlugin(),src_default=createPlugin;export{DESK_PROVIDER_TYPE,DESK_WINDOWS_CONFIG,HelperError,NotWindowsError,PASSED_ENV,UNMASKED_WARNING,WINDOWS_ACTIONS,WINDOWS_LIMITS,WindowsDeskBackend,WindowsHelper,WindowsUnavailableError,createDeskWindowsPlugin,createPlugin,src_default as default,defaultPowerShell,deskEnv,helperCommand,parseHelperEvent,parseKeys,parsePowerShell};
|
|
@@ -23,6 +23,20 @@
|
|
|
23
23
|
// key of a combo are held while the last is pressed
|
|
24
24
|
// scroll notchesX, notchesY (positive: right, down), optional target
|
|
25
25
|
// focus_window app (process name), optional title (substring)
|
|
26
|
+
// active_app the app of the window in front: {"app":{"name","exe","title"}}
|
|
27
|
+
// or {"app":null} when no window is in front
|
|
28
|
+
// indicator state {stewardName, since} shows the "Steward in control"
|
|
29
|
+
// indicator; state null hides it
|
|
30
|
+
//
|
|
31
|
+
// Events the helper sends on its own, without an id (BOFF-16566):
|
|
32
|
+
//
|
|
33
|
+
// {"event":"kill","source":"hotkey"|"tray"} the person pressed the kill
|
|
34
|
+
// hotkey (Ctrl+Alt+Shift+K) or "Stop Steward" in the tray menu
|
|
35
|
+
// {"event":"notice","message":"..."} something the person should
|
|
36
|
+
// know, for example a kill hotkey another program already holds
|
|
37
|
+
//
|
|
38
|
+
// The indicator, the tray icon and the hotkey live on their own UI thread
|
|
39
|
+
// (StewardControls), so the hotkey works while a request is running.
|
|
26
40
|
//
|
|
27
41
|
// Coordinates on the wire are pixels of the screenshot: (0, 0) is the top
|
|
28
42
|
// left corner of the virtual screen. The process is per-monitor DPI aware,
|
|
@@ -34,8 +48,11 @@
|
|
|
34
48
|
// "via":"uia" or "via":"input". Everything else, and every case where the
|
|
35
49
|
// element has no fitting pattern, goes through SendInput, which is subject
|
|
36
50
|
// to UIPI: windows of elevated (administrator) processes and the secure
|
|
37
|
-
// desktop (UAC, lock screen) cannot be driven.
|
|
38
|
-
//
|
|
51
|
+
// desktop (UAC, lock screen) cannot be driven. Windows drops such input
|
|
52
|
+
// without an error, so the helper checks first: a target (or, for keys, the
|
|
53
|
+
// window in front) whose process runs at a higher integrity level than the
|
|
54
|
+
// helper, and any action while the input desktop is not the user's desktop,
|
|
55
|
+
// is refused with DESK_OFFLINE, not reported as done. Text itself is always typed as keystrokes:
|
|
39
56
|
// ValuePattern.SetValue would replace the whole value, not type at the caret.
|
|
40
57
|
|
|
41
58
|
using System;
|
|
@@ -218,6 +235,56 @@ namespace VibeDeskWindows
|
|
|
218
235
|
[DllImport("user32.dll")]
|
|
219
236
|
public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
|
|
220
237
|
|
|
238
|
+
public const int WM_HOTKEY = 0x0312;
|
|
239
|
+
public const uint MOD_ALT = 0x0001;
|
|
240
|
+
public const uint MOD_CONTROL = 0x0002;
|
|
241
|
+
public const uint MOD_SHIFT = 0x0004;
|
|
242
|
+
public const uint MOD_NOREPEAT = 0x4000;
|
|
243
|
+
public const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
|
|
244
|
+
public const uint TOKEN_QUERY = 0x0008;
|
|
245
|
+
public const int TokenIntegrityLevel = 25;
|
|
246
|
+
public const int UOI_NAME = 2;
|
|
247
|
+
public const uint DESKTOP_READOBJECTS = 0x0001;
|
|
248
|
+
|
|
249
|
+
[DllImport("user32.dll", SetLastError = true)]
|
|
250
|
+
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint modifiers, uint vk);
|
|
251
|
+
|
|
252
|
+
[DllImport("user32.dll")]
|
|
253
|
+
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
|
|
254
|
+
|
|
255
|
+
[DllImport("kernel32.dll")]
|
|
256
|
+
public static extern uint GetCurrentProcessId();
|
|
257
|
+
|
|
258
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
259
|
+
public static extern IntPtr OpenProcess(uint access, bool inherit, uint processId);
|
|
260
|
+
|
|
261
|
+
[DllImport("kernel32.dll")]
|
|
262
|
+
public static extern bool CloseHandle(IntPtr handle);
|
|
263
|
+
|
|
264
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
265
|
+
public static extern bool QueryFullProcessImageNameW(IntPtr process, int flags, StringBuilder name, ref int size);
|
|
266
|
+
|
|
267
|
+
[DllImport("advapi32.dll", SetLastError = true)]
|
|
268
|
+
public static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
|
|
269
|
+
|
|
270
|
+
[DllImport("advapi32.dll", SetLastError = true)]
|
|
271
|
+
public static extern bool GetTokenInformation(IntPtr token, int infoClass, IntPtr info, int length, out int returned);
|
|
272
|
+
|
|
273
|
+
[DllImport("advapi32.dll")]
|
|
274
|
+
public static extern IntPtr GetSidSubAuthority(IntPtr sid, uint index);
|
|
275
|
+
|
|
276
|
+
[DllImport("advapi32.dll")]
|
|
277
|
+
public static extern IntPtr GetSidSubAuthorityCount(IntPtr sid);
|
|
278
|
+
|
|
279
|
+
[DllImport("user32.dll", SetLastError = true)]
|
|
280
|
+
public static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access);
|
|
281
|
+
|
|
282
|
+
[DllImport("user32.dll")]
|
|
283
|
+
public static extern bool CloseDesktop(IntPtr desktop);
|
|
284
|
+
|
|
285
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
286
|
+
public static extern bool GetUserObjectInformationW(IntPtr obj, int index, StringBuilder info, int length, out int needed);
|
|
287
|
+
|
|
221
288
|
[DllImport("dwmapi.dll")]
|
|
222
289
|
public static extern int DwmGetWindowAttribute(IntPtr hWnd, int attribute, out int value, int size);
|
|
223
290
|
|
|
@@ -297,6 +364,8 @@ namespace VibeDeskWindows
|
|
|
297
364
|
private static StreamWriter output;
|
|
298
365
|
private static Dictionary<string, RefEntry> refs = new Dictionary<string, RefEntry>();
|
|
299
366
|
private static string uiaError;
|
|
367
|
+
private static uint ownPid;
|
|
368
|
+
private static int ownIntegrity = -1;
|
|
300
369
|
|
|
301
370
|
public static int Run()
|
|
302
371
|
{
|
|
@@ -340,6 +409,9 @@ namespace VibeDeskWindows
|
|
|
340
409
|
ready["uiaError"] = uiaError;
|
|
341
410
|
}
|
|
342
411
|
Write(ready);
|
|
412
|
+
ownPid = Native.GetCurrentProcessId();
|
|
413
|
+
ownIntegrity = IntegrityOf(ownPid);
|
|
414
|
+
StewardControls.Start();
|
|
343
415
|
|
|
344
416
|
string line;
|
|
345
417
|
while ((line = input.ReadLine()) != null)
|
|
@@ -363,12 +435,35 @@ namespace VibeDeskWindows
|
|
|
363
435
|
}
|
|
364
436
|
Write(Handle(request));
|
|
365
437
|
}
|
|
438
|
+
StewardControls.Stop();
|
|
366
439
|
return 0;
|
|
367
440
|
}
|
|
368
441
|
|
|
442
|
+
private static readonly object writeLock = new object();
|
|
443
|
+
|
|
369
444
|
private static void Write(Dictionary<string, object> message)
|
|
370
445
|
{
|
|
371
|
-
|
|
446
|
+
string line = json.Serialize(message);
|
|
447
|
+
lock (writeLock)
|
|
448
|
+
{
|
|
449
|
+
output.WriteLine(line);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/// <summary>Send an event line (no id). Called from the UI thread too.</summary>
|
|
454
|
+
internal static void Emit(string name, string key, string value)
|
|
455
|
+
{
|
|
456
|
+
Dictionary<string, object> message = new Dictionary<string, object>();
|
|
457
|
+
message["event"] = name;
|
|
458
|
+
message[key] = value;
|
|
459
|
+
try
|
|
460
|
+
{
|
|
461
|
+
Write(message);
|
|
462
|
+
}
|
|
463
|
+
catch (Exception)
|
|
464
|
+
{
|
|
465
|
+
// stdout is gone: the agent stopped, and the helper is about to exit.
|
|
466
|
+
}
|
|
372
467
|
}
|
|
373
468
|
|
|
374
469
|
private static Dictionary<string, object> Handle(Dictionary<string, object> request)
|
|
@@ -377,8 +472,14 @@ namespace VibeDeskWindows
|
|
|
377
472
|
try
|
|
378
473
|
{
|
|
379
474
|
string op = GetString(request, "op");
|
|
475
|
+
if (op != "active_app" && op != "indicator")
|
|
476
|
+
{
|
|
477
|
+
RequireUserDesktop();
|
|
478
|
+
}
|
|
380
479
|
switch (op)
|
|
381
480
|
{
|
|
481
|
+
case "active_app": reply = OpActiveApp(); break;
|
|
482
|
+
case "indicator": reply = OpIndicator(request); break;
|
|
382
483
|
case "screenshot": reply = OpScreenshot(); break;
|
|
383
484
|
case "snapshot": reply = OpSnapshot(); break;
|
|
384
485
|
case "click": reply = OpClick(request); break;
|
|
@@ -544,6 +645,10 @@ namespace VibeDeskWindows
|
|
|
544
645
|
}
|
|
545
646
|
uint pid;
|
|
546
647
|
Native.GetWindowThreadProcessId(hWnd, out pid);
|
|
648
|
+
if (pid == ownPid)
|
|
649
|
+
{
|
|
650
|
+
return true; // the indicator and the tray window are not the person's apps
|
|
651
|
+
}
|
|
547
652
|
string app;
|
|
548
653
|
if (!apps.TryGetValue(pid, out app))
|
|
549
654
|
{
|
|
@@ -1097,6 +1202,210 @@ namespace VibeDeskWindows
|
|
|
1097
1202
|
throw new OpException("TARGET_NOT_FOUND", "unknown target kind");
|
|
1098
1203
|
}
|
|
1099
1204
|
|
|
1205
|
+
// ------------------------------------------------------------------
|
|
1206
|
+
// UIPI and the secure desktop
|
|
1207
|
+
|
|
1208
|
+
/// <summary>
|
|
1209
|
+
/// The mandatory integrity level (the RID of the token's integrity
|
|
1210
|
+
/// SID: 0x2000 medium, 0x3000 high, 0x4000 system) of a process, or
|
|
1211
|
+
/// int.MaxValue when it cannot be read, which is the case for
|
|
1212
|
+
/// processes of other users and of SYSTEM.
|
|
1213
|
+
/// </summary>
|
|
1214
|
+
private static int IntegrityOf(uint pid)
|
|
1215
|
+
{
|
|
1216
|
+
IntPtr process = Native.OpenProcess(Native.PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
|
|
1217
|
+
if (process == IntPtr.Zero)
|
|
1218
|
+
{
|
|
1219
|
+
return int.MaxValue;
|
|
1220
|
+
}
|
|
1221
|
+
try
|
|
1222
|
+
{
|
|
1223
|
+
IntPtr token;
|
|
1224
|
+
if (!Native.OpenProcessToken(process, Native.TOKEN_QUERY, out token))
|
|
1225
|
+
{
|
|
1226
|
+
return int.MaxValue;
|
|
1227
|
+
}
|
|
1228
|
+
try
|
|
1229
|
+
{
|
|
1230
|
+
int length;
|
|
1231
|
+
Native.GetTokenInformation(token, Native.TokenIntegrityLevel, IntPtr.Zero, 0, out length);
|
|
1232
|
+
if (length <= 0)
|
|
1233
|
+
{
|
|
1234
|
+
return int.MaxValue;
|
|
1235
|
+
}
|
|
1236
|
+
IntPtr buffer = Marshal.AllocHGlobal(length);
|
|
1237
|
+
try
|
|
1238
|
+
{
|
|
1239
|
+
if (!Native.GetTokenInformation(token, Native.TokenIntegrityLevel, buffer, length, out length))
|
|
1240
|
+
{
|
|
1241
|
+
return int.MaxValue;
|
|
1242
|
+
}
|
|
1243
|
+
IntPtr sid = Marshal.ReadIntPtr(buffer); // TOKEN_MANDATORY_LABEL.Label.Sid
|
|
1244
|
+
int count = Marshal.ReadByte(Native.GetSidSubAuthorityCount(sid));
|
|
1245
|
+
if (count <= 0)
|
|
1246
|
+
{
|
|
1247
|
+
return int.MaxValue;
|
|
1248
|
+
}
|
|
1249
|
+
return Marshal.ReadInt32(Native.GetSidSubAuthority(sid, (uint)(count - 1)));
|
|
1250
|
+
}
|
|
1251
|
+
finally
|
|
1252
|
+
{
|
|
1253
|
+
Marshal.FreeHGlobal(buffer);
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
finally
|
|
1257
|
+
{
|
|
1258
|
+
Native.CloseHandle(token);
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
finally
|
|
1262
|
+
{
|
|
1263
|
+
Native.CloseHandle(process);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
/// <summary>
|
|
1268
|
+
/// Refuses input to a window whose process runs at a higher integrity
|
|
1269
|
+
/// level than the helper (an administrator program, or another
|
|
1270
|
+
/// user's): Windows (UIPI) drops that input without an error.
|
|
1271
|
+
/// </summary>
|
|
1272
|
+
private static void RequireDrivable(IntPtr window)
|
|
1273
|
+
{
|
|
1274
|
+
if (window == IntPtr.Zero)
|
|
1275
|
+
{
|
|
1276
|
+
return;
|
|
1277
|
+
}
|
|
1278
|
+
IntPtr root = Native.GetAncestor(window, Native.GA_ROOT);
|
|
1279
|
+
uint pid;
|
|
1280
|
+
Native.GetWindowThreadProcessId(root == IntPtr.Zero ? window : root, out pid);
|
|
1281
|
+
if (pid == 0 || pid == ownPid)
|
|
1282
|
+
{
|
|
1283
|
+
return;
|
|
1284
|
+
}
|
|
1285
|
+
if (IntegrityOf(pid) > ownIntegrity)
|
|
1286
|
+
{
|
|
1287
|
+
throw new OpException("DESK_OFFLINE",
|
|
1288
|
+
"the window belongs to a program running as administrator or as another user; Windows does not let this desk send it input");
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
/// <summary>The window under a resolved target: its own window, or the one at its point.</summary>
|
|
1293
|
+
private static void RequireDrivableAt(TargetPoint point)
|
|
1294
|
+
{
|
|
1295
|
+
if (point.Window != IntPtr.Zero)
|
|
1296
|
+
{
|
|
1297
|
+
RequireDrivable(point.Window);
|
|
1298
|
+
return;
|
|
1299
|
+
}
|
|
1300
|
+
Native.POINT at;
|
|
1301
|
+
at.X = point.X;
|
|
1302
|
+
at.Y = point.Y;
|
|
1303
|
+
RequireDrivable(Native.WindowFromPoint(at));
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
/// <summary>
|
|
1307
|
+
/// Refuses every screen action while the input desktop is not the
|
|
1308
|
+
/// user's desktop: a UAC prompt or the lock screen (the secure
|
|
1309
|
+
/// desktop) is showing, and nothing can be seen or driven.
|
|
1310
|
+
/// </summary>
|
|
1311
|
+
private static void RequireUserDesktop()
|
|
1312
|
+
{
|
|
1313
|
+
IntPtr desktop = Native.OpenInputDesktop(0, false, Native.DESKTOP_READOBJECTS);
|
|
1314
|
+
if (desktop == IntPtr.Zero)
|
|
1315
|
+
{
|
|
1316
|
+
throw new OpException("DESK_OFFLINE",
|
|
1317
|
+
"a UAC prompt or the lock screen is showing; the person must deal with it before the desk can continue");
|
|
1318
|
+
}
|
|
1319
|
+
try
|
|
1320
|
+
{
|
|
1321
|
+
StringBuilder name = new StringBuilder(64);
|
|
1322
|
+
int needed;
|
|
1323
|
+
if (Native.GetUserObjectInformationW(desktop, Native.UOI_NAME, name, name.Capacity * 2, out needed)
|
|
1324
|
+
&& !string.Equals(name.ToString(), "Default", StringComparison.OrdinalIgnoreCase))
|
|
1325
|
+
{
|
|
1326
|
+
throw new OpException("DESK_OFFLINE",
|
|
1327
|
+
"a UAC prompt or the lock screen is showing; the person must deal with it before the desk can continue");
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
finally
|
|
1331
|
+
{
|
|
1332
|
+
Native.CloseDesktop(desktop);
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// ------------------------------------------------------------------
|
|
1337
|
+
// own-machine safety (BOFF-16567): the app in front and the indicator
|
|
1338
|
+
|
|
1339
|
+
private static Dictionary<string, object> OpActiveApp()
|
|
1340
|
+
{
|
|
1341
|
+
Dictionary<string, object> reply = new Dictionary<string, object>();
|
|
1342
|
+
reply["app"] = null;
|
|
1343
|
+
IntPtr front = Native.GetForegroundWindow();
|
|
1344
|
+
if (front == IntPtr.Zero)
|
|
1345
|
+
{
|
|
1346
|
+
return reply;
|
|
1347
|
+
}
|
|
1348
|
+
IntPtr root = Native.GetAncestor(front, Native.GA_ROOT);
|
|
1349
|
+
if (root != IntPtr.Zero)
|
|
1350
|
+
{
|
|
1351
|
+
front = root;
|
|
1352
|
+
}
|
|
1353
|
+
uint pid;
|
|
1354
|
+
Native.GetWindowThreadProcessId(front, out pid);
|
|
1355
|
+
if (pid == 0 || pid == ownPid)
|
|
1356
|
+
{
|
|
1357
|
+
return reply;
|
|
1358
|
+
}
|
|
1359
|
+
string name;
|
|
1360
|
+
try
|
|
1361
|
+
{
|
|
1362
|
+
name = Process.GetProcessById((int)pid).ProcessName;
|
|
1363
|
+
}
|
|
1364
|
+
catch (Exception)
|
|
1365
|
+
{
|
|
1366
|
+
return reply;
|
|
1367
|
+
}
|
|
1368
|
+
string exe = name + ".exe";
|
|
1369
|
+
IntPtr process = Native.OpenProcess(Native.PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
|
|
1370
|
+
if (process != IntPtr.Zero)
|
|
1371
|
+
{
|
|
1372
|
+
try
|
|
1373
|
+
{
|
|
1374
|
+
StringBuilder path = new StringBuilder(1024);
|
|
1375
|
+
int size = path.Capacity;
|
|
1376
|
+
if (Native.QueryFullProcessImageNameW(process, 0, path, ref size))
|
|
1377
|
+
{
|
|
1378
|
+
exe = Path.GetFileName(path.ToString());
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
finally
|
|
1382
|
+
{
|
|
1383
|
+
Native.CloseHandle(process);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
Dictionary<string, object> app = new Dictionary<string, object>();
|
|
1387
|
+
app["name"] = Clip(name, MaxName);
|
|
1388
|
+
app["exe"] = Clip(exe, MaxName);
|
|
1389
|
+
app["title"] = Clip(WindowTitle(front), MaxName);
|
|
1390
|
+
reply["app"] = app;
|
|
1391
|
+
return reply;
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
private static Dictionary<string, object> OpIndicator(Dictionary<string, object> request)
|
|
1395
|
+
{
|
|
1396
|
+
Dictionary<string, object> state = GetMap(request, "state");
|
|
1397
|
+
if (state == null)
|
|
1398
|
+
{
|
|
1399
|
+
StewardControls.Hide();
|
|
1400
|
+
}
|
|
1401
|
+
else
|
|
1402
|
+
{
|
|
1403
|
+
string steward = (GetString(state, "stewardName") ?? "").Trim();
|
|
1404
|
+
StewardControls.Show(Clip(steward.Length > 0 ? steward : "A Steward", 60));
|
|
1405
|
+
}
|
|
1406
|
+
return new Dictionary<string, object>();
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1100
1409
|
/// <summary>Refuses a ref or window target that another window covers at its point.</summary>
|
|
1101
1410
|
private static void RequireUncovered(TargetPoint point)
|
|
1102
1411
|
{
|
|
@@ -1348,6 +1657,7 @@ namespace VibeDeskWindows
|
|
|
1348
1657
|
private static Dictionary<string, object> OpClick(Dictionary<string, object> request)
|
|
1349
1658
|
{
|
|
1350
1659
|
TargetPoint point = Resolve(GetMap(request, "target"));
|
|
1660
|
+
RequireDrivableAt(point);
|
|
1351
1661
|
bool right = GetString(request, "button") == "right";
|
|
1352
1662
|
int count = GetInt(request, "count", 1) == 2 ? 2 : 1;
|
|
1353
1663
|
// A right or double click has no control pattern: it is input.
|
|
@@ -1374,6 +1684,7 @@ namespace VibeDeskWindows
|
|
|
1374
1684
|
if (target != null)
|
|
1375
1685
|
{
|
|
1376
1686
|
TargetPoint point = Resolve(target);
|
|
1687
|
+
RequireDrivableAt(point);
|
|
1377
1688
|
bool focused = false;
|
|
1378
1689
|
if (point.Element != null)
|
|
1379
1690
|
{
|
|
@@ -1397,6 +1708,8 @@ namespace VibeDeskWindows
|
|
|
1397
1708
|
Send(click);
|
|
1398
1709
|
}
|
|
1399
1710
|
}
|
|
1711
|
+
// The keystrokes go to the window in front, whatever was focused.
|
|
1712
|
+
RequireDrivable(Native.GetForegroundWindow());
|
|
1400
1713
|
List<Native.INPUT> inputs = new List<Native.INPUT>();
|
|
1401
1714
|
foreach (char unit in text)
|
|
1402
1715
|
{
|
|
@@ -1444,6 +1757,7 @@ namespace VibeDeskWindows
|
|
|
1444
1757
|
}
|
|
1445
1758
|
presses.Add(ComboInputs(combo));
|
|
1446
1759
|
}
|
|
1760
|
+
RequireDrivable(Native.GetForegroundWindow());
|
|
1447
1761
|
foreach (List<Native.INPUT> press in presses)
|
|
1448
1762
|
{
|
|
1449
1763
|
Send(press);
|
|
@@ -1549,6 +1863,7 @@ namespace VibeDeskWindows
|
|
|
1549
1863
|
if (target != null)
|
|
1550
1864
|
{
|
|
1551
1865
|
TargetPoint point = Resolve(target);
|
|
1866
|
+
RequireDrivableAt(point);
|
|
1552
1867
|
if (point.Element != null && (notchesX != 0 || notchesY != 0)
|
|
1553
1868
|
&& TryScrollPattern(point.Element, notchesX, notchesY))
|
|
1554
1869
|
{
|
|
@@ -1557,6 +1872,14 @@ namespace VibeDeskWindows
|
|
|
1557
1872
|
RequireUncovered(point);
|
|
1558
1873
|
MovePointer(point.X, point.Y);
|
|
1559
1874
|
}
|
|
1875
|
+
else
|
|
1876
|
+
{
|
|
1877
|
+
Native.POINT cursor;
|
|
1878
|
+
if (Native.GetCursorPos(out cursor))
|
|
1879
|
+
{
|
|
1880
|
+
RequireDrivable(Native.WindowFromPoint(cursor));
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1560
1883
|
List<Native.INPUT> inputs = new List<Native.INPUT>();
|
|
1561
1884
|
// A positive wheel delta scrolls up, so "down" is negative.
|
|
1562
1885
|
for (int i = 0; i < Math.Abs(notchesY); i++)
|
|
@@ -1583,4 +1906,259 @@ namespace VibeDeskWindows
|
|
|
1583
1906
|
return reply;
|
|
1584
1907
|
}
|
|
1585
1908
|
}
|
|
1909
|
+
|
|
1910
|
+
/// <summary>
|
|
1911
|
+
/// The person's controls while a Steward drives this PC (BOFF-16567,
|
|
1912
|
+
/// BOFF-16566): an orange border around every screen and a label naming
|
|
1913
|
+
/// the Steward (both click-through, never focused, never in a snapshot),
|
|
1914
|
+
/// a tray icon with "Stop Steward", and the kill hotkey Ctrl+Alt+Shift+K.
|
|
1915
|
+
/// The hotkey is registered for as long as the helper runs; the border,
|
|
1916
|
+
/// label and tray icon show only while a Steward is in control.
|
|
1917
|
+
///
|
|
1918
|
+
/// Everything runs on one STA thread with its own message loop, so the
|
|
1919
|
+
/// hotkey and the tray menu answer while a request is running on the
|
|
1920
|
+
/// main thread. Pressing either sends {"event":"kill"} to the plugin,
|
|
1921
|
+
/// which presses the desk meta's kill switch.
|
|
1922
|
+
/// </summary>
|
|
1923
|
+
internal static class StewardControls
|
|
1924
|
+
{
|
|
1925
|
+
public const string HotkeyLabel = "Ctrl+Alt+Shift+K";
|
|
1926
|
+
private const int HotkeyId = 0x5D31;
|
|
1927
|
+
private const uint VK_K = 0x4B;
|
|
1928
|
+
private const int BorderWidth = 4;
|
|
1929
|
+
|
|
1930
|
+
private static Thread thread;
|
|
1931
|
+
private static ControlWindow window;
|
|
1932
|
+
private static readonly ManualResetEvent started = new ManualResetEvent(false);
|
|
1933
|
+
|
|
1934
|
+
public static void Start()
|
|
1935
|
+
{
|
|
1936
|
+
thread = new Thread(Loop);
|
|
1937
|
+
thread.IsBackground = true;
|
|
1938
|
+
thread.Name = "steward-controls";
|
|
1939
|
+
thread.SetApartmentState(ApartmentState.STA);
|
|
1940
|
+
thread.Start();
|
|
1941
|
+
// The hotkey must be live before the first action; the thread
|
|
1942
|
+
// creates one invisible window, which takes milliseconds.
|
|
1943
|
+
started.WaitOne(5000);
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
public static void Stop()
|
|
1947
|
+
{
|
|
1948
|
+
try
|
|
1949
|
+
{
|
|
1950
|
+
Post(delegate { window.HideIndicator(); Application.ExitThread(); });
|
|
1951
|
+
}
|
|
1952
|
+
catch (OpException)
|
|
1953
|
+
{
|
|
1954
|
+
// never started
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
|
|
1958
|
+
public static void Show(string steward)
|
|
1959
|
+
{
|
|
1960
|
+
Post(delegate { window.ShowIndicator(steward); });
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
public static void Hide()
|
|
1964
|
+
{
|
|
1965
|
+
Post(delegate { window.HideIndicator(); });
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
private static void Post(MethodInvoker call)
|
|
1969
|
+
{
|
|
1970
|
+
ControlWindow current = window;
|
|
1971
|
+
if (current == null || !current.IsHandleCreated)
|
|
1972
|
+
{
|
|
1973
|
+
throw new OpException("DESK_OFFLINE", "the Steward indicator is not running");
|
|
1974
|
+
}
|
|
1975
|
+
current.BeginInvoke(call);
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
private static void Loop()
|
|
1979
|
+
{
|
|
1980
|
+
try
|
|
1981
|
+
{
|
|
1982
|
+
window = new ControlWindow();
|
|
1983
|
+
IntPtr handle = window.Handle; // creates the window on this thread
|
|
1984
|
+
if (!Native.RegisterHotKey(handle, HotkeyId, Native.MOD_CONTROL | Native.MOD_ALT | Native.MOD_SHIFT | Native.MOD_NOREPEAT, VK_K))
|
|
1985
|
+
{
|
|
1986
|
+
Helper.Emit("notice", "message",
|
|
1987
|
+
"the kill hotkey " + HotkeyLabel + " is taken by another program (error " + Marshal.GetLastWin32Error()
|
|
1988
|
+
+ "); stop the Steward from the tray icon or with `vibe desk kill`");
|
|
1989
|
+
}
|
|
1990
|
+
started.Set();
|
|
1991
|
+
Application.Run();
|
|
1992
|
+
Native.UnregisterHotKey(handle, HotkeyId);
|
|
1993
|
+
}
|
|
1994
|
+
catch (Exception ex)
|
|
1995
|
+
{
|
|
1996
|
+
started.Set();
|
|
1997
|
+
Helper.Emit("notice", "message", "the Steward indicator and kill hotkey could not start: " + ex.Message);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
/// <summary>Invisible window that owns the hotkey and the indicator.</summary>
|
|
2002
|
+
private sealed class ControlWindow : Form
|
|
2003
|
+
{
|
|
2004
|
+
private readonly List<Form> overlays = new List<Form>();
|
|
2005
|
+
private NotifyIcon tray;
|
|
2006
|
+
|
|
2007
|
+
public ControlWindow()
|
|
2008
|
+
{
|
|
2009
|
+
ShowInTaskbar = false;
|
|
2010
|
+
FormBorderStyle = FormBorderStyle.None;
|
|
2011
|
+
Opacity = 0;
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
protected override void SetVisibleCore(bool value)
|
|
2015
|
+
{
|
|
2016
|
+
base.SetVisibleCore(false); // never shown
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
protected override void WndProc(ref Message m)
|
|
2020
|
+
{
|
|
2021
|
+
if (m.Msg == Native.WM_HOTKEY && m.WParam.ToInt32() == HotkeyId)
|
|
2022
|
+
{
|
|
2023
|
+
Helper.Emit("kill", "source", "hotkey");
|
|
2024
|
+
return;
|
|
2025
|
+
}
|
|
2026
|
+
base.WndProc(ref m);
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
public void ShowIndicator(string steward)
|
|
2030
|
+
{
|
|
2031
|
+
HideIndicator();
|
|
2032
|
+
string text = "Steward " + steward + " is in control. Stop: " + HotkeyLabel;
|
|
2033
|
+
foreach (Screen screen in Screen.AllScreens)
|
|
2034
|
+
{
|
|
2035
|
+
Rectangle b = screen.Bounds;
|
|
2036
|
+
overlays.Add(Overlay.Bar(new Rectangle(b.Left, b.Top, b.Width, BorderWidth)));
|
|
2037
|
+
overlays.Add(Overlay.Bar(new Rectangle(b.Left, b.Bottom - BorderWidth, b.Width, BorderWidth)));
|
|
2038
|
+
overlays.Add(Overlay.Bar(new Rectangle(b.Left, b.Top, BorderWidth, b.Height)));
|
|
2039
|
+
overlays.Add(Overlay.Bar(new Rectangle(b.Right - BorderWidth, b.Top, BorderWidth, b.Height)));
|
|
2040
|
+
}
|
|
2041
|
+
Rectangle primary = Screen.PrimaryScreen.Bounds;
|
|
2042
|
+
overlays.Add(Overlay.Label(text, primary));
|
|
2043
|
+
foreach (Form overlay in overlays)
|
|
2044
|
+
{
|
|
2045
|
+
overlay.Show();
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
tray = new NotifyIcon();
|
|
2049
|
+
tray.Icon = SystemIcons.Shield;
|
|
2050
|
+
tray.Text = Clip63("Steward " + steward + " is in control");
|
|
2051
|
+
ContextMenu menu = new ContextMenu();
|
|
2052
|
+
menu.MenuItems.Add(new MenuItem("Stop Steward (" + HotkeyLabel + ")", delegate { Helper.Emit("kill", "source", "tray"); }));
|
|
2053
|
+
tray.ContextMenu = menu;
|
|
2054
|
+
tray.Visible = true;
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
public void HideIndicator()
|
|
2058
|
+
{
|
|
2059
|
+
foreach (Form overlay in overlays)
|
|
2060
|
+
{
|
|
2061
|
+
overlay.Close();
|
|
2062
|
+
overlay.Dispose();
|
|
2063
|
+
}
|
|
2064
|
+
overlays.Clear();
|
|
2065
|
+
if (tray != null)
|
|
2066
|
+
{
|
|
2067
|
+
tray.Visible = false;
|
|
2068
|
+
tray.Dispose();
|
|
2069
|
+
tray = null;
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
private static string Clip63(string text)
|
|
2074
|
+
{
|
|
2075
|
+
return text.Length <= 63 ? text : text.Substring(0, 62) + "…";
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
/// <summary>A topmost, click-through, never-activated window.</summary>
|
|
2080
|
+
private sealed class Overlay : Form
|
|
2081
|
+
{
|
|
2082
|
+
private const int WS_EX_TOPMOST = 0x00000008;
|
|
2083
|
+
private const int WS_EX_TRANSPARENT = 0x00000020;
|
|
2084
|
+
private const int WS_EX_TOOLWINDOW = 0x00000080;
|
|
2085
|
+
private const int WS_EX_NOACTIVATE = 0x08000000;
|
|
2086
|
+
|
|
2087
|
+
private static readonly Color Orange = Color.FromArgb(255, 140, 0);
|
|
2088
|
+
|
|
2089
|
+
private Overlay(Rectangle bounds)
|
|
2090
|
+
{
|
|
2091
|
+
FormBorderStyle = FormBorderStyle.None;
|
|
2092
|
+
ShowInTaskbar = false;
|
|
2093
|
+
StartPosition = FormStartPosition.Manual;
|
|
2094
|
+
TopMost = true;
|
|
2095
|
+
Bounds = bounds;
|
|
2096
|
+
// Opacity below 1 makes the window layered, which together
|
|
2097
|
+
// with WS_EX_TRANSPARENT lets every click pass through it and
|
|
2098
|
+
// keeps it out of WindowFromPoint (the cover check).
|
|
2099
|
+
Opacity = 0.9;
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
public static Overlay Bar(Rectangle bounds)
|
|
2103
|
+
{
|
|
2104
|
+
Overlay bar = new Overlay(bounds);
|
|
2105
|
+
bar.BackColor = Orange;
|
|
2106
|
+
return bar;
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
public static Overlay Label(string text, Rectangle screen)
|
|
2110
|
+
{
|
|
2111
|
+
Font font = new Font("Segoe UI", 10f, FontStyle.Bold);
|
|
2112
|
+
Size size = TextRenderer.MeasureText(text, font);
|
|
2113
|
+
int width = size.Width + 24;
|
|
2114
|
+
int height = size.Height + 10;
|
|
2115
|
+
Overlay label = new Overlay(new Rectangle(
|
|
2116
|
+
screen.Left + (screen.Width - width) / 2, screen.Top + BorderWidth, width, height));
|
|
2117
|
+
label.BackColor = Orange;
|
|
2118
|
+
label.caption = text;
|
|
2119
|
+
label.captionFont = font;
|
|
2120
|
+
return label;
|
|
2121
|
+
}
|
|
2122
|
+
|
|
2123
|
+
// Drawn, not a child Label control: a child window would not be
|
|
2124
|
+
// click-through like its layered, transparent parent.
|
|
2125
|
+
private string caption;
|
|
2126
|
+
private Font captionFont;
|
|
2127
|
+
|
|
2128
|
+
protected override void OnPaint(PaintEventArgs e)
|
|
2129
|
+
{
|
|
2130
|
+
base.OnPaint(e);
|
|
2131
|
+
if (caption != null)
|
|
2132
|
+
{
|
|
2133
|
+
TextRenderer.DrawText(e.Graphics, caption, captionFont, ClientRectangle, Color.Black,
|
|
2134
|
+
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine);
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
protected override void Dispose(bool disposing)
|
|
2139
|
+
{
|
|
2140
|
+
if (disposing && captionFont != null)
|
|
2141
|
+
{
|
|
2142
|
+
captionFont.Dispose();
|
|
2143
|
+
captionFont = null;
|
|
2144
|
+
}
|
|
2145
|
+
base.Dispose(disposing);
|
|
2146
|
+
}
|
|
2147
|
+
|
|
2148
|
+
protected override bool ShowWithoutActivation
|
|
2149
|
+
{
|
|
2150
|
+
get { return true; }
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
protected override CreateParams CreateParams
|
|
2154
|
+
{
|
|
2155
|
+
get
|
|
2156
|
+
{
|
|
2157
|
+
CreateParams cp = base.CreateParams;
|
|
2158
|
+
cp.ExStyle |= WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE;
|
|
2159
|
+
return cp;
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
1586
2164
|
}
|
package/package.json
CHANGED
package/vibe-plugin.sig.json
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"format": "vibecontrols-plugin-signature/v1",
|
|
3
3
|
"package": "@vibecontrols/vibe-plugin-desk-windows",
|
|
4
|
-
"version": "2026.1203.
|
|
4
|
+
"version": "2026.1203.2",
|
|
5
5
|
"keyId": "vc-plugins-2026-11",
|
|
6
6
|
"files": {
|
|
7
7
|
"LICENSE": "sha512-Rww0A8k2ve2punYCwOToupYSPGq/A3QUcNVtHYu19iwzkWPnAVcWx4YwZbmzTkruL9OtfGgl+WjFyqo+R3rqlQ==",
|
|
8
|
-
"README.md": "sha512-
|
|
9
|
-
"dist/backend.d.ts": "sha512-
|
|
8
|
+
"README.md": "sha512-0CVoFc/DrIgl6oubhbGP5mr/bpda4eSWO8hQY3rjMfuFWoY/VR37VWRzwm3iUK7XCJkM8JntXcZyIaaYSAw9wQ==",
|
|
9
|
+
"dist/backend.d.ts": "sha512-Yd3Q1zxCG6/r/tyIqUH5poaiTdzzRcAdlDGYXoTPXW0MDHpq8s9GZ7+ilG89UF9ZZarBVXaxNLAJkaPX/m+J1g==",
|
|
10
10
|
"dist/env.d.ts": "sha512-Aoqc8Jt9PGDZABBKr05UUaI9dT26HTPo0UY8rQ0fdKnm3DjkQar7uH73rlJk8+UoEbEIiyf1B0yARaM2/gvjlQ==",
|
|
11
11
|
"dist/files.d.ts": "sha512-7MRMPUdB5iYdRex5D1EbeB6vHt0pUOejH7yh/RoRlE/6boyALNYcvz+Jb/J8leJAgPAX7CZbDdqBy1/XiyZC3g==",
|
|
12
|
-
"dist/helper.d.ts": "sha512-
|
|
13
|
-
"dist/index.d.ts": "sha512-
|
|
14
|
-
"dist/index.js": "sha512-
|
|
12
|
+
"dist/helper.d.ts": "sha512-5Fa5lClnCxhM/r513oUof6t/NygUV//uylH3aO/AGdyWiZuCsxP1z5bmmfjJSIhXxV0OxZL/EbWIZYZN4h/cuA==",
|
|
13
|
+
"dist/index.d.ts": "sha512-yks/e/LR7iEYLJu1XbvjETYihk14E6cw2WzsLmtC16h3JDKaiBaS91jrxVPqUPtHEs508ggtsoZAbxcJb1YP0g==",
|
|
14
|
+
"dist/index.js": "sha512-EjySrIMD8HAzPNZhsIRMc38UBzkLEL4X9I25rEUgpb5WRpOdB+XghR3lKxVmN/VbtBxLz5PlcP7ZqgtWWoEI/Q==",
|
|
15
15
|
"dist/keys.d.ts": "sha512-sw1eFejKWrYtHZ8uppKibRtxPT65V+VL6F0kNZkPprL6SfuC04vjhZrDEQp+7JqsbbbhV8XjRU0IQCqwwy0DZA==",
|
|
16
|
-
"helper/DeskWindowsHelper.cs": "sha512-
|
|
16
|
+
"helper/DeskWindowsHelper.cs": "sha512-m1gr9tsFlZCbhNT96IaRM9PshMrmNXv6FFqGh2oU49Fk/GOqVVz/XBhdk3UVhtvGfYOHOlsJU69k27Vy7BycjA==",
|
|
17
17
|
"helper/desk_windows_helper.ps1": "sha512-nN3kJuiPFut7zjiKQrZ3bBHnxyzvAL7CLeWrbz830xErwBeKD41W2PMSNpi010W13VdkrV6HZ3ea77mNg5yVPQ==",
|
|
18
|
-
"package.json": "sha512-
|
|
18
|
+
"package.json": "sha512-GICsnMZC6ogSm5yNP27Mdk/D1E1oqy0MBx7uNY8SrkhNRvSZbRv5/0BPAn/VbBXsKXKVKlR9Jd/laQziaR3Swg=="
|
|
19
19
|
},
|
|
20
|
-
"signature": "
|
|
20
|
+
"signature": "BWN2RUgxavga2I42S7bCXJ5ivALdSeBja1Oum0FFVLIpvOg1slf7Y/2JzEi72cxFKrPdZJq3QQH20Hrnl3VPDg=="
|
|
21
21
|
}
|