Cursor Plan & Usage悬浮框显示token使用情况

Cursor Token预览悬浮:CursorTokenOverlay.ps1
# ===================================================================== # Cursor Token Overlay # 一个跟随 Cursor 运行的悬浮窗,显示 Cursor 用量(请求数 / token 数 / 套餐)。 # # 原理: # 1. 从 Cursor 本地 SQLite (state.vscdb) 读取登录 JWT(只读,不保存)。 # 2. 用 Bearer Token 调用 Cursor 内部接口 api2.cursor.sh 获取用量。 # 3. WinForms 绘制一个无边框、置顶、可拖动的悬浮窗。 # 4. 仅在 Cursor.exe 运行时显示,Cursor 关闭后自动隐藏(即“跟随 Cursor”)。 # # 纯 PowerShell + .NET,无需安装任何依赖。 # ===================================================================== [void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') [void][System.Reflection.Assembly]::LoadWithPartialName('System.Drawing') [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # ---------- 配置 ---------- $script:DbPath = Join-Path $env:APPDATA 'Cursor\User\globalStorage\state.vscdb' $script:RefreshSeconds = 60 # 用量刷新间隔(秒) $script:CursorPollSecs = 3 # 检测 Cursor 进程间隔(秒) $script:HideWhenNoCursor= $true # Cursor 未运行时隐藏悬浮窗 $script:PosFile = Join-Path $PSScriptRoot 'overlay_pos.txt' $script:ApiBase = 'https://api2.cursor.sh' # ---------- 拖动支持(无边框窗体)---------- Add-Type @" using System; using System.Runtime.InteropServices; public class Win32Drag { [DllImport("user32.dll")] public static extern bool ReleaseCapture(); [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); public const int WM_NCLBUTTONDOWN = 0xA1; public const int HTCAPTION = 0x2; public static void Drag(IntPtr h){ ReleaseCapture(); SendMessage(h, WM_NCLBUTTONDOWN, HTCAPTION, 0); } } "@ # ---------- 从 SQLite 提取 JWT(只读字节扫描,不依赖任何 SQLite 库)---------- function Get-CursorToken { if (-not (Test-Path $script:DbPath)) { return $null } try { $fs = [System.IO.File]::Open($script:DbPath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite) $buf = New-Object byte[] ($fs.Length) $null = $fs.Read($buf, 0, $buf.Length) $fs.Close() $txt = [System.Text.Encoding]::GetEncoding('ISO-8859-1').GetString($buf) $m = [regex]::Match($txt, 'eyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+') if ($m.Success) { return $m.Value } } catch { } return $null } # ---------- 调用 Cursor 接口 ---------- function Get-CursorUsage { $token = Get-CursorToken if (-not $token) { return @{ ok=$false; err='未找到登录信息(请确认已登录 Cursor)' } } $headers = @{ Authorization = "Bearer $token" } $result = @{ ok=$true } try { $p = Invoke-RestMethod -Uri "$($script:ApiBase)/auth/full_stripe_profile" -Headers $headers -TimeoutSec 15 $result.plan = $p } catch { $result.plan = $null } try { $u = Invoke-RestMethod -Uri "$($script:ApiBase)/aiserver.v1.DashboardService/GetCurrentPeriodUsage" -Method Post -Headers $headers -Body '{}' -ContentType 'application/json' -TimeoutSec 15 $result.usage = $u } catch { return @{ ok=$false; err=('获取用量失败: ' + $_.Exception.Message) } } return $result } # ---------- 构建窗体 ---------- $form = New-Object System.Windows.Forms.Form $form.Text = 'Cursor 用量' $form.FormBorderStyle = 'None' $form.StartPosition = 'Manual' $form.TopMost = $true $form.ShowInTaskbar = $false $form.Size = New-Object System.Drawing.Size(248, 100) $form.BackColor = [System.Drawing.Color]::FromArgb(24, 24, 28) $form.Opacity = 0.95 # 恢复上次位置(默认右上角) $wa = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea if (Test-Path $script:PosFile) { try { $xy = (Get-Content $script:PosFile -Raw).Trim().Split(',') $form.Location = New-Object System.Drawing.Point([int]$xy[0], [int]$xy[1]) } catch { $form.Location = New-Object System.Drawing.Point(($wa.Right - 268), ($wa.Top + 20)) } } else { $form.Location = New-Object System.Drawing.Point(($wa.Right - 268), ($wa.Top + 20)) } # 圆角 Add-Type @" using System; using System.Runtime.InteropServices; public class Win32Rgn { [DllImport("gdi32.dll")] public static extern IntPtr CreateRoundRectRgn(int a,int b,int c,int d,int e,int f); } "@ $form.Region = [System.Drawing.Region]::FromHrgn([Win32Rgn]::CreateRoundRectRgn(0,0,$form.Width,$form.Height,16,16)) # 标题 $lblTitle = New-Object System.Windows.Forms.Label $lblTitle.Text = 'Cursor 用量' $lblTitle.ForeColor = [System.Drawing.Color]::FromArgb(120,180,255) $lblTitle.Font = New-Object System.Drawing.Font('Microsoft YaHei UI', 9.5, [System.Drawing.FontStyle]::Bold) $lblTitle.Location = New-Object System.Drawing.Point(12, 9) $lblTitle.AutoSize = $true $form.Controls.Add($lblTitle) # 关闭按钮(隐藏到托盘) $btnClose = New-Object System.Windows.Forms.Label $btnClose.Text = [char]0x2715 $btnClose.ForeColor = [System.Drawing.Color]::FromArgb(150,150,160) $btnClose.Font = New-Object System.Drawing.Font('Segoe UI', 9, [System.Drawing.FontStyle]::Bold) $btnClose.Size = New-Object System.Drawing.Size(20,20) $btnClose.TextAlign = 'MiddleCenter' $btnClose.Location = New-Object System.Drawing.Point(($form.Width - 26), 8) $btnClose.Cursor = [System.Windows.Forms.Cursors]::Hand $btnClose.Add_Click({ $form.Hide() }) $btnClose.Add_MouseEnter({ $btnClose.ForeColor = [System.Drawing.Color]::FromArgb(255,90,90) }) $btnClose.Add_MouseLeave({ $btnClose.ForeColor = [System.Drawing.Color]::FromArgb(150,150,160) }) $form.Controls.Add($btnClose) # 套餐 $lblPlan = New-Object System.Windows.Forms.Label $lblPlan.ForeColor = [System.Drawing.Color]::FromArgb(190,190,200) $lblPlan.Font = New-Object System.Drawing.Font('Microsoft YaHei UI', 8.5) $lblPlan.Location = New-Object System.Drawing.Point(100, 11) $lblPlan.AutoSize = $true $lblPlan.Text = '...' $form.Controls.Add($lblPlan) # 详细用量 (Auto + API) $lblDetails = New-Object System.Windows.Forms.Label $lblDetails.ForeColor = [System.Drawing.Color]::White $lblDetails.Font = New-Object System.Drawing.Font('Microsoft YaHei UI', 12, [System.Drawing.FontStyle]::Bold) $lblDetails.Location = New-Object System.Drawing.Point(12, 36) $lblDetails.AutoSize = $true $lblDetails.Text = 'Auto: --% | API: --%' $form.Controls.Add($lblDetails) # 进度条 $bar = New-Object System.Windows.Forms.Panel $bar.Location = New-Object System.Drawing.Point(12, 64) $bar.Size = New-Object System.Drawing.Size(224, 6) $bar.BackColor = [System.Drawing.Color]::FromArgb(50,50,58) $barFill = New-Object System.Windows.Forms.Panel $barFill.Location = New-Object System.Drawing.Point(0,0) $barFill.Size = New-Object System.Drawing.Size(0,6) $barFill.BackColor = [System.Drawing.Color]::FromArgb(80,170,255) $bar.Controls.Add($barFill) $form.Controls.Add($bar) # 底部状态 / 刷新时间 $lblStatus = New-Object System.Windows.Forms.Label $lblStatus.ForeColor = [System.Drawing.Color]::FromArgb(120,120,130) $lblStatus.Font = New-Object System.Drawing.Font('Microsoft YaHei UI', 8) $lblStatus.Location = New-Object System.Drawing.Point(12, 76) $lblStatus.AutoSize = $true $lblStatus.Text = '加载中...' $form.Controls.Add($lblStatus) # 刷新按钮 $btnRefresh = New-Object System.Windows.Forms.Label $btnRefresh.Text = [char]0x21BB $btnRefresh.ForeColor = [System.Drawing.Color]::FromArgb(120,180,255) $btnRefresh.Font = New-Object System.Drawing.Font('Segoe UI', 11, [System.Drawing.FontStyle]::Bold) $btnRefresh.Size = New-Object System.Drawing.Size(22,20) $btnRefresh.TextAlign = 'MiddleCenter' $btnRefresh.Location = New-Object System.Drawing.Point(($form.Width - 30), 74) $btnRefresh.Cursor = [System.Windows.Forms.Cursors]::Hand $form.Controls.Add($btnRefresh) # ---------- 数字格式化 ---------- function Format-Num([double]$n) { if ($n -ge 1000000) { return ('{0:0.0}M' -f ($n/1000000)) } if ($n -ge 1000) { return ('{0:0.0}k' -f ($n/1000)) } return ([int]$n).ToString() } # ---------- 刷新 UI ---------- function Update-Usage { $d = Get-CursorUsage if (-not $d.ok) { $lblStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,120,120) $lblStatus.Text = $d.err return } $lblStatus.ForeColor = [System.Drawing.Color]::FromArgb(120,120,130) # 套餐 if ($d.plan) { $mt = if ($d.plan.membershipType) { $d.plan.membershipType } else { '未知' } $st = if ($d.plan.subscriptionStatus) { " ($($d.plan.subscriptionStatus))" } else { '' } $lblPlan.Text = "$mt$st" $lblPlan.Left = $lblTitle.Right + 5 } # 新版用量解析 $u = $d.usage if ($u -and $u.planUsage) { $totalPct = [Math]::Round([double]$u.planUsage.totalPercentUsed) $autoPct = [Math]::Round([double]$u.planUsage.autoPercentUsed) $apiPct = [Math]::Round([double]$u.planUsage.apiPercentUsed) $lblDetails.Text = "Auto: $autoPct% | API: $apiPct%" $ratio = [Math]::Min(1.0, $totalPct / 100.0) $barFill.Width = [int]($bar.Width * $ratio) $bar.Visible = $true if ($ratio -ge 0.9) { $barFill.BackColor = [System.Drawing.Color]::FromArgb(255,90,90) } elseif ($ratio -ge 0.75) { $barFill.BackColor = [System.Drawing.Color]::FromArgb(255,180,60) } else { $barFill.BackColor = [System.Drawing.Color]::FromArgb(80,170,255) } } else { $lblDetails.Text = "Auto: --% | API: --%" $bar.Visible = $false } # 周期重置时间 $cycle = '' if ($u -and $u.billingCycleEnd) { try { $endMs = [long]$u.billingCycleEnd # Convert Unix ms to local DateTime $endTime = [datetimeOffset]::FromUnixTimeMilliseconds($endMs).ToLocalTime().DateTime $days = [Math]::Ceiling(($endTime - [datetime]::Now).TotalDays) $cycle = " 重置: $($endTime.ToString('MM-dd')) (剩 $days 天)" } catch {} } $lblStatus.Text = (Get-Date -Format 'HH:mm:ss') + $cycle } $btnRefresh.Add_Click({ Update-Usage }) # ---------- 拖动 ---------- $dragHandler = { param($s,$e) if ($e.Button -eq [System.Windows.Forms.MouseButtons]::Left) { [Win32Drag]::Drag($form.Handle) } } $form.Add_MouseDown($dragHandler) $lblTitle.Add_MouseDown($dragHandler) $lblPlan.Add_MouseDown($dragHandler) $lblDetails.Add_MouseDown($dragHandler) # ---------- 托盘图标 ---------- $tray = New-Object System.Windows.Forms.NotifyIcon $tray.Icon = [System.Drawing.SystemIcons]::Information $tray.Text = 'Cursor 用量' $tray.Visible = $true $menu = New-Object System.Windows.Forms.ContextMenuStrip $miShow = $menu.Items.Add('显示 / 隐藏'); $miShow.Add_Click({ if ($form.Visible) { $form.Hide() } else { $form.Show(); $form.Activate(); Update-Usage } }) $miRefresh = $menu.Items.Add('刷新'); $miRefresh.Add_Click({ if (-not $form.Visible){ $form.Show() }; Update-Usage }) [void]$menu.Items.Add('-') $miExit = $menu.Items.Add('退出'); $miExit.Add_Click({ $script:reallyExit = $true; $form.Close() }) $tray.ContextMenuStrip = $menu $tray.Add_MouseClick({ param($s,$e) if ($e.Button -eq [System.Windows.Forms.MouseButtons]::Left) { if ($form.Visible) { $form.Hide() } else { $form.Show(); $form.Activate(); Update-Usage } } }) # ---------- Cursor 进程检测 + 定时刷新 ---------- $script:tick = 0 $script:reallyExit = $false $timer = New-Object System.Windows.Forms.Timer $timer.Interval = $script:CursorPollSecs * 1000 $timer.Add_Tick({ $cursorRunning = [bool](Get-Process -Name 'Cursor' -ErrorAction SilentlyContinue) if ($script:HideWhenNoCursor) { if ($cursorRunning -and -not $form.Visible) { $form.Show(); Update-Usage; $script:tick = 0 } elseif (-not $cursorRunning -and $form.Visible) { $form.Hide() } } if ($form.Visible) { $script:tick += $script:CursorPollSecs if ($script:tick -ge $script:RefreshSeconds) { Update-Usage; $script:tick = 0 } } }) $timer.Start() # 关闭时:保存位置;点 X 仅隐藏,托盘“退出”才真正退出 $form.Add_FormClosing({ param($s,$e) try { "$($form.Location.X),$($form.Location.Y)" | Set-Content -Path $script:PosFile -Encoding ASCII } catch {} if (-not $script:reallyExit) { $e.Cancel = $true; $form.Hide() } else { $timer.Stop(); $tray.Visible = $false; $tray.Dispose() } }) # 启动:若 Cursor 已在运行则立即显示并刷新,否则等待 $form.Add_Shown({ if ($script:HideWhenNoCursor -and -not (Get-Process -Name 'Cursor' -ErrorAction SilentlyContinue)) { $form.Hide() } else { Update-Usage } }) [System.Windows.Forms.Application]::EnableVisualStyles() [System.Windows.Forms.Application]::Run($form)
悬浮框记忆窗口位置:overlay_pos.txt
0,0
手动启动:启动悬浮窗.vbs
' 无控制台窗口启动 Cursor 用量悬浮窗 ' 双击此文件即可运行;安装脚本也会用它来开机自启。 Dim shell, fso, here, ps1 Set shell = CreateObject("WScript.Shell") Set fso = CreateObject("Scripting.FileSystemObject") here = fso.GetParentFolderName(WScript.ScriptFullName) ps1 = here & "\CursorTokenOverlay.ps1" shell.Run "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & ps1 & """", 0, False
使用说明:README.md
# Cursor 用量悬浮窗 (Cursor Token Overlay) 一个**跟随 Cursor 运行**的桌面悬浮窗,实时显示你的 Cursor 用量(请求数 / token 数 / 套餐)。 - 纯 PowerShell + WinForms,**无需安装 Python 或任何依赖**(Windows 自带)。 - 只在 `Cursor.exe` 运行时显示,关闭 Cursor 后自动隐藏到托盘 —— 即“跟随 Cursor”。 - 无边框、置顶、可拖动,默认停在屏幕右上角,位置会被记住。  --- ## 文件说明 | 文件 | 作用 | |---|---| | `CursorTokenOverlay.ps1` | 主程序(悬浮窗本体) | | `启动悬浮窗.vbs` | 静默启动(不弹黑色控制台窗口)。**双击即可运行** | | `安装-开机自启.ps1` | 注册到 Windows 启动文件夹,登录后自动运行 | | `卸载-开机自启.ps1` | 移除开机自启并关闭悬浮窗 | | `overlay_pos.txt` | 自动生成,记录窗口位置 | --- ## 快速使用 ### 方式一:试运行(不安装) 双击 **`启动悬浮窗.vbs`**。打开 Cursor 后,右上角即出现悬浮窗,系统托盘也有一个图标。 ### 方式二:开机自启(推荐,真正“跟随 Cursor”) 右键 **`安装-开机自启.ps1`** → “使用 PowerShell 运行”。 之后每次开机它都在后台待命,**只要 Cursor 一打开就自动显示**,Cursor 关闭就自动隐藏。 > 如果右键没有“使用 PowerShell 运行”,可在该文件夹地址栏输入 `powershell`,回车后执行: > ```powershell > powershell -ExecutionPolicy Bypass -File ".\安装-开机自启.ps1" > ``` ### 卸载 右键 **`卸载-开机自启.ps1`** → “使用 PowerShell 运行”。 --- ## 操作 - **拖动**:鼠标左键按住窗体任意空白处拖动,位置自动保存。 - **刷新**:点右下角的 ↻,或托盘菜单“刷新”。 - **隐藏**:点右上角 ✕(仅隐藏到托盘,不退出)。 - **托盘图标**:左键单击 = 显示/隐藏;右键 = 菜单(显示/隐藏、刷新、退出)。 - **彻底退出**:托盘菜单 → 退出。 --- ## 显示内容 - **套餐**:如 `pro (active)`。 - **Total**:当前计费周期的总使用额度百分比(带进度条,接近上限变黄/变红)。 - **Auto / API**:分别显示 Auto + Composer 的使用百分比,以及纯 API 的使用百分比。 - **重置时间**:显示下一次额度重置的日期及剩余天数。 默认每 60 秒自动刷新一次(可在脚本顶部 `$RefreshSeconds` 调整)。 --- ## 工作原理 1. 从 Cursor 本地数据库 `%APPDATA%\Cursor\User\globalStorage\state.vscdb` **只读**提取登录用的 JWT(不落盘、不上传第三方)。 2. 用 `Authorization: Bearer <token>` 调用 Cursor 内部接口: - `POST https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage` —— 获取 Pro 额度百分比及重置时间。 - `GET https://api2.cursor.sh/auth/full_stripe_profile` —— 套餐信息。 3. WinForms 把结果画成悬浮窗;定时器每 3 秒检测 `Cursor.exe` 是否在运行以决定显示/隐藏。 Token 仅通过 HTTPS 发送给 `api2.cursor.sh`,不会写入任何文件,也不会发送到其它服务器。 --- ## 可调参数(`CursorTokenOverlay.ps1` 顶部) | 变量 | 默认 | 含义 | |---|---|---| | `$RefreshSeconds` | `60` | 用量刷新间隔(秒) | | `$CursorPollSecs` | `3` | 检测 Cursor 进程的间隔(秒) | | `$HideWhenNoCursor` | `$true` | Cursor 未运行时是否隐藏(设为 `$false` 则常显) | --- ## 常见问题 - **显示“未找到登录信息”**:请确认已在 Cursor 中登录账号。 - **显示“获取用量失败”**:检查网络是否能访问 `api2.cursor.sh`;token 偶尔会过期,Cursor 会自动续期,稍后会恢复。 - **看不到窗口**:确认 Cursor 已打开;或在系统托盘左键单击图标。 - **不是官方接口**:`api2.cursor.sh` 为 Cursor 内部接口,非官方公开 API,未来可能变动。本工具与 Cursor 官方无关。
安装-开机自启.ps1
# 把悬浮窗注册到 Windows 启动文件夹(登录时自动运行)。 # 悬浮窗本身只在 Cursor.exe 运行时显示、关闭 Cursor 后自动隐藏, # 因此效果就是“跟随 Cursor 启动”。 $ErrorActionPreference = 'Stop' $here = $PSScriptRoot $vbs = Join-Path $here '启动悬浮窗.vbs' $startup = [Environment]::GetFolderPath('Startup') $lnkPath = Join-Path $startup 'CursorTokenOverlay.lnk' if (-not (Test-Path $vbs)) { Write-Host "找不到 $vbs" -ForegroundColor Red; exit 1 } $ws = New-Object -ComObject WScript.Shell $sc = $ws.CreateShortcut($lnkPath) $sc.TargetPath = "$env:WINDIR\System32\wscript.exe" $sc.Arguments = """$vbs""" $sc.WorkingDirectory = $here $sc.WindowStyle = 7 $sc.Description = 'Cursor 用量悬浮窗' $sc.Save() Write-Host "已安装开机自启:" -ForegroundColor Green Write-Host " $lnkPath" Write-Host "" Write-Host "现在为你启动一次悬浮窗..." -ForegroundColor Cyan Start-Process -FilePath "$env:WINDIR\System32\wscript.exe" -ArgumentList """$vbs""" Write-Host "完成。打开 Cursor 即可在右上角看到悬浮窗(也可在系统托盘找到图标)。" -ForegroundColor Green
卸载-开机自启.ps1
# 移除开机自启并尝试关闭正在运行的悬浮窗。 $startup = [Environment]::GetFolderPath('Startup') $lnkPath = Join-Path $startup 'CursorTokenOverlay.lnk' if (Test-Path $lnkPath) { Remove-Item $lnkPath -Force; Write-Host "已移除开机自启。" -ForegroundColor Green } else { Write-Host "未找到开机自启项(可能未安装)。" -ForegroundColor Yellow } # 关闭正在运行的悬浮窗进程(运行 CursorTokenOverlay.ps1 的 powershell) Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" | Where-Object { $_.CommandLine -match 'CursorTokenOverlay\.ps1' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force; Write-Host "已关闭悬浮窗进程 PID=$($_.ProcessId)" -ForegroundColor Green }

浙公网安备 33010602011771号