A Stream Deck is a grid of small screens, and out of the box most people use it as a grid of launchers. I wanted something closer to the dashboard on my NAS: a few keys that I can read at a glance, and that open the right thing when I press them.
This post walks through the plugin I ended up with. It has eight keys, about 670 lines of JavaScript (much of it SVG markup) plus two small helper scripts, and runs on the Stream Deck app (7.6 here) on macOS. The code snippets are trimmed from the real plugin.
What the keys do#
Every key shows something live, or at least a clear icon, and has a second action on a long press.
| Key | Shows | Short press | Long press |
|---|---|---|---|
| Claude | 5-hour and 7-day usage with bars | New Claude panel in VS Code | Open VS Code |
| Weather | Temperature, conditions, AQI, PM2.5 | YouTube subscriptions | Spotify |
| Markets | S&P 500, EUR/HUF, USD/HUF with daily change | Firefox | finance.yahoo.com |
| Thunderbird | Unread badge count | Thunderbird | New message |
| Calendar | Next three appointments | Calendar | To Do app |
| Finder | Spotify’s current track, or “not playing” | New Finder window | Screenshot of a selected area |
| Mic / Sound | Mic and output mute state | Toggle mic | Toggle sound |
| Window | Static icon | Move the active window one display left | One display right |
Small app icons sit in the corners of the keys, so the long-press target is visible before I press anything.
A plugin without a build step#
The official route is the @elgato/cli scaffold, which generates a TypeScript project with Rollup. I skipped it. A Stream Deck plugin is a folder ending in .sdPlugin that contains a manifest.json and a script, and the app runs the script with its own bundled Node.
com.example.dashboard.sdPlugin/
├── manifest.json
├── package.json # "type": "module", one dependency
├── bin/plugin.js
├── imgs/ # action-list icons
└── node_modules/ # @elgato/streamdeckThe manifest declares the plugin and one entry per key. Each action gets a UUID that the code refers to later.
{
"SDKVersion": 2,
"Name": "Dashboard",
"UUID": "com.example.dashboard",
"Icon": "imgs/plugin",
"CodePath": "bin/plugin.js",
"Nodejs": { "Version": "20", "Debug": "enabled" },
"OS": [{ "Platform": "mac", "MinimumVersion": "12" }],
"Actions": [
{
"UUID": "com.example.dashboard.weather",
"Name": "Weather",
"Icon": "imgs/weather",
"Controllers": ["Keypad"],
"States": [{ "Image": "imgs/weather" }]
}
]
}The package.json is only there to pull in the SDK and to mark the file as an ES module:
{
"type": "module",
"dependencies": { "@elgato/streamdeck": "^2.0.0" }
}For development I symlink the folder into the app’s plugin directory, so edits happen in a normal code folder and a restart of the app picks them up.
ln -s ~/Code/streamdeck/com.example.dashboard.sdPlugin \
~/Library/Application\ Support/com.elgato.StreamDeck/Plugins/
osascript -e 'quit app "Elgato Stream Deck"'; sleep 3; open -a "Elgato Stream Deck"One trap: the SDK’s examples register actions with a @action({ UUID: ... }) decorator. Decorators need a transpiler, and plain Node 20 will not parse them. Without a build step, set the ID as a field instead:
import streamDeck, { SingletonAction } from "@elgato/streamdeck";
class WeatherKey extends SingletonAction {
manifestId = "com.example.dashboard.weather"; // instead of @action(...)
async onWillAppear() { /* first draw, start a timer */ }
}
streamDeck.actions.registerAction(new WeatherKey());
streamDeck.connect();Draw the key yourself#
The Stream Deck lets you set a title on a key, but you get little control over font size, alignment or colour. A key image has no such limit, and setImage() accepts an SVG data URL. So every live key in the plugin builds a 144×144 SVG string and sends it.
function svgUrl(svg) {
return "data:image/svg+xml;charset=utf8," + encodeURIComponent(svg);
}
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="144" height="144" viewBox="0 0 144 144">
<rect width="144" height="144" fill="#121212"/>
<text x="72" y="62" font-family="Helvetica, Arial, sans-serif" font-size="44"
font-weight="700" fill="#ffffff" text-anchor="middle">21°C</text>
</svg>`;
for (const a of this.actions) await a.setImage(svgUrl(svg));That gives rounded coloured bars, progress bars, and mixed font sizes on one line, which is most of what makes a key readable at arm’s length. Small app icons are PNGs converted from the apps’ own .icns files with sips, base64-encoded and embedded as <image> elements.
sips -s format png -z 68 68 /Applications/Firefox.app/Contents/Resources/firefox.icns --out fx68.png
base64 -i fx68.png | tr -d '\n' | pbcopyTwo actions per key#
Stream Deck sends keyDown and keyUp, and nothing more. A long press is just a timer: start it on down, fire the long action when it expires, and treat the key-up as a short press only if the timer is still running.
const LONG_PRESS_MS = 500;
function pressHandlers(onShort, onLong) {
let timer;
return {
down() {
timer = setTimeout(() => { timer = undefined; onLong(); }, LONG_PRESS_MS);
},
up() {
if (!timer) return; // the long press already fired
clearTimeout(timer);
timer = undefined;
onShort();
},
};
}
const open = (...args) => execFile("/usr/bin/open", args, () => {});
class MediaKey extends SingletonAction {
manifestId = "com.example.dashboard.media";
press = pressHandlers(
() => open("https://www.youtube.com/feed/subscriptions"),
() => open("-a", "Spotify"),
);
onKeyDown() { this.press.down(); }
onKeyUp() { this.press.up(); }
}The long action fires as soon as the key has been held long enough, so you do not have to release first. The cost is that a short press only fires on release, a fraction of a second later than a plain launcher button would.
A double tap works the same way, with the delay on the other side: the short action has to wait for the double-tap window to pass. I did not add one, because a short press that waits 300 ms feels wrong on a launcher.
Where the data comes from#
None of the sources needs an API key. Several of them are plain macOS: AppleScript, the Dock, and the calendar database.
Claude usage, from the status line and a hook#
Claude Code can run a command on every status line update and passes it a JSON document on stdin. On my subscription account that JSON includes the rate-limit windows, which is exactly what I wanted on a key. The script saves them to a file and prints a short line for the status bar.
#!/bin/bash
# usage-dump.sh
in=$(cat)
dir="$(cd "$(dirname "$0")" && pwd)/data"
mkdir -p "$dir"
echo "$in" > "$dir/last-statusline.json" # raw dump, to check the field names
echo "$in" | jq -c '{five_hour: .rate_limits.five_hour,
seven_day: .rate_limits.seven_day,
updated: now}' > "$dir/usage.json.tmp" \
&& mv "$dir/usage.json.tmp" "$dir/usage.json"
five=$(echo "$in" | jq -r '.rate_limits.five_hour.used_percentage // empty')
week=$(echo "$in" | jq -r '.rate_limits.seven_day.used_percentage // empty')
echo "5h ${five:-?}% · 7d ${week:-?}%"It is registered in ~/.claude/settings.json:
"statusLine": { "type": "command", "command": "/path/to/usage-dump.sh" }The plugin reads usage.json every five seconds. A window whose reset time has passed counts as 0%. Data older than 30 minutes is greyed out and the key shows its age (“2h”) in amber, because the file is only written when a session is active.
function pct(w, nowSec) {
if (!w || typeof w.used_percentage !== "number") return null;
if (typeof w.resets_at === "number" && w.resets_at < nowSec) return 0;
return Math.round(w.used_percentage);
}The catch: the status line only runs in an interactive terminal session. A one-shot claude -p run does not call it, and neither does the Claude panel in the VS Code extension, which is where I do most of my work. For an afternoon the key showed numbers from a terminal session hours earlier.
Two changes fixed that. First, stale numbers now look stale: anything older than 30 minutes turns grey and shows its age. Second, a hook refreshes the file from VS Code too. Hooks are run by Claude Code itself, so a Stop hook fires after every reply, whichever interface sent the message:
"hooks": {
"Stop": [{ "hooks": [{ "type": "command", "command": "/path/to/fetch-usage.sh", "timeout": 10 }] }]
}The hook returns immediately and does the work in the background, at most once a minute. It reads the login token from the Keychain item Claude Code already uses and asks Anthropic’s usage endpoint for the same two windows:
if [ "$1" != "--now" ]; then
cat >/dev/null # drain the hook's JSON on stdin
nohup "$0" --now >/dev/null 2>&1 & # never slow Claude down
exit 0
fi
creds=$(security find-generic-password -s "Claude Code-credentials" -w) || exit 1
/usr/bin/python3 -I - "$OUT" 3<<<"$creds" <<'PY'
import json, os, urllib.request
tok = json.loads(os.fdopen(3).read())["claudeAiOauth"]["accessToken"]
req = urllib.request.Request("https://api.anthropic.com/api/oauth/usage",
headers={"Authorization": "Bearer " + tok, "anthropic-beta": "oauth-2025-04-20"})
data = json.load(urllib.request.urlopen(req, timeout=10))
# data["five_hour"]["utilization"] is a percentage, ["resets_at"] an ISO timestamp
PYThe token goes to Python on a file descriptor rather than in an argument or environment variable, is sent only to Anthropic, and is never printed. The endpoint is undocumented, which is the price of the approach: if it changes, the key simply goes grey again. Its numbers matched the status line’s exactly, reset times included.
Weather and air quality, from Open-Meteo#
Open-Meteo serves current weather and air quality from two endpoints, with no key. The plugin asks for both at once and tolerates one of them failing.
const WX = { lat: 46.253, lon: 20.1414 }; // Szeged
async function getJson(url) {
const r = await fetch(url, { signal: AbortSignal.timeout(10000) });
if (!r.ok) throw new Error(String(r.status));
return r.json();
}
async function fetchWeather() {
const [w, a] = await Promise.allSettled([
getJson(`https://api.open-meteo.com/v1/forecast?latitude=${WX.lat}&longitude=${WX.lon}`
+ `¤t=temperature_2m,weather_code&timezone=auto`),
getJson(`https://air-quality-api.open-meteo.com/v1/air-quality?latitude=${WX.lat}`
+ `&longitude=${WX.lon}¤t=european_aqi,pm2_5`),
]);
return {
temp: w.status === "fulfilled" ? w.value.current.temperature_2m : null,
code: w.status === "fulfilled" ? w.value.current.weather_code : null,
aqi: a.status === "fulfilled" ? a.value.current.european_aqi : null,
pm25: a.status === "fulfilled" ? a.value.current.pm2_5 : null,
};
}The AQI and PM2.5 each get a coloured bar. The colour comes from the European index bands, so a glance tells me whether to open a window.
function pmBand(v) { // PM2.5, µg/m³
if (v === null || v === undefined) return "#888888";
if (v <= 10) return "#50CCAA"; // good
if (v <= 20) return "#8FD14F"; // fair
if (v <= 25) return "#F0E641"; // moderate
if (v <= 50) return "#FF9A3C"; // poor
if (v <= 75) return "#FF5050"; // very poor
return "#960032"; // extremely poor
}The weather code is the WMO number, so a small lookup table turns 3 into “Overcast”. The temperature sits on the top row between the two corner icons, which leaves the rest of the key for the three lines that matter.
Markets, from Yahoo Finance#
The chart endpoint returns daily closes without a key. It is unofficial, so I treat it as best effort and keep the last good value when a request fails.
async function fetchQuote(sym) {
const r = await fetch(
`https://query1.finance.yahoo.com/v8/finance/chart/${encodeURIComponent(sym)}?interval=1d&range=5d`,
{ headers: { "User-Agent": "Mozilla/5.0" }, signal: AbortSignal.timeout(10000) });
const res = (await r.json()).chart.result[0];
const closes = res.indicators.quote[0].close.filter((x) => typeof x === "number");
const price = res.meta.regularMarketPrice ?? closes.at(-1);
const prev = closes.at(-2); // previous session's close
return { price, pct: ((price - prev) / prev) * 100 };
}The prev line is the one that is easy to get wrong. The response also has a chartPreviousClose field, which looks like the right number, but with range=5d it is the close from before the five-day window, not yesterday’s. On the day I noticed, it showed the S&P 500 as flat while the index was down about 1.5%. The second-to-last close in the series is the real previous session. This refreshes every 15 minutes, which is plenty for numbers I only glance at.
Unread mail, from the Dock#
Thunderbird exposes no API, but macOS knows the Dock badge. lsappinfo reads it for any running app:
lsappinfo info -only StatusLabel "Thunderbird"
# "StatusLabel"={ "label"="12" }function thunderbirdBadge() {
return new Promise((resolve) => {
execFile("/usr/bin/lsappinfo", ["info", "-only", "StatusLabel", "Thunderbird"], (err, out) => {
if (err || !out.trim()) return resolve(null);
const m = out.match(/"label"\s*=\s*"([^"]*)"/);
resolve(m ? m[1] : "0");
});
});
}The caveat is that this is the badge, not an exact inbox count. Thunderbird decides what the badge counts, and an app that is not running shows as “off” on the key.
Mic and sound, from AppleScript#
osascript reads and sets the audio state with no extra permissions:
osascript -e 'get volume settings'
# output volume:50, input volume:40, alert volume:14, output muted:falsemacOS has no real microphone mute, so “mute” means setting the input volume to 0 and remembering the previous level. Output has a true mute flag.
let savedInputVolume = 75;
async function toggleMic() {
const s = await audioState();
if (s.micVol === null) return; // device has no input volume
if (s.micVol > 0) {
savedInputVolume = s.micVol;
await osa("set volume input volume 0");
} else {
await osa(`set volume input volume ${savedInputVolume || 75}`);
}
}
async function toggleSound() {
await osa("set volume output muted (not (output muted of (get volume settings)))");
}The key polls every two seconds, so a change made from the menu bar shows up too. Some USB microphones do not report an input volume at all, and the key then shows “n/a”. Apps with their own mute button, such as call apps, can ignore the system setting.
Next appointments, from EventKit#
I first reached for icalBuddy, then for a few lines of Swift. Neither worked out on this machine, and it turned out neither was needed: JavaScript for Automation can call Objective-C frameworks directly, so osascript -l JavaScript gets EventKit with no compiler and no install. Unlike scripting the Calendar app, EventKit expands recurring events and does not launch anything.
ObjC.import("EventKit");
function run(argv) {
const store = $.EKEventStore.alloc.init;
// first run: request access (the prompt is attributed to the Stream Deck app)
const now = $.NSDate.date;
const end = $.NSDate.dateWithTimeIntervalSinceNow(14 * 86400);
const calendars = store.calendarsForEntityType($.EKEntityTypeEvent);
const found = store.eventsMatchingPredicate(
store.predicateForEventsWithStartDateEndDateCalendars(now, end, calendars));
const events = [];
for (let i = 0; i < found.count; i++) {
const e = found.objectAtIndex(i);
events.push({ title: ObjC.unwrap(e.title), start: e.startDate.timeIntervalSince1970 });
}
events.sort((a, b) => a.start - b.start);
return JSON.stringify(events.slice(0, 3));
}The bug I hit here is worth knowing about. EventKit takes nil for “all calendars”, so my first version passed JavaScript null. The bridge turns that into an NSNull object, not nil, and the search failed with -[NSNull count]: unrecognized selector. Passing the calendar list explicitly fixed it.
The plugin runs the script every five minutes and draws the three titles in large white type. I tried showing the time above each title, but at arm’s length the small text was unreadable, and the order already tells me what comes next.
Because the plugin process belongs to the Stream Deck app, macOS asks Stream Deck for calendar access, which works because the app declares a calendar usage string in its Info.plist.
Now playing, from Spotify#
The Finder key doubles as a now-playing display. AppleScript reads Spotify’s current track, and the is running guard matters: without it, simply asking tell application "Spotify" would launch the app.
if application "Spotify" is running then
tell application "Spotify"
if player state is playing then return (name of current track) & "|" & (artist of current track)
end tell
end if
return ""The key polls every three seconds and only redraws when the answer changes. Titles like “Song - Remastered 2011” are cut at the first " - “, because the suffix wastes half the key.
Moving windows between displays#
I have three displays: a portrait monitor on the left, the main one in the middle and the laptop on the right. The window key moves the front window one display left on a short press and one right on a long press, again from a JXA script.
The fiddly part is coordinates. NSScreen measures from the bottom-left of the main display, while System Events positions windows from the top-left, so every display frame has to be flipped:
ObjC.import("AppKit");
const list = $.NSScreen.screens;
const mainH = list.objectAtIndex(0).frame.size.height;
const screens = [];
for (let i = 0; i < list.count; i++) {
const v = list.objectAtIndex(i).visibleFrame; // without menu bar and Dock
screens.push({ x: v.origin.x, y: mainH - (v.origin.y + v.size.height),
w: v.size.width, h: v.size.height });
}
screens.sort((a, b) => a.x - b.x); // left to right
The window’s position and size are then scaled proportionally into the target display, so a half-width window stays half-width even on the portrait screen. It sets the position, then the size, then the position again, because some apps nudge the window while resizing. This one needs Accessibility permission for the Stream Deck app.
Screenshots#
The long press on the Finder key runs the built-in tool in interactive mode, which turns the cursor into a selection crosshair:
execFile("/usr/sbin/screencapture", ["-i", path.join(process.env.HOME, "Desktop", name)], () => {});Use ["-i", "-c"] instead to copy to the clipboard. macOS needs Screen Recording permission for the Stream Deck app, and until it is granted the key may do nothing at all.
Previewing without the device#
Restarting the Stream Deck app for every layout tweak gets old. Because each key is an SVG string, I can render it on the Mac instead. Extract the drawing function into a test script, write the SVG out and let Quick Look rasterise it:
node render-key.mjs out.svg && qlmanage -t -s 576 -o . out.svgTwo things I learned the hard way. Quick Look draws the artwork in the top-left corner of a larger white canvas, so a 144-pixel SVG looks tiny and misaligned unless you crop it. And a test script copied out of the plugin goes stale: more than once I tuned a layout against a preview built from the old code and wondered why nothing had changed. Generate the test script from the current file every time.
Layout problems show up early this way. On the markets key, a larger percentage ran into its label at a font size that looked fine in my head, and I only caught it because the preview showed the two touching.
Limits worth knowing#
- Unofficial sources. The Yahoo chart endpoint, the Claude usage endpoint and the status line’s
rate_limitsfield are not documented contracts. If one changes, that key shows--or “no data”, or goes grey, until I fix it. - Stale numbers. The Claude key greys out data older than 30 minutes. The markets key does not yet, and shows the last good values even if the network has been down for hours.
- Permissions add up. Calendars, control of Spotify and System Events, Accessibility, Screen Recording and Desktop folder access, each granted once to the Stream Deck app.
- Filesystem permissions. The Stream Deck app reads the usage file from my Desktop, so macOS asks once for access.
- Screen sizes. Everything is drawn for the 72-pixel keys at 2× (144 px). A different model scales it, but the font sizes are tuned for this one.
Backing it up#
The key layout lives in the app’s ProfilesV3 folder, and the plugin is a normal code folder. A backup is a copy of both, plus the helper scripts and the status line and hook scripts. I leave out node_modules, which npm install rebuilds.
S=~/Library/Application\ Support/com.elgato.StreamDeck
B=~/Code/streamdeck/backup/$(date +%F-%H%M)
mkdir -p "$B"
cp -R "$S/ProfilesV3" "$S/BackupV3" "$B/"
rsync -a --exclude node_modules --exclude logs \
~/Code/streamdeck/com.example.dashboard.sdPlugin/ "$B/plugin-source/"
cp -R ~/Code/streamdeck/helpers ~/Code/streamdeck/*.sh "$B/"The app also writes its own .streamDeckProfilesBackup files into BackupV3, and double-clicking one restores the layout.
Wrapping up#
The pattern is small enough to repeat for any other source. Fetch something on a timer, build an SVG, call setImage(). Anything with a local command or an HTTP endpoint fits the same shape, whether that is a build status light or a server health check.
The other thing I would repeat is the two-action key. Once short press and long press are free, each key is both a display and a launcher, and eight keys cover most of what I used to open a browser tab for.