Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/open-source-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ jobs:
with:
node-version: '24'
- name: Install the tested Claude Code CLI
run: npm install --global @anthropic-ai/claude-code@2.1.287
run: npm install --global @anthropic-ai/claude-code@2.1.325
- name: Validate and test the native Mods plugin
run: make test-claude

Expand Down
2 changes: 1 addition & 1 deletion plugins/claude-code/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "pulse-cc",
"displayName": "Pulse CC",
"version": "0.5.0",
"version": "0.6.0",
"description": "Stock and crypto quotes above the Claude Code prompt, with a /pulse panel to manage your watchlist.",
"author": {
"name": "fatwang2",
Expand Down
4 changes: 4 additions & 0 deletions plugins/claude-code/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
removed the Mac mode, its bundled MCP server and token option. Do not
reintroduce MCP calls, commands or credentials. Keep a compact quote band and
a management panel; do not display charts or mini trends.
- The backdrop (`/pulse backdrop on`, Desktop and mobile only) stays opt-in:
`$.theme.set` replaces any other mod's theme. It shows mood only (a glow
and the largest mover in a corner), never charts, links or branding, and
only redraws from quotes the band already has.
- Use Claude Code Mods APIs, not Node imports or direct filesystem/network
access. Write each host call explicitly in `hooks/register.tsx` so the
host's static analyzer can inventory it, with each fetch's https origin and
Expand Down
30 changes: 26 additions & 4 deletions plugins/claude-code/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ watchlists and position P&L. Free for 30 days, then a one-time purchase.
| `/pulse refresh` | Request one refresh round, including while paused |
| `/pulse off` | Pause automatic refresh; keep the watchlist and cached quotes |
| `/pulse on` | Resume automatic refresh |
| `/pulse backdrop on` | Put the market-mood backdrop behind the conversation (Claude Desktop and the Claude mobile app) |
| `/pulse backdrop off` | Take the backdrop off |
| `/pulse help` | Show command usage |

The panel header shows the watchlist size with Refresh and Pause beside it and
Expand Down Expand Up @@ -95,6 +97,22 @@ compact band; other currencies remain visible. The panel includes currency.
Neither surface displays charts or mini trends. Opening the panel does not
trigger an extra quote request.

## Backdrop

In Claude Desktop's **Code** tab and the Claude mobile app, `/pulse backdrop on`
puts a quiet backdrop behind the conversation: a slow glow in the top-right
corner, green when your watchlist is up on average, red when it is down, and
blue when it is flat or has no fresh quotes. Stronger days glow a little
stronger. The day's largest mover is set large and faint in the same corner.
It uses the quotes the band already has, with no extra requests, and draws no
chart. Cached quotes do not count toward the mood. The backdrop needs Claude
Code 2.1.323 or later; the band and panel keep working on older builds. The glow holds still when
the system asks for reduced motion. The terminal draws no backdrop.

It is off by default because a session holds one theme: turning it on replaces
another mod's colors or backdrop, and `/pulse backdrop off` clears the session's
theme. The setting is saved, so new sessions start with it.

Pulse CC refreshes 60 seconds **after each round**. Stock requests are spaced
at least one second apart, so a large watchlist takes longer to complete a
round; crypto pairs are read together in one request.
Expand Down Expand Up @@ -136,7 +154,8 @@ rights to Yahoo's market data. These quotes are for informational use.
## Local data and privacy

The plugin saves Yahoo ticker symbols, Binance pairs and the paused setting in
Claude Code's local plugin store (`watchlist.v1`). That store is shared by your
Claude Code's local plugin store (`watchlist.v1`), and the backdrop setting
in `backdrop.v1`. That store is shared by your
local sessions. Edits in one session are picked up by another at its next
refresh; concurrent writes across processes are last-writer-wins. Quote caches
are in memory and are fetched again in a new session.
Expand All @@ -160,18 +179,21 @@ and every host call is written out in that one file.

### What each hook does

- `session.start`: registers the `/pulse` command and, in a terminal session,
starts the quote refresh.
- `session.start`: registers the `/pulse` command, sets the backdrop if you
turned it on, and, in a terminal session, starts the quote refresh.
- `session.attach` and `session.detach` (Claude Desktop only): start the refresh
when a Desktop window attaches and stop it when the last one detaches.
- `session.end`: stops the refresh.
- `command.run`, matched to `/pulse` only: the one call it sees is the person
typing `/pulse`. It reads the arguments (`add`, `remove`, `refresh`, `off`,
`on`, `help` or none), updates the watchlist in the plugin store or opens and
`on`, `backdrop on|off`, `help` or none), updates the watchlist in the plugin store or opens and
closes the panel, and answers with one short line such as `Added AAPL.`. It
never runs, rewrites or forwards the command, and never sees other commands.
- `ui.render` for `AbovePrompt` and for its own `pulse-quotes` pane: draws the
quote band above the prompt and the `/pulse` panel.
- `ui.render` for `Backdrop`, its own `pulse-mood` scene only: draws the
backdrop as a self-contained SVG with no script and no links. It leaves
another mod's backdrop alone.

It has no hook on Claude's tool calls, prompts, permission checks or messages,
so it never sees, changes or approves them.
Expand Down
84 changes: 84 additions & 0 deletions plugins/claude-code/hooks/backdrop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import type { Quote } from './yahoo'
import { formatChange } from './yahoo'

/** The scene name Pulse sets with `$.theme.set` and answers at `Backdrop`. */
export const SCENE = 'pulse-mood'
export const BACKDROP_KEY = 'backdrop.v1'
export type BackdropPreference = { version: 1; enabled: boolean }

export function readBackdrop(value: unknown): BackdropPreference {
const saved = value as Partial<BackdropPreference> | null
return { version: 1, enabled: saved?.version === 1 && saved.enabled === true }
}

export type Mood = {
/** Average change of the quoted symbols, or null when none is quoted. */
average: number | null
/** The quoted symbol with the largest absolute change, if any. */
mover?: { symbol: string; change: number }
}

/** Reads the watchlist's mood from fresh quotes only; cached quotes say nothing. */
export function readMood(symbols: string[], quotes: Record<string, Quote>, errors: Record<string, string>): Mood {
let sum = 0
let count = 0
let mover: Mood['mover']
for (const symbol of symbols) {
const change = quotes[symbol]?.changePercent
if (errors[symbol] || typeof change !== 'number' || !Number.isFinite(change)) continue
sum += change
count++
if (!mover || Math.abs(change) > Math.abs(mover.change)) mover = { symbol, change }
}
return { average: count ? sum / count : null, mover }
}

// Colors follow the band: green up, red down, the logo's blue when flat or unknown.
const UP = '#2FB36B'
const DOWN = '#E5484D'
const FLAT = '#6AB0FF'

function escape(text: string): string {
return text.replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`)
}

/**
* The backdrop: a slow glow in the top-right corner tinted by the watchlist's
* average change, and the day's largest mover set large and faint beneath it.
* Everything sits in the corner, away from the conversation and the prompt: the root
* fills any box and the nested drawing stays pinned to that corner.
*/
export function backdropScene(mood: Mood): string {
const average = mood.average
const flat = average === null || Math.abs(average) < 0.05
const color = flat ? FLAT : average! > 0 ? UP : DOWN
// Stronger days glow a little stronger, within a narrow, quiet range.
const strength = flat ? 0 : Math.min(Math.abs(average!) / 3, 1)
const light = (0.16 + strength * 0.16).toFixed(3)
const dark = (0.22 + strength * 0.2).toFixed(3)
const mover = mood.mover && Math.abs(mood.mover.change) >= 0.01
? `${escape(mood.mover.symbol)} ${escape(formatChange(mood.mover.change))}` : ''
return `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
<style>
.base{fill:#F5F8FC}.glow{opacity:${light}}.mark{fill:#0B2A4D;fill-opacity:.055}
@media (prefers-color-scheme:dark){.base{fill:#07182E}.glow{opacity:${dark}}.mark{fill:#EAF3FF;fill-opacity:.06}}
@media (prefers-reduced-motion:no-preference){.breathe{animation:breathe 14s ease-in-out infinite;transform-origin:1300px 120px}}
@keyframes breathe{0%,100%{transform:scale(1)}50%{transform:scale(1.12)}}
</style>
<defs><radialGradient id="g"><stop offset="0" stop-color="${color}"/><stop offset=".55" stop-color="${color}" stop-opacity=".35"/><stop offset="1" stop-color="${color}" stop-opacity="0"/></radialGradient></defs>
<rect class="base" width="100%" height="100%"/>
<svg width="100%" height="100%" viewBox="0 0 1600 1000" preserveAspectRatio="xMaxYMin meet">
<g class="breathe"><ellipse class="glow" cx="1300" cy="120" rx="560" ry="420" fill="url(#g)"/></g>
</svg>
${mover ? `<svg x="55%" width="45%" height="40%" viewBox="0 0 700 400" preserveAspectRatio="xMaxYMin meet">
<text class="mark" x="676" y="130" text-anchor="end" font-family="-apple-system,BlinkMacSystemFont,'Helvetica Neue',sans-serif" font-size="64" font-weight="700" letter-spacing="-1">${mover}</text>
</svg>` : ''}
</svg>`
}

export function sceneAlt(mood: Mood): string {
if (mood.average === null) return 'A soft blue glow in the corner'
const direction = Math.abs(mood.average) < 0.05 ? 'flat' : mood.average > 0 ? 'up' : 'down'
const mover = mood.mover ? `, largest mover ${mood.mover.symbol} ${formatChange(mood.mover.change)}` : ''
return `A soft glow showing the watchlist ${direction} on average${mover}`
}
42 changes: 38 additions & 4 deletions plugins/claude-code/hooks/register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import type { EngineInterface, Register } from 'claude-code'
import { SETTINGS_KEY, Watchlist } from './watchlist'
import { formatChange, formatPrice, formatBandPrice, formatStaleDate } from './yahoo'
import { isCryptoPair } from './binance'
import { BACKDROP_KEY, SCENE, backdropScene, readBackdrop, readMood, sceneAlt } from './backdrop'

export const PANE = 'pulse-quotes'
const HELP = '/pulse · /pulse add AAPL · /pulse remove AAPL · /pulse refresh · /pulse off · /pulse on\n' +
const HELP = '/pulse · /pulse add AAPL · /pulse remove AAPL · /pulse refresh · /pulse off · /pulse on · /pulse backdrop on|off\n' +
'Quotes in your Mac menu bar, with charts and positions: Pulse for Mac, pulseticker.app'
// The site, tagged with where the click came from. Opened only when the person clicks.
const SITE_PANEL = 'https://www.pulseticker.app/?utm_source=claude-code&utm_medium=plugin&utm_content=panel'
Expand Down Expand Up @@ -33,9 +34,12 @@ export const register: Register = on => {
on('session.start', async ($, e, next) => {
await $.command.register({
name: 'pulse', description: 'Watch stock and crypto quotes above the prompt',
argumentHint: '[add <ticker> | remove <ticker> | refresh | off | on]',
argumentHint: '[add <ticker> | remove <ticker> | refresh | off | on | backdrop on|off]',
immediate: true,
})
// The backdrop is opt-in: a session holds one theme, and setting it would
// replace a theme the person chose. Neither reload nor --resume keeps it.
if (readBackdrop(await $.store.get(BACKDROP_KEY)).enabled) await setBackdrop($)
interactive = e.isInteractive
if (interactive) await startWatch($, watch)
return next(e)
Expand Down Expand Up @@ -80,6 +84,18 @@ export const register: Register = on => {
if (args[0] === 'remove' && args.length === 2) return { text: await watch.remove(args[1]) }
if (args[0] === 'off' && args.length === 1) return { text: await watch.pause(true) }
if (args[0] === 'on' && args.length === 1) return { text: await watch.pause(false) }
if (args[0] === 'backdrop' && args.length === 2 && (args[1] === 'on' || args[1] === 'off')) {
const enabled = args[1] === 'on'
await $.store.set(BACKDROP_KEY, { version: 1, enabled })
if (!enabled) {
try { await $.theme.clear() } catch { /* No themes before Claude Code 2.1.319. */ }
return { text: 'Backdrop off.' }
}
const set = await setBackdrop($)
if (!set) return { text: 'The backdrop needs Claude Code 2.1.323 or later.' }
return { text: set.isDrawn ? 'Backdrop on: a glow tinted by your watchlist, behind the conversation.'
: 'Backdrop on. It shows in Claude Desktop and the Claude mobile app; the terminal draws none.' }
}
if (args[0] === 'refresh' && args.length === 1) {
// Refresh on a background timer, so a long watchlist never blocks input.
$.clock.after(0, () => watch.refresh())
Expand Down Expand Up @@ -127,6 +143,15 @@ export const register: Register = on => {
</Text></Box>
})

on('ui.render', { component: 'Backdrop' }, async ($, e, next) => {
// Every mod's backdrop asks here: draw only Pulse's own scene.
if (e.props.plugin !== $.plugin.name || e.props.scene !== SCENE) return next(e)
if (e.surface !== 'desktop' && e.surface !== 'mobile') return next(e)
const { Svg } = $.ui.resolve(e)
const mood = readMood(watch.preferences.symbols, watch.quotes, watch.errors)
return <Svg source={backdropScene(mood)} alt={sceneAlt(mood)} isInteractive />
})

on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
if (e.surface !== 'terminal' && e.surface !== 'desktop') return next(e)
const { Box, Text, Button, Input, Link } = $.ui.resolve(e)
Expand Down Expand Up @@ -242,6 +267,15 @@ function changeColor(change: number | null): string | undefined {
return change === null ? undefined : change >= 0 ? 'green' : 'red'
}

// Older Claude Code builds have no themes; the rest of Pulse still runs there.
async function setBackdrop($: EngineInterface) {
try {
return await $.theme.set({ backdrop: { scene: SCENE, glass: {} } })
} catch {
return undefined
}
}

function startWatch($: EngineInterface, watch: Watchlist): Promise<void> {
return watch.start({
load: () => $.store.get(SETTINGS_KEY),
Expand All @@ -251,10 +285,10 @@ function startWatch($: EngineInterface, watch: Watchlist): Promise<void> {
after: (ms, callback) => $.clock.after(ms, callback),
// The only two hosts the mod contacts, each written whole at its call.
fetchYahoo: path => $.http.fetch(`https://query1.finance.yahoo.com/v8/finance/chart/${path}`, {
headers: { 'User-Agent': 'Pulse-CC/0.5.0', Accept: 'application/json' },
headers: { 'User-Agent': 'Pulse-CC/0.6.0', Accept: 'application/json' },
}),
fetchBinance: query => $.http.fetch(`https://data-api.binance.vision/api/v3/ticker/24hr?${query}`, {
headers: { 'User-Agent': 'Pulse-CC/0.5.0', Accept: 'application/json' },
headers: { 'User-Agent': 'Pulse-CC/0.6.0', Accept: 'application/json' },
}),
redraw: () => $.ui.invalidate('ui.render'),
})
Expand Down
49 changes: 49 additions & 0 deletions plugins/claude-code/tests/pulse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import type { Engine } from 'claude-code/testing'
import type { On } from 'claude-code'
import { SETTINGS_KEY } from '../hooks/watchlist'
import { decodeQuote, formatBandPrice, formatPrice, formatStaleDate, normalizeSymbol, quotePath, YahooError } from '../hooks/yahoo'
import { BACKDROP_KEY, backdropScene, readMood } from '../hooks/backdrop'
import type { Quote } from '../hooks/yahoo'
import { BinanceError, decodeTickers, isCryptoPair, tickersQuery } from '../hooks/binance'

// The URL the mod's one Binance call builds from its fixed address.
Expand Down Expand Up @@ -536,3 +538,50 @@ test('Pulse for Mac links sit in the panel footer, under an empty list and in he
expect(await band.find({ type: 'Text', text: /Pulse for Mac|pulseticker/ })).toBe(undefined)
await band.unmount()
})

test('the backdrop is opt-in, follows the watchlist mood, and draws only the Pulse scene', async ($, on) => {
const { clock, saved } = host(on, ['AAPL', 'NVDA'])
const themes: unknown[] = []
on('theme.set', (_, e) => { themes.push(e); return { value: { isDrawn: true, requestId: 'backdrop' } } })
on('theme.clear', () => { themes.push('clear'); return { value: { isDrawn: false, reason: 'the theme is cleared' } } })
on('http.fetch', (_, e) => ({ value: e.url.includes('NVDA') ? response('NVDA', 104, 100) : response('AAPL', 101, 100) }))
await $.session.start(START)
await clock.settle()
await clock.advance(1000)
expect(themes).toEqual([])

expect((await command($, 'backdrop on')).text).toMatch(/^Backdrop on/)
expect(themes).toEqual([{ backdrop: { scene: 'pulse-mood', glass: {} } }])
expect(saved.get(BACKDROP_KEY)).toEqual({ version: 1, enabled: true })

const target = { plugin: PLUGIN, component: 'Backdrop', requestId: 'backdrop', viewport: { columns: 100, rows: 30 },
props: { scene: 'pulse-mood', plugin: PLUGIN, glass: { blur: 16, opacity: 0.6 } } } as const
const drawn = await $.ui.mount({ ...target, surface: 'desktop' })
const svg = await drawn.find({ type: 'Svg' })
expect(String(svg?.props.source)).toContain('#2FB36B')
expect(String(svg?.props.source)).toContain('NVDA +4.00%')
expect(String(svg?.props.source)).not.toMatch(/pulseticker|Pulse for Mac|<script/)
await drawn.unmount()

const other = await $.ui.mount({ ...target, surface: 'desktop', props: { ...target.props, plugin: 'someone-else' } })
expect(await other.find({ type: 'Svg' })).toBe(undefined)
await other.unmount()

// A new session restores it; turning it off clears it and stays off.
await $.session.start(START)
expect(themes.length).toBe(2)
expect((await command($, 'backdrop off')).text).toBe('Backdrop off.')
expect(themes[2]).toBe('clear')
await $.session.start(START)
expect(themes.length).toBe(3)
})

test('the backdrop mood ignores cached quotes and escapes symbols', () => {
const quote = (changePercent: number) => ({ changePercent }) as unknown as Quote
expect(readMood(['A', 'B'], { A: quote(-2), B: quote(5) }, { B: 'failed' })).toEqual({ average: -2, mover: { symbol: 'A', change: -2 } })
expect(readMood(['A'], {}, {})).toEqual({ average: null, mover: undefined })
const scene = backdropScene({ average: -1, mover: { symbol: 'A&<B', change: -1 } })
expect(scene).toContain('#E5484D')
expect(scene).toContain('A&#38;&#60;B')
expect(backdropScene({ average: null }).length).toBeLessThan(131072)
})
Loading