pi-winnotify-toast 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +177 -3
- package/acceptance.mjs +78 -0
- package/index.ts +566 -0
- package/package.json +38 -6
- package/pifocus.cs +378 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lev Asmanov
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,177 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# pi-winnotify-toast
|
|
2
|
+
|
|
3
|
+
Windows toast notifications for the [Pi coding agent](https://pi.dev), with three
|
|
4
|
+
things a generic notifier does not do:
|
|
5
|
+
|
|
6
|
+
1. **The body is the answer, not "ready for input".** At hour six of a long run the
|
|
7
|
+
only question is *do I need to come back*, and the first line of the reply answers
|
|
8
|
+
it. Markdown is stripped, the text is capped.
|
|
9
|
+
2. **A real focus check.** The foreground window is read through Win32
|
|
10
|
+
(`GetForegroundWindow` + `GetWindowText`) and compared with the title Pi gives the
|
|
11
|
+
tab (`π - <project>`). If the tab is in front, nothing is sent — the answer is
|
|
12
|
+
already on screen. A notifier gated on *inactivity* (a timeout) is a different
|
|
13
|
+
thing: you can be active in another window and get nothing.
|
|
14
|
+
3. **Urgent, so "Do Not Disturb" does not eat it.** Windows turns DND on by itself
|
|
15
|
+
while a fullscreen app holds the session (Discord, a game), and a normal toast is
|
|
16
|
+
then accepted and silently dropped. This one is created with `Scenario=Urgent`
|
|
17
|
+
and a ten-minute expiry, so it also waits in the Action Center when the popup was
|
|
18
|
+
missed.
|
|
19
|
+
|
|
20
|
+
Runs in native Windows Pi, including when launched from Git Bash.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pi install npm:pi-winnotify-toast
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Then `/reload`. Check it in one keystroke:
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
/wintoast-test
|
|
32
|
+
/wintoast-test your own body text
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Windows helper and local changes
|
|
36
|
+
|
|
37
|
+
The npm package ships [`pifocus.cs`](pifocus.cs) as source. There is no prebuilt
|
|
38
|
+
`pifocus.exe` in the package and npm installation does not compile one. The
|
|
39
|
+
extension bootstraps Windows registration on the first notification or when you
|
|
40
|
+
run `/wintoast-bootstrap`. Bootstrap uses the Windows .NET Framework C# compiler
|
|
41
|
+
(`%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\csc.exe`) to build
|
|
42
|
+
`pifocus.exe` if it is missing or the bundled source has changed. It needs
|
|
43
|
+
Windows PowerShell 5.1 and runs with the current user's permissions.
|
|
44
|
+
|
|
45
|
+
The helper registers the Windows COM callback that receives the text entered
|
|
46
|
+
in the toast. It also handles the shortcut and `piwinnotify:` URI used to focus
|
|
47
|
+
Pi. Before submitting a toast, the sender starts or reuses a background helper
|
|
48
|
+
in the current Windows session and waits for its ready signal. The helper
|
|
49
|
+
normally exits 11 minutes after the sender last renewed its lease. Each toast
|
|
50
|
+
has a 10-minute expiration time.
|
|
51
|
+
|
|
52
|
+
With the defaults, bootstrap creates these per-user entries.
|
|
53
|
+
|
|
54
|
+
| Location | What it contains |
|
|
55
|
+
|---|---|
|
|
56
|
+
| `%APPDATA%\Microsoft\Windows\Start Menu\Programs\Pi.lnk` | Shortcut to the helper with the AppUserModelID and toast activator CLSID |
|
|
57
|
+
| `HKCU\Software\Classes\AppUserModelId\Pi.WinNotify.Toast` | Notification identity, display name, icon and activator CLSID |
|
|
58
|
+
| `HKCU\Software\Classes\CLSID\{7B0E5F3A-2C41-4D9B-8E77-3F1A6B9C0D52}` | COM registration with a `LocalServer32` command pointing to the local helper |
|
|
59
|
+
| `HKCU\Software\Classes\piwinnotify` | URI handler pointing to the helper |
|
|
60
|
+
| `%LOCALAPPDATA%\pi-winnotify-toast\` | Helper source and executable, focus marker, lease file, activation log and reply queues |
|
|
61
|
+
|
|
62
|
+
Reply queues may contain the text typed in a toast, encoded as Base64. The
|
|
63
|
+
default extension log is separate at `%LOCALAPPDATA%\pi-notify.log`.
|
|
64
|
+
|
|
65
|
+
### Remove the extension
|
|
66
|
+
|
|
67
|
+
1. Run `/wintoast-unregister` in Pi. It removes the shortcut and registry keys,
|
|
68
|
+
signals the background helper to stop, and deletes the helper directory,
|
|
69
|
+
including any replies still stored there.
|
|
70
|
+
2. Run `pi remove npm:pi-winnotify-toast` in your terminal to remove the package
|
|
71
|
+
from Pi. Use the original install source if you installed from Git or a
|
|
72
|
+
local path.
|
|
73
|
+
3. To remove the separate decision log, delete
|
|
74
|
+
`%LOCALAPPDATA%\pi-notify.log` or the file selected by `PI_WINTOAST_LOG`.
|
|
75
|
+
|
|
76
|
+
## Reply from a notification
|
|
77
|
+
|
|
78
|
+
Type in the toast and press **Send**. The background COM callback writes a UTF-8
|
|
79
|
+
reply as Base64 on one line of the originating process’s queue. The extension claims the queue
|
|
80
|
+
atomically at settlement or on a 500 ms idle poll. It submits replies one at a
|
|
81
|
+
time and waits for Pi to acknowledge each user message. Unconfirmed submissions
|
|
82
|
+
are retained for inspection. New notifications replace the previous notification
|
|
83
|
+
for the same Pi process. When Pi stays in the background, the result of a toast
|
|
84
|
+
reply appears in a new banner that also accepts replies.
|
|
85
|
+
|
|
86
|
+
## How it decides
|
|
87
|
+
|
|
88
|
+
On Pi's `agent_settled` event (once the run is over and nothing else will start on its
|
|
89
|
+
own; not on `agent_end`, which also fires for retries and compaction):
|
|
90
|
+
|
|
91
|
+
Immediately before posting an automatic toast:
|
|
92
|
+
|
|
93
|
+
> read the foreground window → is it a terminal **and** does its title look like this
|
|
94
|
+
> session? → in front: silence · otherwise: toast
|
|
95
|
+
|
|
96
|
+
Three title rules, because Pi rewrites the tab title while a turn runs (a tool name, a
|
|
97
|
+
progress marker) and an exact match then fails:
|
|
98
|
+
|
|
99
|
+
| rule | matches |
|
|
100
|
+
|---|---|
|
|
101
|
+
| marker | the title contains `π - <project>` |
|
|
102
|
+
| project | the title contains the project directory name |
|
|
103
|
+
| pi | the title starts with `π` (any Pi tab) |
|
|
104
|
+
|
|
105
|
+
Skipped when there is no terminal UI (`pi -p`, JSON, RPC): nobody to notify, and a
|
|
106
|
+
nested run would double-notify its parent. `/wintoast-test` explicitly posts a
|
|
107
|
+
test notification even while Pi is focused.
|
|
108
|
+
|
|
109
|
+
## Configuration
|
|
110
|
+
|
|
111
|
+
All optional, all environment:
|
|
112
|
+
|
|
113
|
+
| variable | meaning |
|
|
114
|
+
|---|---|
|
|
115
|
+
| `PI_WINTOAST=0` | disable the extension |
|
|
116
|
+
| `PI_WINTOAST_ALWAYS=1` | toast even when the tab is in the foreground |
|
|
117
|
+
| `PI_WINTOAST_FOCUS=0` | same as above |
|
|
118
|
+
| `PI_WINTOAST_MARK=…` | the title marker to look for (default `π - <cwd>`) |
|
|
119
|
+
| `PI_WINTOAST_TERMS=…` | comma-separated terminal process names |
|
|
120
|
+
| `PI_WINTOAST_PREVIEW=0` | send a fixed body instead of the answer preview |
|
|
121
|
+
| `PI_WINTOAST_LOG=…` | where the decision log goes |
|
|
122
|
+
|
|
123
|
+
## When nothing appears
|
|
124
|
+
|
|
125
|
+
Check `%LOCALAPPDATA%\pi-notify.log` or the file selected by
|
|
126
|
+
`PI_WINTOAST_LOG`. The extension logs whether it skipped a focused Pi window,
|
|
127
|
+
whether Windows accepted the toast via `Show()`, and whether Pi acknowledged a
|
|
128
|
+
reply. Check `%LOCALAPPDATA%\pi-winnotify-toast\focus.log` for COM activation
|
|
129
|
+
and queue writes. Windows still controls whether and when a banner appears.
|
|
130
|
+
|
|
131
|
+
## Compared with the existing Pi notifiers
|
|
132
|
+
|
|
133
|
+
There are several, and they are good. Install one, not two, or you get two toasts.
|
|
134
|
+
|
|
135
|
+
| | `pi-winnotify-toast` | `pi-notify` | `@raidou/pi-notify` | `@pi-lab/notify` |
|
|
136
|
+
|---|---|---|---|---|
|
|
137
|
+
| terminal notifications (OSC 777/99/9) | — | yes | yes | yes |
|
|
138
|
+
| Windows toast | yes | yes | yes (also WSL) | yes |
|
|
139
|
+
| header reads the tool's own name | **yes** (after bootstrap) | no | no | no |
|
|
140
|
+
| body is the answer | **yes** | fixed text | fixed text | fixed text |
|
|
141
|
+
| focus check | **foreground window** | no | *inactivity timeout* | no |
|
|
142
|
+
| click returns to the window | **yes, by title match** | yes for OSC | — | — |
|
|
143
|
+
| survives Do Not Disturb | **yes (`Urgent`)** | no | no | no |
|
|
144
|
+
| delivery diagnostics | **yes** | no | no | no |
|
|
145
|
+
| macOS / Linux | no | yes | yes | yes |
|
|
146
|
+
|
|
147
|
+
If you want terminal notifications, click-to-focus, or a non-Windows OS, use
|
|
148
|
+
[`pi-notify`](https://www.npmjs.com/package/pi-notify) — it covers more ground. This
|
|
149
|
+
package exists for the preview and the two Windows-specific behaviours above.
|
|
150
|
+
|
|
151
|
+
## Measurements and limitations
|
|
152
|
+
|
|
153
|
+
- The protocol handler received only `piwinnotify:open`. A 120-second in-process
|
|
154
|
+
WinRT activation listener received no callback.
|
|
155
|
+
- Shell automation read back both shortcut properties. The tagged toast and reply
|
|
156
|
+
input appeared in Notification Center history. A real Notification Center reply
|
|
157
|
+
reached the COM callback. During cold-start testing, the synthetic COM client
|
|
158
|
+
timed out and Windows recorded DCOM event 10010. Starting the helper manually
|
|
159
|
+
released three pending shell activations in a burst. The sender now warms the
|
|
160
|
+
helper before it posts.
|
|
161
|
+
- Replies go to the Pi process that posted the notification. Keep that process
|
|
162
|
+
running to receive them. Older notifications written before process routing
|
|
163
|
+
use the shared legacy queue. A failed injection leaves the claimed file for
|
|
164
|
+
inspection.
|
|
165
|
+
- Windows controls banner timing and visibility. Do Not Disturb or full-screen
|
|
166
|
+
mode may leave a notification in Notification Center.
|
|
167
|
+
- Requires native Windows Node and Windows PowerShell 5.1. The helper uses the
|
|
168
|
+
installed .NET Framework compiler and requires no SDK, MSIX package, or admin.
|
|
169
|
+
|
|
170
|
+
Run `node acceptance.mjs` from the package directory. Synthetic replies use
|
|
171
|
+
the test process’s queue. The checks print shortcut properties, history
|
|
172
|
+
observations, negative controls, and the COM result. `npm test` covers preview,
|
|
173
|
+
focus matching, and queue delivery.
|
|
174
|
+
|
|
175
|
+
## License
|
|
176
|
+
|
|
177
|
+
MIT
|
package/acceptance.mjs
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { bootstrapScript, toastScript } from "./index.ts";
|
|
6
|
+
|
|
7
|
+
const aumid = process.env.PI_WINTOAST_APPID?.trim() || "Pi.WinNotify.Toast";
|
|
8
|
+
const name = process.env.PI_WINTOAST_APPNAME?.trim() || "Pi";
|
|
9
|
+
const clsid = "{7B0E5F3A-2C41-4D9B-8E77-3F1A6B9C0D52}";
|
|
10
|
+
const psLiteral = (value) => "'" + value.replaceAll("'", "''") + "'";
|
|
11
|
+
const run = (label, script, timeout = 20_000) => {
|
|
12
|
+
const file = join(process.env.LOCALAPPDATA, `pi-wintoast-acceptance-${randomUUID()}.ps1`);
|
|
13
|
+
writeFileSync(file, "\uFEFF$ErrorActionPreference = 'Stop'\n" + script);
|
|
14
|
+
try {
|
|
15
|
+
const result = spawnSync("powershell.exe", ["-NoProfile", "-MTA", "-NonInteractive",
|
|
16
|
+
"-ExecutionPolicy", "Bypass", "-File", file], { encoding: "utf8", windowsHide: true, timeout });
|
|
17
|
+
console.log(`[${label}] ${result.stdout.trim() || "No observations written."}`);
|
|
18
|
+
if (result.status !== 0) throw new Error(result.error?.message || result.stderr.trim());
|
|
19
|
+
} finally {
|
|
20
|
+
unlinkSync(file);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
run("bootstrap", bootstrapScript());
|
|
26
|
+
run("shortcut", `
|
|
27
|
+
$dir = Join-Path $env:APPDATA 'Microsoft\\Windows\\Start Menu\\Programs'
|
|
28
|
+
$item = (New-Object -ComObject Shell.Application).NameSpace($dir).ParseName(${psLiteral(name + ".lnk")})
|
|
29
|
+
if (!$item) { throw 'Start Menu shortcut missing' }
|
|
30
|
+
function Assert-Property($property, $expected) {
|
|
31
|
+
$actual = $item.ExtendedProperty($property)
|
|
32
|
+
if ($actual -ne $expected) { throw "$property expected '$expected', observed '$actual'" }
|
|
33
|
+
Write-Output "$property = $actual"
|
|
34
|
+
}
|
|
35
|
+
$rejected = $false
|
|
36
|
+
try { Assert-Property 'System.AppUserModel.ID' 'Deliberately.Broken' }
|
|
37
|
+
catch { $rejected = $true; Write-Output ('Negative control rejected: ' + $_.Exception.Message) }
|
|
38
|
+
if (!$rejected) { throw 'Negative control unexpectedly passed' }
|
|
39
|
+
Assert-Property 'System.AppUserModel.ID' ${psLiteral(aumid)}
|
|
40
|
+
Assert-Property 'System.AppUserModel.ToastActivatorCLSID' '${clsid}'
|
|
41
|
+
`);
|
|
42
|
+
const tag = randomUUID().slice(0, 16);
|
|
43
|
+
run("post", toastScript("Pi", "Toast reply acceptance", tag, true, process.pid) + `
|
|
44
|
+
$entries = [Windows.UI.Notifications.ToastNotificationManager]::History.GetHistory($primary)
|
|
45
|
+
$entry = $entries | Where-Object { $_.Tag -eq $toast.Tag }
|
|
46
|
+
if (!$entry) { throw 'Posted tag absent from Notification Center history' }
|
|
47
|
+
if (!$entry.Content.GetXml().Contains('id="reply"')) { throw 'Reply input missing from posted XML' }
|
|
48
|
+
Write-Output 'History contains the tagged toast and reply input.'
|
|
49
|
+
`);
|
|
50
|
+
const token = `synthetic reply ${randomUUID()} π=✓`;
|
|
51
|
+
const expected = "reply\treply=" + Buffer.from(token).toString("base64");
|
|
52
|
+
const runtime = join(process.env.LOCALAPPDATA, "pi-winnotify-toast");
|
|
53
|
+
const probe = (guid) => `
|
|
54
|
+
[void][Reflection.Assembly]::Load([IO.File]::ReadAllBytes(${psLiteral(join(runtime, "pifocus.exe"))}))
|
|
55
|
+
[Program]::TestActivation([Guid]'${guid}', ${psLiteral(aumid)}, 'reply', ${psLiteral(token)}, 'reply:${process.pid}')
|
|
56
|
+
`;
|
|
57
|
+
run("COM negative control", `
|
|
58
|
+
$rejected = $false
|
|
59
|
+
try { ${probe(randomUUID())} } catch {
|
|
60
|
+
$errorCode = $_.Exception.InnerException.HResult
|
|
61
|
+
if ($errorCode -ne -2147221164) { throw }
|
|
62
|
+
$rejected = $true
|
|
63
|
+
Write-Output 'Unregistered CLSID rejected with REGDB_E_CLASSNOTREG.'
|
|
64
|
+
}
|
|
65
|
+
if (!$rejected) { throw 'Unregistered CLSID unexpectedly activated' }
|
|
66
|
+
`);
|
|
67
|
+
run("resident COM callback", probe(clsid) + "\nWrite-Output 'CoCreateInstance and Activate returned successfully.'", 12_000);
|
|
68
|
+
const queue = join(runtime, `queue-${process.pid}.txt`);
|
|
69
|
+
const matches = readFileSync(queue, "utf8").split(/\r?\n/).filter((line) => line === expected);
|
|
70
|
+
if (matches.length !== 1) throw new Error(`Expected one matching queue record, found ${matches.length}.`);
|
|
71
|
+
unlinkSync(queue);
|
|
72
|
+
console.log("[queue] Received exactly one matching Unicode reply in the acceptance process queue.");
|
|
73
|
+
console.log("[UI] Test a fresh toast from Notification Center and another while Pi is focused.");
|
|
74
|
+
} catch (error) {
|
|
75
|
+
console.error(`FAIL ${error.message}`);
|
|
76
|
+
process.exitCode = 1;
|
|
77
|
+
}
|
|
78
|
+
|
package/index.ts
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-winnotify-toast — Windows toast notifications for the Pi coding agent.
|
|
3
|
+
*
|
|
4
|
+
* Three things this does that a generic notifier does not:
|
|
5
|
+
*
|
|
6
|
+
* 1. THE BODY IS THE ANSWER, not "ready for input". At hour six of a long run the
|
|
7
|
+
* only question that matters is "do I need to come back?", and the first line
|
|
8
|
+
* of the reply answers it. Markdown is stripped, the text is capped.
|
|
9
|
+
* 2. A REAL FOCUS CHECK. The foreground window is read through Win32
|
|
10
|
+
* (GetForegroundWindow + GetWindowText) and compared with the title Pi gives
|
|
11
|
+
* the tab (`π - <project>`). Pi rewrites that title while a turn runs, so three
|
|
12
|
+
* rules are tried: the full marker, the project name, and a leading `π`. If the
|
|
13
|
+
* tab is in front, nothing is sent — the answer is already on screen.
|
|
14
|
+
* 3. URGENT, SO "DO NOT DISTURB" DOES NOT EAT IT. Windows turns DND on by itself
|
|
15
|
+
* while a fullscreen app (Discord, a game) holds the session, and a normal toast
|
|
16
|
+
* is then accepted and silently dropped. The toast is created with
|
|
17
|
+
* Scenario=Urgent and a ten-minute expiry, so it also waits in the Action
|
|
18
|
+
* Center when the popup was missed.
|
|
19
|
+
*
|
|
20
|
+
* It is Windows-only by construction: it shells out to powershell.exe, which is also
|
|
21
|
+
* how it works from WSL and from Git Bash.
|
|
22
|
+
*
|
|
23
|
+
* Every decision goes to a log (`$TEMP\pi-notify.log`, or PI_WINTOAST_LOG), because
|
|
24
|
+
* "the notification did not arrive" is otherwise indistinguishable from "the handler
|
|
25
|
+
* never ran", "the tab was focused", and "the shell suppressed it".
|
|
26
|
+
*
|
|
27
|
+
* Configuration (all optional, environment):
|
|
28
|
+
* PI_WINTOAST=0 disable
|
|
29
|
+
* PI_WINTOAST_ALWAYS=1 toast even when the tab is in the foreground
|
|
30
|
+
* PI_WINTOAST_FOCUS=0 same as above
|
|
31
|
+
* PI_WINTOAST_MARK=... the title marker to look for (default `π - <cwd>`)
|
|
32
|
+
* PI_WINTOAST_TERMS=... comma-separated terminal process names
|
|
33
|
+
* PI_WINTOAST_PREVIEW=0 send a fixed body instead of the answer preview
|
|
34
|
+
* PI_WINTOAST_LOG=... where to write the decision log
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
import { randomUUID } from "node:crypto";
|
|
38
|
+
import { execFile } from "node:child_process";
|
|
39
|
+
import { appendFileSync, existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
40
|
+
import { homedir, tmpdir } from "node:os";
|
|
41
|
+
import { basename, join } from "node:path";
|
|
42
|
+
|
|
43
|
+
/** One decoded answer text, flattened into a single line for a toast body. */
|
|
44
|
+
export function previewOf(text: string, cap = 150): string {
|
|
45
|
+
const flat = (text ?? "")
|
|
46
|
+
.replace(/\r/g, "")
|
|
47
|
+
.split("\n")
|
|
48
|
+
.map((l) => l.trim())
|
|
49
|
+
.filter((l) => l && !l.startsWith("```"))
|
|
50
|
+
.join(" ")
|
|
51
|
+
.replace(/\*\*|`|__|#+ /g, "")
|
|
52
|
+
.replace(/\s+/g, " ")
|
|
53
|
+
.trim();
|
|
54
|
+
if (!flat) return "";
|
|
55
|
+
// the ellipsis is ONE character, so trim to cap-1: cap-3 was off by two and
|
|
56
|
+
// a test caught it (38 chars for a cap of 40)
|
|
57
|
+
return flat.length > cap ? flat.slice(0, Math.max(1, cap - 1)) + "…" : flat;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Is the window that shows THIS session in front?
|
|
62
|
+
*
|
|
63
|
+
* `proc` is the foreground process name and `title` its window title. The terminal
|
|
64
|
+
* names come from the environment because every machine names them differently.
|
|
65
|
+
* Pure on purpose: it is the part worth testing.
|
|
66
|
+
*/
|
|
67
|
+
export function foregroundIsOurs(
|
|
68
|
+
proc: string,
|
|
69
|
+
title: string,
|
|
70
|
+
mark: string,
|
|
71
|
+
project: string,
|
|
72
|
+
terms: string[],
|
|
73
|
+
): number {
|
|
74
|
+
const isTerm = terms.some((t) => t.toLowerCase() === proc.toLowerCase());
|
|
75
|
+
if (!isTerm) return 0;
|
|
76
|
+
return new RegExp(focusTitlePattern(mark, project)).test(title) ? 1 : 0;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function focusTitlePattern(mark: string, project: string): string {
|
|
80
|
+
const literal = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
81
|
+
return [literal(mark), ...(project ? [literal(project)] : []), "^\\s*π"].join("|");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const ENABLED = process.env.PI_WINTOAST !== "0";
|
|
85
|
+
const ALWAYS = process.env.PI_WINTOAST_ALWAYS === "1" || process.env.PI_WINTOAST_FOCUS === "0";
|
|
86
|
+
const PREVIEW = process.env.PI_WINTOAST_PREVIEW !== "0";
|
|
87
|
+
// Urgent is off by default: it makes Windows ask the user for permission the first
|
|
88
|
+
// time, and a notification you asked for should not need a second permission to be
|
|
89
|
+
// seen. Turn it on when the toast has to survive "Do Not Disturb".
|
|
90
|
+
const URGENT = process.env.PI_WINTOAST_URGENT === "1";
|
|
91
|
+
const MARK = process.env.PI_WINTOAST_MARK ?? `π - ${basename(process.cwd())}`;
|
|
92
|
+
const PROJECT = basename(process.cwd());
|
|
93
|
+
const TERMS = (process.env.PI_WINTOAST_TERMS ??
|
|
94
|
+
"WindowsTerminal,conhost,OpenConsole,mintty,alacritty,wezterm-gui,Code,Code - Insiders")
|
|
95
|
+
.split(",")
|
|
96
|
+
.map((s) => s.trim())
|
|
97
|
+
.filter(Boolean);
|
|
98
|
+
const APPID = (process.env.PI_WINTOAST_APPID ?? "").trim() || "Pi.WinNotify.Toast";
|
|
99
|
+
const CLSID = "{7B0E5F3A-2C41-4D9B-8E77-3F1A6B9C0D52}";
|
|
100
|
+
const NAME = (process.env.PI_WINTOAST_APPNAME ?? "").trim() || "Pi";
|
|
101
|
+
// Keep the existing focus URI registered for callers outside the toast.
|
|
102
|
+
const SCHEME = (process.env.PI_WINTOAST_SCHEME ?? "").trim() || "piwinnotify";
|
|
103
|
+
const BOOTSTRAP = process.env.PI_WINTOAST_BOOTSTRAP !== "0";
|
|
104
|
+
const LOG = (process.env.PI_WINTOAST_LOG ?? "").trim() || join(process.env.LOCALAPPDATA ?? tmpdir(), "pi-notify.log");
|
|
105
|
+
|
|
106
|
+
// Registering the AppID is the "light bootstrap": one Start Menu shortcut carrying
|
|
107
|
+
// System.AppUserModel.ID plus one HKCU\Software\Classes\AppUserModelId key. No admin,
|
|
108
|
+
// no installer, nothing outside HKCU, and reversible by deleting the shortcut.
|
|
109
|
+
//
|
|
110
|
+
// SHChangeNotify(SHCNE_ASSOCCHANGED) at the end is NOT cosmetic: without it the shell
|
|
111
|
+
// does not re-enumerate the Start Menu, Get-StartApps does not list the AppID, and
|
|
112
|
+
// CreateToastNotifier reports an empty Setting -- measured ("start-app: NOT LISTED",
|
|
113
|
+
// "setting:"), then Enabled on the next run. A bootstrap that reports success while
|
|
114
|
+
// the platform still refuses the AppID is the kind of thing that looks fine and does
|
|
115
|
+
// nothing.
|
|
116
|
+
function focusDir(): string {
|
|
117
|
+
const base = process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local");
|
|
118
|
+
return join(base, "pi-winnotify-toast");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// What the marker in focus.ps1 is set to: the leading token of the title rule, so any
|
|
122
|
+
// Pi tab matches and the shortcut does not have to be rebuilt per project.
|
|
123
|
+
function focusMarker(): string {
|
|
124
|
+
const head = MARK.split(" - ")[0].trim();
|
|
125
|
+
return head || "π";
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function shortcutPath(): string {
|
|
129
|
+
const appData = process.env.APPDATA ?? join(homedir(), "AppData", "Roaming");
|
|
130
|
+
return join(appData, "Microsoft", "Windows", "Start Menu", "Programs", `${NAME}.lnk`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function bootstrapScript(): string {
|
|
134
|
+
return [
|
|
135
|
+
"$ErrorActionPreference = 'Stop'",
|
|
136
|
+
`$Aumid = '${APPID}'`,
|
|
137
|
+
`$Name = '${NAME}'`,
|
|
138
|
+
"$dir = Join-Path $env:APPDATA 'Microsoft\\Windows\\Start Menu\\Programs'",
|
|
139
|
+
"$ps = Join-Path $env:SystemRoot 'System32\\WindowsPowerShell\\v1.0\\powershell.exe'",
|
|
140
|
+
"$lnk = Join-Path $dir ($Name + '.lnk')",
|
|
141
|
+
// The click handler and its marker live next to the shortcut's target: the .lnk
|
|
142
|
+
// keeps a path to it, so it has to persist (LOCALAPPDATA, not the temp dir).
|
|
143
|
+
"$fdir = Join-Path $env:LOCALAPPDATA 'pi-winnotify-toast'",
|
|
144
|
+
"New-Item -ItemType Directory -Path $fdir -Force | Out-Null",
|
|
145
|
+
"$exe = Join-Path $fdir 'pifocus.exe'",
|
|
146
|
+
"$src = Join-Path $fdir 'pifocus.cs'",
|
|
147
|
+
"$source = '" + Buffer.from(readFileSync(new URL("./pifocus.cs", import.meta.url))).toString("base64") + "'",
|
|
148
|
+
"if (!(Test-Path $exe) -or !(Test-Path $src) -or [Convert]::ToBase64String([IO.File]::ReadAllBytes($src)) -ne $source) {",
|
|
149
|
+
" $stage = Join-Path $fdir ([Guid]::NewGuid().ToString() + '.cs')",
|
|
150
|
+
" $built = [IO.Path]::ChangeExtension($stage, 'exe')",
|
|
151
|
+
" try {",
|
|
152
|
+
" [IO.File]::WriteAllBytes($stage, [Convert]::FromBase64String($source))",
|
|
153
|
+
" & (Join-Path $env:SystemRoot 'Microsoft.NET\\Framework64\\v4.0.30319\\csc.exe') /nologo /target:winexe /out:$built $stage",
|
|
154
|
+
" if ($LASTEXITCODE -ne 0) { throw 'pifocus compilation failed' }",
|
|
155
|
+
" if (Test-Path -LiteralPath $exe) {",
|
|
156
|
+
" $old = [Reflection.Assembly]::Load([IO.File]::ReadAllBytes($exe)).GetType('Program')",
|
|
157
|
+
" if ($old -and $old.GetMethod('StopResident')) { $old.GetMethod('StopResident').Invoke($null, @()) }",
|
|
158
|
+
" }",
|
|
159
|
+
" for ($attempt = 0; ; $attempt++) {",
|
|
160
|
+
" try { Copy-Item -LiteralPath $built -Destination $exe -Force -ErrorAction Stop; break }",
|
|
161
|
+
" catch [IO.IOException] { if ($attempt -ge 20) { throw }; Start-Sleep -Milliseconds 100 }",
|
|
162
|
+
" }",
|
|
163
|
+
" Move-Item -LiteralPath $stage -Destination $src -Force",
|
|
164
|
+
" } finally { Remove-Item -LiteralPath $stage,$built -Force -ErrorAction SilentlyContinue }",
|
|
165
|
+
"}",
|
|
166
|
+
"Set-Content -Path (Join-Path $fdir 'marker.b64.txt') -Value '" + Buffer.from(focusMarker(), "utf8").toString("base64") + "' -Encoding ASCII",
|
|
167
|
+
"$cs = @'\n" +
|
|
168
|
+
"using System;\n" +
|
|
169
|
+
"using System.Runtime.InteropServices;\n" +
|
|
170
|
+
"[StructLayout(LayoutKind.Sequential, Pack = 4)] public struct PROPERTYKEY { public Guid fmtid; public int pid; }\n" +
|
|
171
|
+
"[StructLayout(LayoutKind.Explicit, Size = 24)] public struct PROPVARIANT { [FieldOffset(0)] public ushort vt; [FieldOffset(8)] public IntPtr pointerValue; }\n" +
|
|
172
|
+
"[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid(\"886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99\")]\n" +
|
|
173
|
+
"public interface IPropertyStore { void GetCount(out uint c); void GetAt(uint i, out PROPERTYKEY k); void GetValue(ref PROPERTYKEY k, out PROPVARIANT v); void SetValue(ref PROPERTYKEY k, ref PROPVARIANT v); void Commit(); }\n" +
|
|
174
|
+
"public static class Aumid {\n" +
|
|
175
|
+
" [DllImport(\"shell32.dll\", CharSet = CharSet.Unicode, PreserveSig = false)] static extern void SHGetPropertyStoreFromParsingName(string path, IntPtr bag, int flags, ref Guid iid, [MarshalAs(UnmanagedType.Interface)] out IPropertyStore store);\n" +
|
|
176
|
+
" public static void Set(string lnkPath, string aumid, Guid clsid) {\n" +
|
|
177
|
+
" Guid iid = new Guid(\"886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99\"); IPropertyStore store;\n" +
|
|
178
|
+
" SHGetPropertyStoreFromParsingName(lnkPath, IntPtr.Zero, 2, ref iid, out store);\n" +
|
|
179
|
+
" PROPERTYKEY key = new PROPERTYKEY(); key.fmtid = new Guid(\"9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3\"); key.pid = 5;\n" +
|
|
180
|
+
" PROPVARIANT pv = new PROPVARIANT(); pv.vt = 31; pv.pointerValue = Marshal.StringToCoTaskMemUni(aumid);\n" +
|
|
181
|
+
" try { store.SetValue(ref key, ref pv); } finally { Marshal.FreeCoTaskMem(pv.pointerValue); }\n" +
|
|
182
|
+
" key.pid = 26; pv.vt = 72; pv.pointerValue = Marshal.AllocCoTaskMem(16);\n" +
|
|
183
|
+
" try { Marshal.StructureToPtr(clsid, pv.pointerValue, false); store.SetValue(ref key, ref pv); store.Commit(); } finally { Marshal.FreeCoTaskMem(pv.pointerValue); }\n" +
|
|
184
|
+
" }\n" +
|
|
185
|
+
"}\n" +
|
|
186
|
+
"'@",
|
|
187
|
+
"Add-Type -TypeDefinition $cs -Language CSharp | Out-Null",
|
|
188
|
+
"$ws = New-Object -ComObject WScript.Shell",
|
|
189
|
+
"$s = $ws.CreateShortcut($lnk)",
|
|
190
|
+
"$s.TargetPath = $exe",
|
|
191
|
+
"$s.Arguments = ''",
|
|
192
|
+
"$s.WorkingDirectory = $env:SystemRoot",
|
|
193
|
+
"$s.IconLocation = $ps + ',0'",
|
|
194
|
+
"$s.Description = 'Pi terminal notifications'",
|
|
195
|
+
"$s.WindowStyle = 7",
|
|
196
|
+
"$s.Save()",
|
|
197
|
+
"$k = 'HKCU:\\Software\\Classes\\AppUserModelId\\' + $Aumid",
|
|
198
|
+
"New-Item -Path $k -Force | Out-Null",
|
|
199
|
+
"New-ItemProperty -Path $k -Name DisplayName -Value $Name -PropertyType String -Force | Out-Null",
|
|
200
|
+
"New-ItemProperty -Path $k -Name IconUri -Value $ps -PropertyType String -Force | Out-Null",
|
|
201
|
+
`$clsid = '${CLSID}'`,
|
|
202
|
+
"New-ItemProperty -Path $k -Name CustomActivator -Value $clsid -PropertyType String -Force | Out-Null",
|
|
203
|
+
"$class = 'HKCU:\\Software\\Classes\\CLSID\\' + $clsid",
|
|
204
|
+
"$server = Join-Path $class 'LocalServer32'",
|
|
205
|
+
"New-Item -Path $server -Force | Out-Null",
|
|
206
|
+
"New-ItemProperty -Path $class -Name CustomActivator -Value 1 -PropertyType DWord -Force | Out-Null",
|
|
207
|
+
"Set-Item -Path $server -Value (([char]34).ToString() + $exe + [char]34 + ' -ToastActivated')",
|
|
208
|
+
"[Aumid]::Set($lnk, $Aumid, [Guid]$clsid)",
|
|
209
|
+
`$scheme = '${SCHEME}'`,
|
|
210
|
+
"$sroot = 'HKCU:\\Software\\Classes\\' + $scheme",
|
|
211
|
+
"New-Item -Path $sroot -Force | Out-Null",
|
|
212
|
+
"New-ItemProperty -Path $sroot -Name '(default)' -Value ('URL:' + $Name + ' notifications') -PropertyType String -Force | Out-Null",
|
|
213
|
+
"New-ItemProperty -Path $sroot -Name 'URL Protocol' -Value '' -PropertyType String -Force | Out-Null",
|
|
214
|
+
"New-Item -Path ($sroot + '\\shell\\open\\command') -Force | Out-Null",
|
|
215
|
+
"$cmdline = '\"' + $exe + '\" \"%1\"'",
|
|
216
|
+
"New-ItemProperty -Path ($sroot + '\\shell\\open\\command') -Name '(default)' -Value $cmdline -PropertyType String -Force | Out-Null",
|
|
217
|
+
"Add-Type -Namespace Sh -Name C -MemberDefinition '[DllImport(\"shell32.dll\")] public static extern void SHChangeNotify(int ev, uint flags, IntPtr a, IntPtr b);'",
|
|
218
|
+
"[Sh.C]::SHChangeNotify(0x08000000, 0, [IntPtr]::Zero, [IntPtr]::Zero)",
|
|
219
|
+
"Start-Sleep -Milliseconds 700",
|
|
220
|
+
"[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null",
|
|
221
|
+
"$n = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($Aumid)",
|
|
222
|
+
"$seen = (Get-StartApps | Where-Object { $_.AppID -eq $Aumid } | ForEach-Object { $_.Name }) -join ','",
|
|
223
|
+
"Write-Output ('bootstrap: startapps=' + $seen + ' setting=' + $n.Setting)",
|
|
224
|
+
].join("\n");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// The bootstrap runs at most once per process, on the first toast (or on demand), so
|
|
228
|
+
// loading the extension stays instant and nothing is written unless a toast is
|
|
229
|
+
// actually wanted.
|
|
230
|
+
let appIdState: "new" | "running" | "ready" | "failed" = "new";
|
|
231
|
+
const waiting: Array<() => void> = [];
|
|
232
|
+
|
|
233
|
+
function ensureAppId(after: () => void): void {
|
|
234
|
+
if (!BOOTSTRAP || appIdState === "ready" || appIdState === "failed") { after(); return; }
|
|
235
|
+
// Fast path: the shortcut is the whole registration in one file, so its presence
|
|
236
|
+
// answers "was this bootstrapped already" without spawning PowerShell. Without
|
|
237
|
+
// this, every new pi session pays ~5 s on its first toast for nothing.
|
|
238
|
+
if (appIdState === "new" && existsSync(shortcutPath()) && existsSync(join(focusDir(), "pifocus.exe")) &&
|
|
239
|
+
existsSync(join(focusDir(), "pifocus.cs")) &&
|
|
240
|
+
readFileSync(join(focusDir(), "pifocus.cs")).equals(readFileSync(new URL("./pifocus.cs", import.meta.url)))) {
|
|
241
|
+
appIdState = "ready";
|
|
242
|
+
log(`bootstrap: ${shortcutPath()} exists, skipped`);
|
|
243
|
+
after();
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (appIdState === "running") { waiting.push(after); return; }
|
|
247
|
+
appIdState = "running";
|
|
248
|
+
log(`bootstrap: registering AppID ${APPID}`);
|
|
249
|
+
if (process.env.PI_WINTOAST_DUMP === "1") {
|
|
250
|
+
log("bootstrap-script:" + String.fromCharCode(10) + bootstrapScript());
|
|
251
|
+
}
|
|
252
|
+
ps(bootstrapScript(), (out, err) => {
|
|
253
|
+
const line = out.split("\r\n").filter(Boolean).pop() ?? "";
|
|
254
|
+
if (/setting=Enabled/.test(line)) { appIdState = "ready"; log(line); }
|
|
255
|
+
else {
|
|
256
|
+
appIdState = "failed";
|
|
257
|
+
// Not registered yet. The usual cause is not a broken script but the
|
|
258
|
+
// shell's Start-Menu cache: a shortcut created seconds ago is not re-read
|
|
259
|
+
// until SHChangeNotify settles (or the next logon), so Setting comes back
|
|
260
|
+
// empty. Say so instead of claiming success -- the toast then goes out
|
|
261
|
+
// under the fallback AppID, with the wrong header, and that is visible.
|
|
262
|
+
log(`bootstrap: not registered yet -- ${line || err.slice(0, 160) || "no output"}` +
|
|
263
|
+
" (shell may not have re-indexed the Start Menu; a re-run later or the next logon fixes it)");
|
|
264
|
+
}
|
|
265
|
+
after();
|
|
266
|
+
for (const w of waiting.splice(0)) w();
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function unregisterScript(): string {
|
|
271
|
+
return [
|
|
272
|
+
"$ErrorActionPreference = 'Continue'",
|
|
273
|
+
`$Aumid = '${APPID}'`,
|
|
274
|
+
`$lnk = Join-Path $env:APPDATA 'Microsoft\\Windows\\Start Menu\\Programs\\${NAME}.lnk'`,
|
|
275
|
+
"if (Test-Path $lnk) { Remove-Item $lnk -Force; Write-Output ('removed: ' + $lnk) } else { Write-Output 'removed: nothing to remove' }",
|
|
276
|
+
"Remove-Item ('HKCU:\\Software\\Classes\\AppUserModelId\\' + $Aumid) -Recurse -Force -ErrorAction SilentlyContinue",
|
|
277
|
+
`Remove-Item ('HKCU:\\Software\\Classes\\${SCHEME}') -Recurse -Force -ErrorAction SilentlyContinue`,
|
|
278
|
+
`Remove-Item -LiteralPath 'HKCU:\\Software\\Classes\\CLSID\\${CLSID}' -Recurse -Force -ErrorAction SilentlyContinue`,
|
|
279
|
+
"$dir = Join-Path $env:LOCALAPPDATA 'pi-winnotify-toast'",
|
|
280
|
+
"$exe = Join-Path $dir 'pifocus.exe'",
|
|
281
|
+
"if (Test-Path -LiteralPath $exe) {",
|
|
282
|
+
" $helper = [Reflection.Assembly]::Load([IO.File]::ReadAllBytes($exe)).GetType('Program')",
|
|
283
|
+
" if ($helper -and $helper.GetMethod('StopResident')) { $helper.GetMethod('StopResident').Invoke($null, @()) }",
|
|
284
|
+
"}",
|
|
285
|
+
"if (Test-Path -LiteralPath $dir) { Remove-Item -LiteralPath $dir -Recurse -Force -ErrorAction Stop }",
|
|
286
|
+
"Write-Output 'unregistered'",
|
|
287
|
+
].join("\n");
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
function log(msg: string): void {
|
|
292
|
+
try {
|
|
293
|
+
appendFileSync(LOG, `${new Date().toISOString()} ${msg}\n`);
|
|
294
|
+
} catch {
|
|
295
|
+
/* logging must never break the session */
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function ps(script: string, cb: (out: string, err: string) => void): void {
|
|
300
|
+
// Through a temp .ps1 and `-File`, not `-Command`: the multi-line toast script
|
|
301
|
+
// came back with only `quns=` when handed to -Command (twice), while the very
|
|
302
|
+
// same text executed as a file worked. Quoting a here-string and a function body
|
|
303
|
+
// into a command line is the part that breaks, so stop doing it.
|
|
304
|
+
let file = "";
|
|
305
|
+
try {
|
|
306
|
+
file = join(process.env.LOCALAPPDATA ?? tmpdir(), `pi-wintoast-${randomUUID()}.ps1`);
|
|
307
|
+
writeFileSync(file, "\uFEFF" + script, "utf8");
|
|
308
|
+
} catch (e) {
|
|
309
|
+
log(`ps: cannot write the script file: ${String(e).slice(0, 120)}`);
|
|
310
|
+
}
|
|
311
|
+
const argv = file
|
|
312
|
+
? ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file]
|
|
313
|
+
: ["-NoProfile", "-NonInteractive", "-Command", script];
|
|
314
|
+
execFile(
|
|
315
|
+
"powershell.exe",
|
|
316
|
+
argv,
|
|
317
|
+
// 5 s was enough for a toast script and NOT for one that compiles C#: the
|
|
318
|
+
// bootstrap took ~6 s and came back as "Command failed" after doing its job.
|
|
319
|
+
{ timeout: 60000, windowsHide: true },
|
|
320
|
+
(err, stdout, stderr) => {
|
|
321
|
+
if (err) log(`ps: error ${err.message.slice(0, 200)}`);
|
|
322
|
+
const e = String(stderr ?? "").trim();
|
|
323
|
+
if (e) log(`ps: stderr ${e.split("\n").slice(0, 2).join(" | ").slice(0, 240)}`);
|
|
324
|
+
if (file) { try { unlinkSync(file); } catch { /* temp file, ignore */ } }
|
|
325
|
+
cb(String(stdout ?? "").trim(), e);
|
|
326
|
+
},
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const foregroundInterop = [
|
|
331
|
+
'Add-Type -Namespace W -Name U -MemberDefinition @"',
|
|
332
|
+
'[DllImport("user32.dll")] public static extern System.IntPtr GetForegroundWindow();',
|
|
333
|
+
'[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(System.IntPtr h, System.Text.StringBuilder s, int n);',
|
|
334
|
+
'[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(System.IntPtr h, out uint pid);',
|
|
335
|
+
'"@',
|
|
336
|
+
];
|
|
337
|
+
|
|
338
|
+
function suppressIfFocused(): string[] {
|
|
339
|
+
const quote = (value: string) => "'" + value.replaceAll("'", "''") + "'";
|
|
340
|
+
return [
|
|
341
|
+
"$h = [W.U]::GetForegroundWindow()",
|
|
342
|
+
"$sb = New-Object System.Text.StringBuilder 512",
|
|
343
|
+
"[void][W.U]::GetWindowText($h, $sb, $sb.Capacity)",
|
|
344
|
+
"[uint32]$foregroundPid = 0",
|
|
345
|
+
"[void][W.U]::GetWindowThreadProcessId($h, [ref]$foregroundPid)",
|
|
346
|
+
"$foreground = Get-Process -Id $foregroundPid -ErrorAction SilentlyContinue",
|
|
347
|
+
`if (@(${TERMS.map(quote).join(", ")}) -contains $foreground.ProcessName -and $sb.ToString() -cmatch ${quote(focusTitlePattern(MARK, PROJECT))}) {`,
|
|
348
|
+
" Write-Output 'skipped: Pi window is focused'",
|
|
349
|
+
" return",
|
|
350
|
+
"}",
|
|
351
|
+
];
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
export function toastScript(title: string, body: string, tag = randomUUID().slice(0, 16), resident = false, replyPid?: number, respectFocus = false): string {
|
|
355
|
+
const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64");
|
|
356
|
+
return [
|
|
357
|
+
"$ErrorActionPreference = 'Stop'",
|
|
358
|
+
...(respectFocus ? foregroundInterop : []),
|
|
359
|
+
`$primary = '${APPID}'`,
|
|
360
|
+
...(resident ? [
|
|
361
|
+
"$exe = Join-Path $env:LOCALAPPDATA 'pi-winnotify-toast\\pifocus.exe'",
|
|
362
|
+
"[void][Reflection.Assembly]::LoadFrom($exe)",
|
|
363
|
+
"[Program]::WaitUntilReady($exe, $primary)",
|
|
364
|
+
] : []),
|
|
365
|
+
`$t = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(title)}'))`,
|
|
366
|
+
`$b = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(body)}'))`,
|
|
367
|
+
"[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null",
|
|
368
|
+
"[Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null",
|
|
369
|
+
"[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] > $null",
|
|
370
|
+
"$e = [System.Security.SecurityElement]",
|
|
371
|
+
`$xmlText = '<toast${URGENT ? ' scenario="urgent" duration="long"' : ''}><visual><binding template="ToastGeneric"><text>' + $e::Escape($t) + '</text><text>' + $e::Escape($b) + '</text></binding></visual><actions><input id="reply" type="text" placeHolderContent="Reply to Pi"/><action content="Send" hint-inputId="reply" activationType="background" arguments="reply${replyPid === undefined ? "" : ":" + replyPid}"/></actions></toast>'`,
|
|
372
|
+
"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument",
|
|
373
|
+
"$xml.LoadXml($xmlText)",
|
|
374
|
+
"$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)",
|
|
375
|
+
`$toast.Tag = '${tag}'`,
|
|
376
|
+
"$toast.ExpirationTime = [DateTimeOffset]::Now.AddMinutes(10)",
|
|
377
|
+
"$n = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($primary)",
|
|
378
|
+
"if ($n.Setting -ne 'Enabled') { throw ('Toast setting: ' + $n.Setting) }",
|
|
379
|
+
...(respectFocus ? suppressIfFocused() : []),
|
|
380
|
+
"$n.Show($toast)",
|
|
381
|
+
"Write-Output ('Show() returned for ' + $primary + ' tag=' + $toast.Tag)",
|
|
382
|
+
].join("\n");
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function toast(title: string, body: string, respectFocus: boolean): void {
|
|
386
|
+
ps(toastScript(title, body, `pi-${process.pid}`, true, process.pid, respectFocus), (out, err) => log(`toast: ${out || err}`));
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// The toast path is the only caller that wants an AppID, so the first toast of the
|
|
390
|
+
// process pays for the bootstrap. `PI_WINTOAST_BOOTSTRAP=0` keeps the extension fully
|
|
391
|
+
// read-only for anyone who does not want a Start Menu shortcut written on their behalf.
|
|
392
|
+
function toastBootstrapped(title: string, body: string, respectFocus = false): void {
|
|
393
|
+
ensureAppId(() => toast(title, body, respectFocus));
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export function drainReplyQueue(queue: string, deliver: (text: string) => void): boolean {
|
|
397
|
+
if (!existsSync(queue)) return false;
|
|
398
|
+
const claim = `${queue}.${randomUUID()}.claimed`;
|
|
399
|
+
try {
|
|
400
|
+
renameSync(queue, claim);
|
|
401
|
+
} catch (error: any) {
|
|
402
|
+
if (error.code !== "ENOENT" && error.code !== "EPERM" && error.code !== "EBUSY") {
|
|
403
|
+
log(`queue: ${error.message}`);
|
|
404
|
+
}
|
|
405
|
+
return false;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
let records: string[];
|
|
409
|
+
try {
|
|
410
|
+
records = readFileSync(claim, "utf8").split(/\r?\n/);
|
|
411
|
+
} catch (error) {
|
|
412
|
+
log(`queue: read failed, retained ${claim}: ${String(error)}`);
|
|
413
|
+
return false;
|
|
414
|
+
}
|
|
415
|
+
const prefix = "reply\treply=";
|
|
416
|
+
const replies = records.filter((line) => line.startsWith(prefix))
|
|
417
|
+
.map((line) => Buffer.from(line.slice(prefix.length), "base64").toString("utf8"))
|
|
418
|
+
.filter((text) => text.trim());
|
|
419
|
+
for (const reply of replies) {
|
|
420
|
+
try {
|
|
421
|
+
deliver(reply);
|
|
422
|
+
} catch (error) {
|
|
423
|
+
log(`queue: injection failed, retained ${claim}: ${String(error)}`);
|
|
424
|
+
return false;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
try { unlinkSync(claim); } catch (error) { log(`queue: ${String(error)}`); }
|
|
428
|
+
return replies.length > 0;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
export default function (pi: any) {
|
|
432
|
+
log(`loaded: mark=${JSON.stringify(MARK)} always=${ALWAYS} preview=${PREVIEW} log=${LOG}`);
|
|
433
|
+
|
|
434
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
435
|
+
const pending: string[] = [];
|
|
436
|
+
let submittedAt = 0;
|
|
437
|
+
|
|
438
|
+
const retainReplies = (replies: string[]) => {
|
|
439
|
+
if (!replies.length) return;
|
|
440
|
+
const failed = join(focusDir(), `undelivered-${process.pid}.txt`);
|
|
441
|
+
try {
|
|
442
|
+
appendFileSync(failed, replies.map((reply) =>
|
|
443
|
+
"reply\treply=" + Buffer.from(reply).toString("base64") + "\n").join(""));
|
|
444
|
+
log(`queue: retained unconfirmed replies in ${failed}`);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
log(`queue: could not retain unconfirmed replies: ${String(error)}`);
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
const collectReplies = () => {
|
|
451
|
+
const collect = (text: string) => { pending.push(text); };
|
|
452
|
+
drainReplyQueue(join(focusDir(), `queue-${process.pid}.txt`), collect);
|
|
453
|
+
drainReplyQueue(join(focusDir(), "queue.txt"), collect);
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
pi.on("session_start", (_event: any, ctx: any) => {
|
|
457
|
+
if (!ENABLED || !process.stdout.isTTY || process.platform !== "win32") return;
|
|
458
|
+
timer = setInterval(() => {
|
|
459
|
+
if (!ctx.isIdle()) return;
|
|
460
|
+
collectReplies();
|
|
461
|
+
const reply = pending[0];
|
|
462
|
+
if (!reply) return;
|
|
463
|
+
if (submittedAt) {
|
|
464
|
+
if (Date.now() - submittedAt < 30000) return;
|
|
465
|
+
retainReplies([reply]);
|
|
466
|
+
pending.shift();
|
|
467
|
+
submittedAt = 0;
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
submittedAt = Date.now();
|
|
471
|
+
try {
|
|
472
|
+
pi.sendUserMessage(reply, { deliverAs: "followUp" });
|
|
473
|
+
log(`queue: submitted reply to Pi pid=${process.pid}`);
|
|
474
|
+
} catch (error) {
|
|
475
|
+
log(`queue: Pi rejected reply: ${String(error)}`);
|
|
476
|
+
retainReplies([reply]);
|
|
477
|
+
pending.shift();
|
|
478
|
+
submittedAt = 0;
|
|
479
|
+
}
|
|
480
|
+
}, 500);
|
|
481
|
+
timer.unref();
|
|
482
|
+
});
|
|
483
|
+
|
|
484
|
+
pi.on("session_shutdown", () => {
|
|
485
|
+
clearInterval(timer);
|
|
486
|
+
retainReplies(pending);
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
pi.on("message_start", (event: any) => {
|
|
490
|
+
if (!submittedAt || event?.message?.role !== "user") return;
|
|
491
|
+
const content = event.message.content;
|
|
492
|
+
const text = typeof content === "string" ? content : Array.isArray(content)
|
|
493
|
+
? content.filter((block: any) => block.type === "text").map((block: any) => block.text).join("\n")
|
|
494
|
+
: "";
|
|
495
|
+
if (text !== pending[0]) return;
|
|
496
|
+
pending.shift();
|
|
497
|
+
submittedAt = 0;
|
|
498
|
+
log(`queue: Pi accepted reply pid=${process.pid}`);
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
let preview = "";
|
|
502
|
+
|
|
503
|
+
// `/wintoast-test [text]` posts the same toast on demand, so the setup can be
|
|
504
|
+
// checked in one keystroke instead of by finishing a turn and looking away.
|
|
505
|
+
pi.registerCommand?.("wintoast-test", {
|
|
506
|
+
description: "Post the Windows toast this extension sends when a turn settles",
|
|
507
|
+
handler: async (args: any, ctx: any) => {
|
|
508
|
+
const body = (args && String(args).trim()) || preview || "wintoast: test body";
|
|
509
|
+
toastBootstrapped(`π — ${PROJECT}`, body);
|
|
510
|
+
try { ctx?.ui?.notify?.("toast dispatched", "info"); } catch { /* UI optional */ }
|
|
511
|
+
},
|
|
512
|
+
});
|
|
513
|
+
|
|
514
|
+
pi.registerCommand?.("wintoast-bootstrap", {
|
|
515
|
+
description: "Register the AppID that titles the toast (HKCU only, no admin, reversible)",
|
|
516
|
+
handler: async (args: any, ctx: any) => {
|
|
517
|
+
appIdState = "new";
|
|
518
|
+
const wasBootstrapped = BOOTSTRAP;
|
|
519
|
+
log(`bootstrap: on demand (enabled=${wasBootstrapped})`);
|
|
520
|
+
if (process.env.PI_WINTOAST_DUMP === "1") {
|
|
521
|
+
log("bootstrap-script:" + String.fromCharCode(10) + bootstrapScript());
|
|
522
|
+
}
|
|
523
|
+
ps(bootstrapScript(), (out, err) => {
|
|
524
|
+
const line = out.split("\r\n").filter(Boolean).pop() ?? "";
|
|
525
|
+
log(`bootstrap: ${line || err.slice(0, 160)}`);
|
|
526
|
+
try { ctx?.ui?.notify?.(line || "bootstrap finished", /setting=Enabled/.test(line) ? "info" : "warn"); } catch { /* UI optional */ }
|
|
527
|
+
});
|
|
528
|
+
},
|
|
529
|
+
});
|
|
530
|
+
|
|
531
|
+
pi.registerCommand?.("wintoast-unregister", {
|
|
532
|
+
description: "Remove the shortcut, registry entries, and installed notification helper",
|
|
533
|
+
handler: async (args: any, ctx: any) => {
|
|
534
|
+
ps(unregisterScript(), (out, err) => {
|
|
535
|
+
appIdState = "new";
|
|
536
|
+
if (err) log(`unregister: ${err}`);
|
|
537
|
+
log(`unregister: ${out.replace(/\r?\n/g, " | ")}`);
|
|
538
|
+
try { ctx?.ui?.notify?.(out.split("\r\n")[0] || "unregistered", "info"); } catch { /* UI optional */ }
|
|
539
|
+
});
|
|
540
|
+
},
|
|
541
|
+
});
|
|
542
|
+
|
|
543
|
+
pi.on("message_end", async (event: any) => {
|
|
544
|
+
const m = event?.message;
|
|
545
|
+
if (!m || m.role !== "assistant") return;
|
|
546
|
+
const text = typeof m.content === "string"
|
|
547
|
+
? m.content
|
|
548
|
+
: Array.isArray(m.content)
|
|
549
|
+
? m.content.filter((c: any) => c?.type === "text").map((c: any) => c.text).join("\n")
|
|
550
|
+
: "";
|
|
551
|
+
const p = previewOf(text);
|
|
552
|
+
if (p) preview = p;
|
|
553
|
+
});
|
|
554
|
+
|
|
555
|
+
pi.on("agent_settled", async (event: any) => {
|
|
556
|
+
if (!ENABLED || process.platform !== "win32") return;
|
|
557
|
+
// A run without a terminal UI (`pi -p`, JSON, RPC) has nobody to notify and
|
|
558
|
+
// nested runs would double-notify their parent.
|
|
559
|
+
if (!process.stdout.isTTY) { log("settled: no TTY, skipped"); return; }
|
|
560
|
+
collectReplies();
|
|
561
|
+
if (pending.length) return;
|
|
562
|
+
|
|
563
|
+
const body = PREVIEW && preview ? preview : (event?.aborted ? "прервано" : "готово");
|
|
564
|
+
toastBootstrapped(`π — ${PROJECT}`, body, !ALWAYS);
|
|
565
|
+
});
|
|
566
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "pi-winnotify-toast",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-winnotify-toast",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Windows toast for the Pi coding agent with the answer preview, a real window-focus gate, and Urgent toasts that survive Do Not Disturb",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "index.ts",
|
|
7
|
+
"pi": {
|
|
8
|
+
"extensions": [
|
|
9
|
+
"./index.ts"
|
|
10
|
+
]
|
|
11
|
+
},
|
|
12
|
+
"peerDependencies": {
|
|
13
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"pi-package",
|
|
17
|
+
"pi",
|
|
18
|
+
"notification",
|
|
19
|
+
"windows",
|
|
20
|
+
"toast",
|
|
21
|
+
"wsl",
|
|
22
|
+
"windows-terminal"
|
|
23
|
+
],
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"files": [
|
|
26
|
+
"index.ts",
|
|
27
|
+
"pifocus.cs",
|
|
28
|
+
"acceptance.mjs",
|
|
29
|
+
"README.md",
|
|
30
|
+
"LICENSE"
|
|
31
|
+
],
|
|
32
|
+
"scripts": {
|
|
33
|
+
"test": "node --test index.test.ts"
|
|
34
|
+
},
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=20"
|
|
37
|
+
}
|
|
38
|
+
}
|
package/pifocus.cs
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
// pifocus.exe -- the click handler AND the toast COM activator for pi-winnotify-toast.
|
|
2
|
+
//
|
|
3
|
+
// Two jobs in one process, because Windows launches the AUMID's target anyway:
|
|
4
|
+
// 1. plain launch (shortcut click) -> bring the Pi window to the front;
|
|
5
|
+
// 2. COM activation (toast button) -> receive NOTIFICATION_USER_INPUT_DATA, i.e. the
|
|
6
|
+
// text the user typed into the toast, write it to queue.txt, then also focus.
|
|
7
|
+
//
|
|
8
|
+
// Only job 2 can carry the input text. Measured, in order:
|
|
9
|
+
// * `activationType="protocol"` delivers the URI alone ("piwinnotify:open"), no payload;
|
|
10
|
+
// * the in-process ToastNotification.Activated event never fires when the AUMID has a
|
|
11
|
+
// shortcut target to launch instead (a 120 s listener saw nothing);
|
|
12
|
+
// * INotificationActivationCallback::Activate gets Key/Value pairs -- the documented
|
|
13
|
+
// desktop path, and the only one that also works from the Action Center later.
|
|
14
|
+
//
|
|
15
|
+
// Compiles with the .NET Framework 4 csc alone: this is plain COM interop, no WinRT
|
|
16
|
+
// reference, no SDK. That matters -- the machine has Windows.winmd but no .NET reference
|
|
17
|
+
// facades, so `Add-Type` with WinRT types fails outright.
|
|
18
|
+
|
|
19
|
+
using System;
|
|
20
|
+
using System.IO;
|
|
21
|
+
using System.Text;
|
|
22
|
+
using System.Threading;
|
|
23
|
+
using System.Runtime.InteropServices;
|
|
24
|
+
|
|
25
|
+
[ComImport, Guid("53E31837-6600-4A81-9395-75CFFE746F94"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
|
26
|
+
public interface INotificationActivationCallback
|
|
27
|
+
{
|
|
28
|
+
[PreserveSig] int Activate(
|
|
29
|
+
[MarshalAs(UnmanagedType.LPWStr)] string appUserModelId,
|
|
30
|
+
[MarshalAs(UnmanagedType.LPWStr)] string invokedArgs,
|
|
31
|
+
IntPtr data,
|
|
32
|
+
uint count);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
36
|
+
public struct NotificationUserInputData
|
|
37
|
+
{
|
|
38
|
+
public IntPtr Key;
|
|
39
|
+
public IntPtr Value;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
[ComImport, Guid("00000001-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
|
43
|
+
public interface IClassFactory
|
|
44
|
+
{
|
|
45
|
+
[PreserveSig] int CreateInstance(IntPtr pUnkOuter, ref Guid riid, out IntPtr ppv);
|
|
46
|
+
[PreserveSig] int LockServer([MarshalAs(UnmanagedType.Bool)] bool fLock);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
public static class Paths
|
|
50
|
+
{
|
|
51
|
+
public static string Dir
|
|
52
|
+
{
|
|
53
|
+
get { return Path.GetDirectoryName(typeof(Paths).Assembly.Location); }
|
|
54
|
+
}
|
|
55
|
+
public static string Marker
|
|
56
|
+
{
|
|
57
|
+
get
|
|
58
|
+
{
|
|
59
|
+
try
|
|
60
|
+
{
|
|
61
|
+
string f = Path.Combine(Dir, "marker.b64.txt");
|
|
62
|
+
if (File.Exists(f))
|
|
63
|
+
{
|
|
64
|
+
return Encoding.UTF8.GetString(Convert.FromBase64String(File.ReadAllText(f).Trim()));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch { }
|
|
68
|
+
return "\u03c0";
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
public static void Log(string line)
|
|
72
|
+
{
|
|
73
|
+
try
|
|
74
|
+
{
|
|
75
|
+
File.AppendAllText(Path.Combine(Dir, "focus.log"),
|
|
76
|
+
DateTime.Now.ToString("o") + " " + line + Environment.NewLine);
|
|
77
|
+
}
|
|
78
|
+
catch { }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// The answer the user typed, one line per activation: "<args>\\t<key>=<value>...".
|
|
83
|
+
// A queue file rather than a pipe so that a reply typed while pi is busy is not lost by a
|
|
84
|
+
// process that has already exited.
|
|
85
|
+
public static class Queue
|
|
86
|
+
{
|
|
87
|
+
public static void Write(string fileName, string line)
|
|
88
|
+
{
|
|
89
|
+
for (int attempt = 0; ; attempt++)
|
|
90
|
+
{
|
|
91
|
+
try
|
|
92
|
+
{
|
|
93
|
+
using (var file = new FileStream(Path.Combine(Paths.Dir, fileName),
|
|
94
|
+
FileMode.Append, FileAccess.Write, FileShare.Read))
|
|
95
|
+
using (var writer = new StreamWriter(file, new UTF8Encoding(false)))
|
|
96
|
+
writer.WriteLine(line);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
catch (IOException)
|
|
100
|
+
{
|
|
101
|
+
if (attempt == 49) throw;
|
|
102
|
+
Thread.Sleep(20);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
public static class Focus
|
|
109
|
+
{
|
|
110
|
+
public delegate bool EnumProc(IntPtr h, IntPtr p);
|
|
111
|
+
[DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr p);
|
|
112
|
+
[DllImport("user32.dll")] static extern int GetWindowTextLength(IntPtr h);
|
|
113
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr h, StringBuilder s, int n);
|
|
114
|
+
[DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
|
|
115
|
+
[DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
|
|
116
|
+
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h);
|
|
117
|
+
[DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int c);
|
|
118
|
+
[DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr h, IntPtr a, int x, int y, int cx, int cy, uint f);
|
|
119
|
+
[DllImport("user32.dll")] static extern void keybd_event(byte vk, byte sc, uint f, IntPtr e);
|
|
120
|
+
|
|
121
|
+
// Three steps are load-bearing, measured with a foreground Discord and the terminal
|
|
122
|
+
// behind: a lone Alt down/up (tells the shell "the user is interacting", which is what
|
|
123
|
+
// unlocks the foreground lock), SW_RESTORE, then HWND_TOP before SetForegroundWindow.
|
|
124
|
+
// SetForegroundWindow alone is REFUSED in that situation.
|
|
125
|
+
public static int Run()
|
|
126
|
+
{
|
|
127
|
+
string marker = Paths.Marker;
|
|
128
|
+
IntPtr found = IntPtr.Zero;
|
|
129
|
+
EnumWindows(delegate(IntPtr h, IntPtr p)
|
|
130
|
+
{
|
|
131
|
+
if (!IsWindowVisible(h)) return true;
|
|
132
|
+
int n = GetWindowTextLength(h);
|
|
133
|
+
if (n <= 0) return true;
|
|
134
|
+
StringBuilder sb = new StringBuilder(n + 2);
|
|
135
|
+
GetWindowText(h, sb, sb.Capacity);
|
|
136
|
+
if (sb.ToString().Contains(marker)) { found = h; return false; }
|
|
137
|
+
return true;
|
|
138
|
+
}, IntPtr.Zero);
|
|
139
|
+
if (found == IntPtr.Zero) { Paths.Log("focus: no window matching '" + marker + "'"); return 1; }
|
|
140
|
+
keybd_event(0x12, 0, 0, IntPtr.Zero);
|
|
141
|
+
Thread.Sleep(30);
|
|
142
|
+
keybd_event(0x12, 0, 2, IntPtr.Zero);
|
|
143
|
+
ShowWindow(found, 9);
|
|
144
|
+
SetWindowPos(found, IntPtr.Zero, 0, 0, 0, 0, 0x0043);
|
|
145
|
+
SetForegroundWindow(found);
|
|
146
|
+
Thread.Sleep(80);
|
|
147
|
+
bool ok = GetForegroundWindow() == found;
|
|
148
|
+
Paths.Log("focus: " + (ok ? "in front" : "refused by the shell"));
|
|
149
|
+
return ok ? 0 : 2;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
[ComVisible(true), Guid("7B0E5F3A-2C41-4D9B-8E77-3F1A6B9C0D52"), ClassInterface(ClassInterfaceType.None)]
|
|
154
|
+
public class PiToastActivator : INotificationActivationCallback
|
|
155
|
+
{
|
|
156
|
+
public static ManualResetEvent Done = new ManualResetEvent(false);
|
|
157
|
+
|
|
158
|
+
public int Activate(string appUserModelId, string invokedArgs, IntPtr data, uint count)
|
|
159
|
+
{
|
|
160
|
+
try
|
|
161
|
+
{
|
|
162
|
+
string route = null;
|
|
163
|
+
int sessionPid;
|
|
164
|
+
if (invokedArgs != null && invokedArgs.StartsWith("reply:", StringComparison.Ordinal) &&
|
|
165
|
+
Int32.TryParse(invokedArgs.Substring(6), out sessionPid) && sessionPid > 0)
|
|
166
|
+
route = "queue-" + sessionPid.ToString() + ".txt";
|
|
167
|
+
else if (invokedArgs == "reply")
|
|
168
|
+
route = "queue.txt";
|
|
169
|
+
|
|
170
|
+
if (route != null)
|
|
171
|
+
{
|
|
172
|
+
int size = Marshal.SizeOf(typeof(NotificationUserInputData));
|
|
173
|
+
for (uint i = 0; i < count; i++)
|
|
174
|
+
{
|
|
175
|
+
var item = (NotificationUserInputData)Marshal.PtrToStructure(
|
|
176
|
+
IntPtr.Add(data, checked((int)i * size)), typeof(NotificationUserInputData));
|
|
177
|
+
if (Marshal.PtrToStringUni(item.Key) != "reply") continue;
|
|
178
|
+
string text = Marshal.PtrToStringUni(item.Value);
|
|
179
|
+
if (!String.IsNullOrWhiteSpace(text))
|
|
180
|
+
{
|
|
181
|
+
Queue.Write(route, "reply\treply=" + Convert.ToBase64String(Encoding.UTF8.GetBytes(text)));
|
|
182
|
+
Paths.Log("activated: reply queued in " + route);
|
|
183
|
+
}
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
else Focus.Run();
|
|
188
|
+
return 0;
|
|
189
|
+
}
|
|
190
|
+
catch (Exception e)
|
|
191
|
+
{
|
|
192
|
+
Paths.Log("activation failed: " + e.Message);
|
|
193
|
+
return Marshal.GetHRForException(e);
|
|
194
|
+
}
|
|
195
|
+
finally { Done.Set(); }
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
[ComVisible(true), ClassInterface(ClassInterfaceType.None)]
|
|
200
|
+
public class Factory : IClassFactory
|
|
201
|
+
{
|
|
202
|
+
public int CreateInstance(IntPtr pUnkOuter, ref Guid riid, out IntPtr ppv)
|
|
203
|
+
{
|
|
204
|
+
Paths.Log("CreateInstance: " + riid);
|
|
205
|
+
ppv = IntPtr.Zero;
|
|
206
|
+
if (pUnkOuter != IntPtr.Zero) return unchecked((int)0x80040110); // CLASS_E_NOAGGREGATION
|
|
207
|
+
try
|
|
208
|
+
{
|
|
209
|
+
IntPtr unk = Marshal.GetIUnknownForObject(new PiToastActivator());
|
|
210
|
+
try { return Marshal.QueryInterface(unk, ref riid, out ppv); }
|
|
211
|
+
finally { Marshal.Release(unk); }
|
|
212
|
+
}
|
|
213
|
+
catch (Exception e) { Paths.Log("CreateInstance failed: " + e.Message); return unchecked((int)0x80004005); }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
public int LockServer(bool fLock) { return 0; }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
public static class Program
|
|
220
|
+
{
|
|
221
|
+
[DllImport("ole32.dll")] static extern int CoRegisterClassObject(
|
|
222
|
+
ref Guid rclsid,
|
|
223
|
+
IntPtr pUnk,
|
|
224
|
+
int dwClsContext,
|
|
225
|
+
int flags,
|
|
226
|
+
out uint cookie);
|
|
227
|
+
[DllImport("ole32.dll")] static extern int CoRevokeClassObject(uint cookie);
|
|
228
|
+
|
|
229
|
+
const int CLSCTX_LOCAL_SERVER = 0x4;
|
|
230
|
+
const int REGCLS_MULTIPLEUSE = 1;
|
|
231
|
+
|
|
232
|
+
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
|
|
233
|
+
static extern int SetCurrentProcessExplicitAppUserModelID(string id);
|
|
234
|
+
|
|
235
|
+
public static uint Register(string appId = null)
|
|
236
|
+
{
|
|
237
|
+
if (appId != null)
|
|
238
|
+
Marshal.ThrowExceptionForHR(SetCurrentProcessExplicitAppUserModelID(appId));
|
|
239
|
+
Guid clsid = typeof(PiToastActivator).GUID;
|
|
240
|
+
uint cookie;
|
|
241
|
+
IntPtr factory = Marshal.GetComInterfaceForObject(new Factory(), typeof(IClassFactory));
|
|
242
|
+
try
|
|
243
|
+
{
|
|
244
|
+
Marshal.ThrowExceptionForHR(CoRegisterClassObject(
|
|
245
|
+
ref clsid, factory, CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, out cookie));
|
|
246
|
+
}
|
|
247
|
+
finally { Marshal.Release(factory); }
|
|
248
|
+
return cookie;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
[DllImport("ole32.dll")]
|
|
252
|
+
static extern int CoCreateInstance(ref Guid clsid, IntPtr outer, int context, ref Guid iid,
|
|
253
|
+
[MarshalAs(UnmanagedType.Interface)] out INotificationActivationCallback callback);
|
|
254
|
+
|
|
255
|
+
public static void TestActivation(Guid clsid, string appId, string key, string value, string invokedArgs = "reply")
|
|
256
|
+
{
|
|
257
|
+
Guid iid = typeof(INotificationActivationCallback).GUID;
|
|
258
|
+
INotificationActivationCallback callback;
|
|
259
|
+
Marshal.ThrowExceptionForHR(CoCreateInstance(ref clsid, IntPtr.Zero, CLSCTX_LOCAL_SERVER, ref iid, out callback));
|
|
260
|
+
var item = new NotificationUserInputData {
|
|
261
|
+
Key = Marshal.StringToCoTaskMemUni(key),
|
|
262
|
+
Value = Marshal.StringToCoTaskMemUni(value)
|
|
263
|
+
};
|
|
264
|
+
IntPtr data = Marshal.AllocCoTaskMem(Marshal.SizeOf(item));
|
|
265
|
+
try
|
|
266
|
+
{
|
|
267
|
+
Marshal.StructureToPtr(item, data, false);
|
|
268
|
+
Marshal.ThrowExceptionForHR(callback.Activate(appId, invokedArgs, data, 1));
|
|
269
|
+
}
|
|
270
|
+
finally
|
|
271
|
+
{
|
|
272
|
+
Marshal.FreeCoTaskMem(data);
|
|
273
|
+
Marshal.FreeCoTaskMem(item.Key);
|
|
274
|
+
Marshal.FreeCoTaskMem(item.Value);
|
|
275
|
+
if (Marshal.IsComObject(callback)) Marshal.ReleaseComObject(callback);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
[DllImport("ole32.dll")]
|
|
280
|
+
static extern int CoInitializeEx(IntPtr reserved, uint flags);
|
|
281
|
+
|
|
282
|
+
const string ReadyEvent = @"Local\Pi.WinNotify.Toast.Ready";
|
|
283
|
+
const string StopEvent = @"Local\Pi.WinNotify.Toast.Stop";
|
|
284
|
+
|
|
285
|
+
public static void WaitUntilReady(string exe, string appId)
|
|
286
|
+
{
|
|
287
|
+
File.WriteAllText(Path.Combine(Paths.Dir, "lease.txt"), "");
|
|
288
|
+
using (var ready = new EventWaitHandle(false, EventResetMode.ManualReset, ReadyEvent))
|
|
289
|
+
{
|
|
290
|
+
if (ready.WaitOne(0)) return;
|
|
291
|
+
using (var process = System.Diagnostics.Process.Start(exe, "-ToastResident \"" + appId + "\""))
|
|
292
|
+
{
|
|
293
|
+
if (!ready.WaitOne(5000))
|
|
294
|
+
throw new TimeoutException("Pi toast COM helper did not become ready.");
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
public static void StopResident()
|
|
300
|
+
{
|
|
301
|
+
using (var ready = new EventWaitHandle(false, EventResetMode.ManualReset, ReadyEvent))
|
|
302
|
+
using (var stop = new EventWaitHandle(false, EventResetMode.ManualReset, StopEvent))
|
|
303
|
+
{
|
|
304
|
+
if (!ready.WaitOne(0)) return;
|
|
305
|
+
stop.Set();
|
|
306
|
+
for (int i = 0; i < 100 && ready.WaitOne(0); i++) Thread.Sleep(50);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
static int RunResident(string appId)
|
|
311
|
+
{
|
|
312
|
+
bool own;
|
|
313
|
+
using (var singleton = new Mutex(true, @"Local\Pi.WinNotify.Toast.Resident", out own))
|
|
314
|
+
{
|
|
315
|
+
if (!own) return 0;
|
|
316
|
+
using (var ready = new EventWaitHandle(false, EventResetMode.ManualReset, ReadyEvent))
|
|
317
|
+
using (var stop = new EventWaitHandle(false, EventResetMode.ManualReset, StopEvent))
|
|
318
|
+
{
|
|
319
|
+
stop.Reset();
|
|
320
|
+
uint cookie = Register(appId);
|
|
321
|
+
try
|
|
322
|
+
{
|
|
323
|
+
Paths.Log("resident COM registered");
|
|
324
|
+
ready.Set();
|
|
325
|
+
string lease = Path.Combine(Paths.Dir, "lease.txt");
|
|
326
|
+
while (!stop.WaitOne(1000) &&
|
|
327
|
+
DateTime.UtcNow - File.GetLastWriteTimeUtc(lease) < TimeSpan.FromMinutes(11)) { }
|
|
328
|
+
}
|
|
329
|
+
finally
|
|
330
|
+
{
|
|
331
|
+
CoRevokeClassObject(cookie);
|
|
332
|
+
ready.Reset();
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return 0;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
[MTAThread]
|
|
340
|
+
public static int Main(string[] args)
|
|
341
|
+
{
|
|
342
|
+
if (args.Length == 2 && args[0] == "-ToastResident")
|
|
343
|
+
{
|
|
344
|
+
try
|
|
345
|
+
{
|
|
346
|
+
Marshal.ThrowExceptionForHR(CoInitializeEx(IntPtr.Zero, 0));
|
|
347
|
+
return RunResident(args[1]);
|
|
348
|
+
}
|
|
349
|
+
catch (Exception error)
|
|
350
|
+
{
|
|
351
|
+
Paths.Log("resident COM failed: " + error.Message);
|
|
352
|
+
return 4;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
bool viaToast = false;
|
|
357
|
+
for (int i = 0; i < args.Length; i++)
|
|
358
|
+
{
|
|
359
|
+
if (args[i].IndexOf("ToastActivated", StringComparison.OrdinalIgnoreCase) >= 0) viaToast = true;
|
|
360
|
+
}
|
|
361
|
+
if (!viaToast)
|
|
362
|
+
{
|
|
363
|
+
// Plain launch (a click on the shortcut or the toast body).
|
|
364
|
+
return Focus.Run();
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
Marshal.ThrowExceptionForHR(CoInitializeEx(IntPtr.Zero, 0));
|
|
368
|
+
uint cookie = Register();
|
|
369
|
+
Paths.Log("com registered in " + Thread.CurrentThread.GetApartmentState() + "; waiting for Activate");
|
|
370
|
+
// 60 s: long enough for a slow click, short enough not to leave a process per
|
|
371
|
+
// toast lying around. The Action Center case launches a fresh process anyway.
|
|
372
|
+
bool done = PiToastActivator.Done.WaitOne(60000);
|
|
373
|
+
if (done) Thread.Sleep(500);
|
|
374
|
+
Paths.Log("com revoking; activated=" + done);
|
|
375
|
+
CoRevokeClassObject(cookie);
|
|
376
|
+
return 0;
|
|
377
|
+
}
|
|
378
|
+
}
|