-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotify.ps1
More file actions
341 lines (303 loc) · 8.9 KB
/
notify.ps1
File metadata and controls
341 lines (303 loc) · 8.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#Requires -Version 5.1
<#
.SYNOPSIS
Claude Code 桌面通知脚本
.DESCRIPTION
通过 BurntToast 发送 Windows Toast 通知,自动识别项目名称和终端来源。
.PARAMETER Type
通知类型: info | success | warning | error
.EXAMPLE
powershell -ExecutionPolicy Bypass -File notify.ps1 -Type success
#>
[CmdletBinding()]
param(
[ValidateSet('info', 'success', 'warning', 'error')]
[string]$Type = 'info'
)
# ============================================================
# 编码设置 - 修复中文乱码
# ============================================================
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
# ============================================================
# 配置常量
# ============================================================
$Script:ICON_DIR = Join-Path $env:USERPROFILE '.claude'
$Script:ICON_PATH = Join-Path $Script:ICON_DIR 'notify-icon.png'
$Script:APP_NAME = 'Claude Code'
# ============================================================
# 模块: 依赖检查
# ============================================================
function Assert-Dependencies {
if (-not (Get-Module -ListAvailable -Name BurntToast)) {
Write-Host "[notify] BurntToast not installed, installing..." -ForegroundColor Yellow
try {
Install-Module -Name BurntToast -Force -Scope CurrentUser -ErrorAction Stop
}
catch {
Write-Warning "[notify] Failed to install BurntToast: $_"
Write-Warning "[notify] Run: Install-Module -Name BurntToast -Force"
return $false
}
}
try {
Import-Module BurntToast -ErrorAction Stop
return $true
}
catch {
Write-Warning "[notify] Failed to import BurntToast: $_"
return $false
}
}
# ============================================================
# 模块: 输入解析
# ============================================================
function Read-HookInput {
<#
.SYNOPSIS
从 stdin 读取 Claude Code hook 传入的 JSON 数据
#>
try {
$raw = [Console]::In.ReadToEnd()
if ($raw -and $raw.Trim()) {
return ($raw | ConvertFrom-Json)
}
}
catch {
Write-Verbose "[notify] stdin parse failed: $_"
}
return $null
}
# ============================================================
# 模块: 上下文检测
# ============================================================
function Get-ProjectName {
<#
.SYNOPSIS
从工作目录推断项目名称,优先使用 git 仓库名
#>
param([string]$Cwd)
if (-not $Cwd) { return '' }
# 优先: git 仓库根目录名称
try {
$gitRoot = git -C $Cwd rev-parse --show-toplevel 2>$null
if ($gitRoot) {
$branch = git -C $Cwd branch --show-current 2>$null
$name = Split-Path $gitRoot -Leaf
if ($branch) { return "$name [$branch]" }
return $name
}
}
catch { }
# 回退: 路径最后两段
$segments = @($Cwd -split '[\\/]' | Where-Object { $_ })
if ($segments.Count -ge 2) {
return "$($segments[-2])/$($segments[-1])"
}
if ($segments.Count -ge 1) { return $segments[-1] }
return $Cwd
}
function Get-TerminalIdentity {
<#
.SYNOPSIS
通过环境变量检测当前终端类型和配置,返回结构化信息
#>
$result = [ordered]@{
Name = ''
Profile = ''
Icon = ''
}
# --- Windows Terminal ---
if ($env:WT_SESSION) {
$result.Name = 'Windows Terminal'
$result.Icon = 'wt'
if ($env:WT_PROFILE_NAME) {
$result.Profile = $env:WT_PROFILE_NAME
}
return $result
}
# --- VS Code ---
if ($env:TERM_PROGRAM -eq 'vscode') {
$result.Name = 'VS Code'
$result.Icon = 'vscode'
return $result
}
# --- ConEmu / Cmder ---
if ($env:ConEmuPID) {
$result.Name = if ($env:CMDER_ROOT) { 'Cmder' } else { 'ConEmu' }
$result.Icon = 'conemu'
return $result
}
# --- WezTerm ---
if ($env:TERM_PROGRAM -eq 'WezTerm') {
$result.Name = 'WezTerm'
$result.Icon = 'wezterm'
return $result
}
# --- Alacritty ---
if ($env:TERM_PROGRAM -eq 'alacritty') {
$result.Name = 'Alacritty'
$result.Icon = 'alacritty'
return $result
}
# --- PowerShell ISE ---
if ($host.Name -eq 'Windows PowerShell ISE Host') {
$result.Name = 'PowerShell ISE'
$result.Icon = 'ise'
return $result
}
# --- 回退: 检测父进程 ---
try {
$parentPid = (Get-CimInstance Win32_Process -Filter "ProcessId=$PID").ParentProcessId
$parentProc = (Get-CimInstance Win32_Process -Filter "ProcessId=$parentPid")
$result.Name = [IO.Path]::GetFileNameWithoutExtension($parentProc.Name)
$result.Icon = 'terminal'
}
catch {
$result.Name = 'Terminal'
$result.Icon = 'terminal'
}
return $result
}
function Build-NotifyLabel {
<#
.SYNOPSIS
组合项目名 + 终端信息,生成通知标题中的标签
#>
param(
[string]$ProjectName,
[object]$Terminal
)
$parts = @()
# 项目名
if ($ProjectName) {
$parts += $ProjectName
}
# 终端信息
if ($Terminal.Name) {
$termText = $Terminal.Name
if ($Terminal.Profile) {
$termText += " ($($Terminal.Profile))"
}
$parts += $termText
}
return ($parts -join ' · ')
}
# ============================================================
# 模块: 通知构建与发送
# ============================================================
function Get-NotificationPayload {
<#
.SYNOPSIS
根据通知类型和上下文数据,构建标题、正文和声音
#>
param(
[string]$Type,
[string]$Label,
$Data
)
# 类型配置表 (集中管理,便于扩展)
$typeMap = @{
'success' = @{
Prefix = 'Done'
Emoji = [char]0x2713
Sound = 'Default'
FallbackMsg = 'Task completed'
}
'warning' = @{
Prefix = 'Attention'
Emoji = [char]0x26A0
Sound = 'IM'
FallbackMsg = 'Claude needs your approval'
}
'error' = @{
Prefix = 'Error'
Emoji = [char]0x2717
Sound = 'Reminder'
FallbackMsg = 'An error occurred'
}
'info' = @{
Prefix = 'Idle'
Emoji = [char]0x25CF
Sound = 'Default'
FallbackMsg = 'Claude is waiting for your input'
}
}
$cfg = $typeMap[$Type]
# 构建标题
$title = if ($Label) { "$($cfg.Emoji) $($cfg.Prefix) · $Label" } else { "$($cfg.Emoji) $($cfg.Prefix)" }
# 构建正文 (按优先级取值)
$message = $null
if ($Type -eq 'success' -and $Data) {
$message = $Data.task_subject
}
if (-not $message -and $Data) {
$message = $Data.message
}
if (-not $message) {
$message = $cfg.FallbackMsg
}
return @{
Title = $title
Message = $message
Sound = $cfg.Sound
}
}
function Send-ToastNotification {
<#
.SYNOPSIS
发送 Windows Toast 通知,带错误兜底
#>
param(
[string]$Title,
[string]$Message,
[string]$Sound
)
$params = @{
Text = $Title, $Message
Sound = $Sound
}
# 附加自定义图标
if (Test-Path $Script:ICON_PATH) {
$params.AppLogo = $Script:ICON_PATH
}
try {
New-BurntToastNotification @params
}
catch {
# 图标加载失败时回退到无图标模式
try {
New-BurntToastNotification -Text $Title, $Message -Sound $Sound
}
catch {
Write-Warning "[notify] Toast failed: $_"
# 最终回退: 控制台输出
Write-Host "`n[$Title] $Message`n" -ForegroundColor Cyan
}
}
}
# ============================================================
# 主流程
# ============================================================
function Main {
# 1. 检查依赖
$depsOk = Assert-Dependencies
if (-not $depsOk) { return }
# 2. 读取 hook 输入
$data = Read-HookInput
# 3. 检测上下文
$cwd = if ($data -and $data.cwd) { $data.cwd } else { $PWD.Path }
$projectName = Get-ProjectName -Cwd $cwd
$terminal = Get-TerminalIdentity
$label = Build-NotifyLabel -ProjectName $projectName -Terminal $terminal
# 4. 构建并发送通知
$payload = Get-NotificationPayload -Type $Type -Label $label -Data $data
Send-ToastNotification -Title $payload.Title -Message $payload.Message -Sound $payload.Sound
}
# 执行 - 顶层异常捕获
try {
Main
}
catch {
Write-Error "[notify] Unhandled error: $_"
}