diff --git a/README.md b/README.md index eca78e7..45adaa5 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,8 @@ bottom of the window. Pulse in the opencode sidebar -Add it to `~/.config/opencode/tui.json` and restart opencode: +In opencode v2, run `opencode plugin add opencode-pulse-ticker`. In opencode v1 +(1.15+), add it to `~/.config/opencode/tui.json` and restart opencode: ```json { "plugin": ["opencode-pulse-ticker"] } diff --git a/opencode/AGENTS.md b/opencode/AGENTS.md index 44ca362..c158fad 100644 --- a/opencode/AGENTS.md +++ b/opencode/AGENTS.md @@ -1,11 +1,16 @@ # Pulse for opencode - An opencode TUI plugin (npm package `opencode-pulse-ticker`, entry - `exports["./tui"]` = `src/tui.tsx`). opencode compiles the TSX with its own - Solid runtime, so ship source, no build step and no runtime dependencies. - Use only `@opencode-ai/plugin/tui` APIs that exist since opencode 1.15 - (`slots`, `keymap.registerLayer`, `kv`, `lifecycle`, `ui`), and test in a real - opencode before release. + `exports["./tui"]` = `src/tui.tsx`) for both opencode lines. opencode compiles + the TSX with its own Solid runtime, so ship source, no build step and no + runtime dependencies. `src/tui.tsx` exports `{ id, tui, setup }`: v1 + (`opencode-ai` 1.15+) calls `tui` (`src/v1.tsx`: `@opencode-ai/plugin/tui` + `slots`, `keymap.registerLayer`, `kv`, `lifecycle`, `ui`), v2 (`@opencode/cli` + 2.x) calls `setup` (`src/v2.tsx`: `@opencode/plugin/tui` `ui.slot`, + `keymap.layer`, `storage.store`, promise dialogs). Both render the views in + `src/view.tsx`. v2's `storage.store` updates only after its file is written, + so `v2.tsx` keeps an unsaved edit in memory until then. Test both lines in a + real opencode before release. - `src/quotes.js` and `src/watchlist.js` are copies of the Herdr mod's (`herdr/pulse/mods/pulse/`): only the header comment and `PULSE_URLS` differ, and a test checks it. Change both copies together. Keep them and @@ -18,10 +23,11 @@ - Respect Yahoo cooldowns; never show cached data as fresh or unknown delay as real time. Crypto never waits on Yahoo. - The quote band shows quotes only, never a Pulse for Mac link, and uses only - slots opencode adds content to (`app_bottom`, `*_prompt_right`). Never replace - opencode's own UI (`session_prompt`, `home_prompt`, `home_logo` etc.). + slots opencode adds content to (v1 `app_bottom`, `*_prompt_right`; v2 `append` + to `app`, `prompt.footer`, `sidebar.content`). Never replace opencode's own UI + (v1 `session_prompt`, `home_prompt`, `home_logo`; v2 `replace` claims). - `preview.png` must be a screenshot of the real plugin running in opencode. -- Releases: bump `version` in `package.json` and `VERSION` in `src/tui.tsx` +- Releases: bump `version` in `package.json` and `VERSION` in `src/view.tsx` together (a test checks they match), merge to main, then push the tag `opencode-v`. `.github/workflows/release-opencode.yml` checks the tag, tests, publishes to npm with provenance through npm trusted publishing diff --git a/opencode/README.md b/opencode/README.md index 7dd0716..f3c2e97 100644 --- a/opencode/README.md +++ b/opencode/README.md @@ -11,7 +11,19 @@ Finance, crypto pairs (`BTC/USDT`) from Binance's public Spot data. ## Install -Requires opencode 1.15 or later. Add the plugin to `tui.json` +Works with both opencode lines: v1 (`opencode-ai` 1.15 or later) and v2 +(`@opencode/cli` 2.x). + +**opencode v2:** run `opencode plugin add opencode-pulse-ticker`, or add it to +`~/.config/opencode/cli.json` yourself: + +```json +{ + "plugins": ["opencode-pulse-ticker"] +} +``` + +**opencode v1:** add the plugin to `tui.json` (`~/.config/opencode/tui.json` for every project, or `.opencode/tui.json` in one): ```json @@ -23,7 +35,15 @@ Requires opencode 1.15 or later. Add the plugin to `tui.json` Restart opencode and open a session: Pulse appears in the sidebar. To start from your own list instead of the starter one (AAPL, NVDA, ^GSPC, BTC/USDT), -pass it as an option: +pass it as an option. In v2's `cli.json`: + +```json +{ + "plugins": [{ "package": "opencode-pulse-ticker", "options": { "symbols": ["AAPL", "0700.HK", "^GSPC", "BTC/USDT"], "placement": "bottom" } }] +} +``` + +In v1's `tui.json`: ```json { @@ -36,7 +56,7 @@ pass it as an option: | `placement` | Where | | --- | --- | | `bottom` (default) | The bottom line of the window, on every screen | -| `right` | Right of the model name inside the prompt, first two tickers | +| `right` | In the prompt's footer, on the right (v1: right of the model name), first two tickers | | `off` | No band; the sidebar only | ## Use @@ -62,7 +82,7 @@ earlier day carries its date, and a delay Yahoo does not state is shown as Pulse sends read-only requests to two hosts, `query1.finance.yahoo.com` and `data-api.binance.vision`, with the tickers on your list and nothing else. Your -watchlist stays in opencode's own state on your computer. The only program the +watchlist stays in opencode's own storage on your computer. The only program the plugin starts is your system's browser (`open`, `xdg-open` or `start`), and only when you click "Pulse for Mac". @@ -76,14 +96,16 @@ Want the same watchlist in your menu bar, with charts and positions? ## Development -Point `tui.json` at your checkout and restart opencode after each change: +In opencode v2, link your checkout into a project's `.opencode/plugins/` +(`ln -s /path/to/Pulse/opencode .opencode/plugins/pulse`); v2 reloads it on +save. In v1, point `tui.json` at it and restart opencode after each change: ```json { "plugin": ["/path/to/Pulse/opencode"] } ``` `node --test opencode/tests/*.test.mjs` from the repository root runs the tests. -To release, bump the version in `package.json` and `src/tui.tsx`, merge, and +To release, bump the version in `package.json` and `src/view.tsx`, merge, and push the tag `opencode-v`: GitHub Actions publishes to npm with provenance (trusted publishing, no token) and creates a GitHub release. `src/quotes.js` and `src/watchlist.js` are shared with the Herdr mod; see diff --git a/opencode/package.json b/opencode/package.json index 07ec7eb..f9eb05c 100644 --- a/opencode/package.json +++ b/opencode/package.json @@ -1,6 +1,6 @@ { "name": "opencode-pulse-ticker", - "version": "0.1.0", + "version": "0.2.0", "description": "Stock and crypto quotes in the opencode sidebar, from the makers of Pulse for Mac", "type": "module", "license": "MIT", diff --git a/opencode/src/tui.tsx b/opencode/src/tui.tsx index b69172a..3de5822 100644 --- a/opencode/src/tui.tsx +++ b/opencode/src/tui.tsx @@ -1,340 +1,14 @@ -// Pulse for opencode: a stock and crypto watchlist in the session sidebar. -// Each ticker shows its price, today's line and its change; click one for its -// day. Stocks and indices come from Yahoo Finance, crypto pairs (BTC/USDT) -// from Binance's public Spot data. Edit the list with /pulse-add and -// /pulse-remove; it is kept in opencode's own state (api.kv). -import type { TuiPlugin, TuiPluginApi, TuiPluginModule } from "@opencode-ai/plugin/tui" -import { createMemo, createSignal, For, Show } from "solid-js" -import { spawn } from "node:child_process" -import { Watchlist } from "./watchlist.js" -import { PULSE_URLS, formatBandPrice, formatChange, normalizeSymbol } from "./quotes.js" -import { SPARK_WIDTH, detailText, sparkline } from "./format.js" - -const ID = "pulse-ticker" -const VERSION = "0.1.0" -// The watchlist and the panel's open state, in opencode's persisted key-value store. -const STORE = "pulse.watchlist.v1" -const OPEN = "pulse.sidebar.open" -const PLACEMENT = "pulse.band.placement" -// Where the one-line quote band goes; the sidebar panel is always there. -const PLACEMENTS = { - bottom: "Bottom line of the window", - right: "Right of the model name in the prompt (first two)", - off: "Off (sidebar only)", -} as const -type Placement = keyof typeof PLACEMENTS -const isPlacement = (value: unknown): value is Placement => typeof value === "string" && value in PLACEMENTS -const HEADERS = { "User-Agent": `Pulse-opencode/${VERSION}`, Accept: "application/json" } -// Pulse's blue: the bright one on dark themes, the text-safe one on light. -const brand = (api: TuiPluginApi) => (api.theme.mode() === "light" ? "#1066C6" : "#6AB0FF") - -type Quote = { - symbol: string - name: string - price: number - changePercent: number | null - currency: string | null - timestamp: number - delaySeconds: number | null - series: number[] - open: number | null - high: number | null - low: number | null - previousClose: number | null - periods: unknown -} - -// What the panel reads from watchlist.js (plain JavaScript, shared with the Herdr mod). -type Watch = { - preferences: { symbols: string[]; paused: boolean } - quotes: Record - errors: Record - message: string - loading: boolean - add(input: string): string - remove(symbol: string): string - pause(paused: boolean): string - refreshNow(): void - stop(): void - run(): Promise -} - -// The site, in the system's browser: the one program the plugin runs, and only on a click. -function openSite(place: keyof typeof PULSE_URLS) { - const url = PULSE_URLS[place] - const [command, args] = - process.platform === "darwin" - ? ["open", [url]] - : process.platform === "win32" - ? ["cmd", ["/c", "start", "", url]] - : ["xdg-open", [url]] - try { - spawn(command, args as string[], { detached: true, stdio: "ignore" }).on("error", () => {}).unref() - } catch { - /* No browser to open: nothing else to do. */ - } -} - -function startingList(options: Record | undefined) { - const given = options?.symbols - if (!Array.isArray(given)) return null - return { version: 1, symbols: given.filter((item) => typeof item === "string"), paused: false } -} - -function Panel(props: { api: TuiPluginApi; watch: Watch; tick: () => number }) { - const api = props.api - const theme = () => api.theme.current - const [open, setOpen] = createSignal(api.kv.get(OPEN, true) !== false) - const rows = createMemo(() => { - props.tick() - return props.watch.preferences.symbols.map((symbol: string) => ({ - symbol, - quote: props.watch.quotes[symbol], - error: props.watch.errors[symbol], - })) - }) - const status = createMemo(() => { - props.tick() - if (props.watch.preferences.paused) return "paused" - if (props.watch.loading && !Object.keys(props.watch.quotes).length) return "loading…" - return "" - }) - const message = createMemo(() => (props.tick(), props.watch.message)) - // Prices line up on the right: each one padded to the widest on the list. - const priceWidth = createMemo(() => - Math.max(0, ...rows().map((row) => (row.quote ? formatBandPrice(row.quote).length : 0))), - ) - const toggle = () => { - const next = !open() - setOpen(next) - api.kv.set(OPEN, next) - } - const color = (change: number | null | undefined) => - change === null || change === undefined ? theme().textMuted : change >= 0 ? theme().success : theme().error - const showDetail = (symbol: string) => { - const quote = props.watch.quotes[symbol] - if (!quote) return - const title = quote.name && quote.name !== symbol ? `${symbol} · ${quote.name}` : symbol - api.ui.dialog.replace(() => ( - api.ui.dialog.clear()} - /> - )) - } - - return ( - - - {open() ? "▼" : "▶"} - - Pulse - - {status()} - - - - - - {message()} - - 0} - fallback={Add a ticker with /pulse-add} - > - - {(row) => ( - showDetail(row.symbol)}> - - {row.symbol} - - - {row.error ? "unavailable" : "—"} - - } - > - {(quote) => ( - <> - - {sparkline(quote().series).padStart(SPARK_WIDTH)} - - - {formatBandPrice(quote()).padStart(priceWidth())} - - - {formatChange(quote().changePercent).padStart(7)} - - - )} - - - )} - - - openSite("panel")}> - Pulse for Mac ↗ - - - - ) -} - -/** One line of quotes: symbol, price, change. Only what has a quote; cut at the edge. */ -function Band(props: { api: TuiPluginApi; watch: Watch; tick: () => number; max?: number }) { - const theme = () => props.api.theme.current - const items = createMemo(() => { - props.tick() - return props.watch.preferences.symbols - .filter((symbol) => props.watch.quotes[symbol]) - .slice(0, props.max ?? Infinity) - .map((symbol) => props.watch.quotes[symbol]) - }) - const color = (change: number | null) => - change === null ? theme().textMuted : change >= 0 ? theme().success : theme().error - return ( - 0}> - - - {(quote, index) => ( - <> - {(index() ? " " : "") + quote.symbol} - {formatBandPrice(quote)} - {formatChange(quote.changePercent)} - - )} - - - - ) -} - -const tui: TuiPlugin = async (api, options) => { - const [tick, setTick] = createSignal(0) - const signal = api.lifecycle.signal - const watch: Watch = new Watchlist({ - load: () => api.kv.get(STORE, undefined) ?? startingList(options), - save: (preferences: unknown) => api.kv.set(STORE, preferences), - // Read-only GETs to Yahoo Finance and Binance; see quotes.js for the two hosts. - fetch: (url: string) => fetch(url, { headers: HEADERS, signal }), - now: () => Date.now(), - sleep: (ms: number) => - new Promise((resolve) => { - const timer = setTimeout(resolve, ms) - signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true }) - }), - changed: () => setTick((n) => n + 1), - }) - api.lifecycle.onDispose(() => watch.stop()) - watch.run().catch(() => {}) - - const act = (action: () => string) => { - try { - api.ui.toast({ variant: "info", title: "Pulse", message: action() }) - } catch (error) { - api.ui.toast({ variant: "error", title: "Pulse", message: error instanceof Error ? error.message : String(error) }) - } - setTick((n) => n + 1) - } - - const showAdd = () => - api.ui.dialog.replace(() => ( - { - api.ui.dialog.clear() - if (value.trim()) act(() => watch.add(value)) - }} - onCancel={() => api.ui.dialog.clear()} - /> - )) - - const showRemove = () => { - const symbols: string[] = watch.preferences.symbols - if (!symbols.length) return api.ui.toast({ variant: "info", title: "Pulse", message: "Your watchlist is empty." }) - api.ui.dialog.replace(() => ( - ({ title: symbol, value: symbol }))} - onSelect={(option) => { - api.ui.dialog.clear() - act(() => watch.remove(normalizeSymbol(option.value))) - }} - /> - )) - } - - api.keymap.registerLayer({ - commands: [ - { namespace: "palette", name: "pulse.add", title: "Pulse: add a ticker", category: "Pulse", slashName: "pulse-add", run: showAdd }, - { namespace: "palette", name: "pulse.remove", title: "Pulse: remove a ticker", category: "Pulse", slashName: "pulse-remove", run: showRemove }, - { - namespace: "palette", name: "pulse.refresh", title: "Pulse: refresh quotes", category: "Pulse", slashName: "pulse-refresh", - run: () => watch.refreshNow(), - }, - { - namespace: "palette", name: "pulse.pause", title: "Pulse: pause or resume refresh", category: "Pulse", slashName: "pulse-pause", - run: () => act(() => watch.pause(!watch.preferences.paused)), - }, - ], - } as Parameters[0]) - - // The person's pick (kept in kv) wins over the tui.json option; "bottom" by default. - const [placement, setPlacement] = createSignal( - isPlacement(api.kv.get(PLACEMENT, undefined)) - ? api.kv.get(PLACEMENT) - : isPlacement(options?.placement) ? (options.placement as Placement) : "bottom", - ) - const showPlacement = () => - api.ui.dialog.replace(() => ( - ({ title: PLACEMENTS[value], value }))} - onSelect={(option) => { - api.ui.dialog.clear() - setPlacement(option.value) - api.kv.set(PLACEMENT, option.value) - }} - /> - )) - const band = (max?: number) => - - api.keymap.registerLayer({ - commands: [ - { - namespace: "palette", name: "pulse.placement", title: "Pulse: move the quote band", category: "Pulse", - slashName: "pulse-band", run: showPlacement, - }, - ], - } as Parameters[0]) - - api.slots.register({ - order: 300, - slots: { - sidebar_content() { - return - }, - session_prompt_right() { - return {band(2)} - }, - home_prompt_right() { - return {band(2)} - }, - app_bottom() { - return ( - - {band()} - - ) - }, - }, - }) -} - -const plugin: TuiPluginModule & { id: string } = { id: ID, tui } +// Pulse for opencode: a stock and crypto watchlist in the session sidebar, plus a +// one-line quote band. Each ticker shows its price, today's line and its change; +// click one for its day. Stocks and indices come from Yahoo Finance, crypto pairs +// (BTC/USDT) from Binance's public Spot data. Edit the list with /pulse-add and +// /pulse-remove; it is kept in opencode's own storage. +// +// One module for both opencode lines: v1 (opencode-ai 1.15+) calls `tui`, v2 +// (@opencode/cli 2.x) calls `setup`. Both share the views in view.tsx. +import { ID } from "./view.tsx" +import { tui } from "./v1.tsx" +import { setup } from "./v2.tsx" + +const plugin = { id: ID, tui, setup } export default plugin diff --git a/opencode/src/v1.tsx b/opencode/src/v1.tsx new file mode 100644 index 0000000..3cc6020 --- /dev/null +++ b/opencode/src/v1.tsx @@ -0,0 +1,167 @@ +// The opencode v1 host (opencode-ai 1.15+): slots, keymap layer, kv and dialogs from +// @opencode-ai/plugin/tui. +import type { TuiPlugin, TuiPluginApi } from "@opencode-ai/plugin/tui" +import { createSignal, Show } from "solid-js" +import { normalizeSymbol } from "./quotes.js" +import { + Band, + PLACEMENTS, + Panel, + brandColor, + createWatch, + detail, + isPlacement, + openSite, + startingList, + type Placement, +} from "./view.tsx" + +// The watchlist, the panel's open state and the band's place, in opencode's persisted key-value store. +const STORE = "pulse.watchlist.v1" +const OPEN = "pulse.sidebar.open" +const PLACEMENT = "pulse.band.placement" + +export const tui: TuiPlugin = async (api, options) => { + const [tick, setTick] = createSignal(0) + const watch = createWatch({ + load: () => api.kv.get(STORE, undefined) ?? startingList(options), + save: (preferences) => api.kv.set(STORE, preferences), + signal: api.lifecycle.signal, + changed: () => setTick((n) => n + 1), + }) + api.lifecycle.onDispose(() => watch.stop()) + + const colors = () => { + const theme = api.theme.current + return { + text: theme.text, + muted: theme.textMuted, + up: theme.success, + down: theme.error, + brand: brandColor(api.theme.mode()), + } + } + + const act = (action: () => string) => { + try { + api.ui.toast({ variant: "info", title: "Pulse", message: action() }) + } catch (error) { + api.ui.toast({ variant: "error", title: "Pulse", message: error instanceof Error ? error.message : String(error) }) + } + setTick((n) => n + 1) + } + + const showDetail = (symbol: string) => { + const shown = detail(watch, symbol) + if (!shown) return + api.ui.dialog.replace(() => ( + api.ui.dialog.clear()} /> + )) + } + + const showAdd = () => + api.ui.dialog.replace(() => ( + { + api.ui.dialog.clear() + if (value.trim()) act(() => watch.add(value)) + }} + onCancel={() => api.ui.dialog.clear()} + /> + )) + + const showRemove = () => { + const symbols: string[] = watch.preferences.symbols + if (!symbols.length) return api.ui.toast({ variant: "info", title: "Pulse", message: "Your watchlist is empty." }) + api.ui.dialog.replace(() => ( + ({ title: symbol, value: symbol }))} + onSelect={(option) => { + api.ui.dialog.clear() + act(() => watch.remove(normalizeSymbol(option.value))) + }} + /> + )) + } + + // The person's pick (kept in kv) wins over the tui.json option; "bottom" by default. + const [placement, setPlacement] = createSignal( + isPlacement(api.kv.get(PLACEMENT, undefined)) + ? api.kv.get(PLACEMENT) + : isPlacement(options?.placement) ? (options.placement as Placement) : "bottom", + ) + const showPlacement = () => + api.ui.dialog.replace(() => ( + ({ title: PLACEMENTS[value], value }))} + onSelect={(option) => { + api.ui.dialog.clear() + setPlacement(option.value) + api.kv.set(PLACEMENT, option.value) + }} + /> + )) + + api.keymap.registerLayer({ + commands: [ + { namespace: "palette", name: "pulse.add", title: "Pulse: add a ticker", category: "Pulse", slashName: "pulse-add", run: showAdd }, + { namespace: "palette", name: "pulse.remove", title: "Pulse: remove a ticker", category: "Pulse", slashName: "pulse-remove", run: showRemove }, + { + namespace: "palette", name: "pulse.refresh", title: "Pulse: refresh quotes", category: "Pulse", slashName: "pulse-refresh", + run: () => watch.refreshNow(), + }, + { + namespace: "palette", name: "pulse.pause", title: "Pulse: pause or resume refresh", category: "Pulse", slashName: "pulse-pause", + run: () => act(() => watch.pause(!watch.preferences.paused)), + }, + { + namespace: "palette", name: "pulse.placement", title: "Pulse: move the quote band", category: "Pulse", + slashName: "pulse-band", run: showPlacement, + }, + ], + } as Parameters[0]) + + const [open, setOpen] = createSignal(api.kv.get(OPEN, true) !== false) + const toggle = () => { + setOpen(!open()) + api.kv.set(OPEN, open()) + } + const band = (max?: number) => + + api.slots.register({ + order: 300, + slots: { + sidebar_content() { + return ( + openSite("panel")} + /> + ) + }, + session_prompt_right() { + return {band(2)} + }, + home_prompt_right() { + return {band(2)} + }, + app_bottom() { + return ( + + {band()} + + ) + }, + }, + }) +} diff --git a/opencode/src/v2.tsx b/opencode/src/v2.tsx new file mode 100644 index 0000000..9aac4df --- /dev/null +++ b/opencode/src/v2.tsx @@ -0,0 +1,187 @@ +// The opencode v2 host (@opencode/cli 2.x): slot claims, keymap layers, storage and +// promise dialogs from @opencode/plugin/tui. Types are written out here so the +// package needs no v2 dependency. +import { createSignal, Show } from "solid-js" +import { normalizeSymbol } from "./quotes.js" +import { + Band, + PLACEMENTS, + Panel, + brandColor, + createWatch, + detail, + isPlacement, + openSite, + startingList, + type Placement, +} from "./view.tsx" + +// The parts of the v2 plugin context this file uses. +type Context = { + options: Readonly> + theme: any + themeMode: "dark" | "light" + storage: { + store( + key: string, + options: { initial: Value }, + ): readonly [Value, (mutation: (draft: Value) => void) => Promise] + } + keymap: { layer(factory: () => { mode?: string; commands?: readonly any[] }): void } + ui: { + toast: { show(options: { title?: string; message: string; variant?: "info" | "success" | "warning" | "error" }): void } + dialog: { + alert(options: { title: string; message: string }): Promise + prompt(options: { title: string; description?: string; placeholder?: string }): Promise + select(options: { + title: string + options: readonly { title: string; value: Value; description?: string }[] + current?: Value + }): Promise + } + slot(claim: { append: string; render: (input: any) => any }): () => void + } +} + +export async function setup(context: Context) { + const options = context.options + const controller = new AbortController() + const [tick, setTick] = createSignal(0) + + // Durable JSON in opencode's own storage. A store holds an object, so each value sits in one. + const [saved, save] = context.storage.store<{ preferences: unknown }>("watchlist", { initial: { preferences: null } }) + const [view, saveView] = context.storage.store<{ open: boolean; placement: string | null }>("view", { + initial: { open: true, placement: null }, + }) + + // The store updates only once its file is written, so an edit is kept here until then; + // otherwise the next read would bring back the list from before the edit. + let unsaved: unknown = undefined + const copy = (value: unknown) => JSON.parse(JSON.stringify(value)) + const watch = createWatch({ + load: () => copy(unsaved ?? saved.preferences ?? startingList(options)), + save: (preferences) => { + const value = copy(preferences) + unsaved = value + save((draft) => void (draft.preferences = value)) + .catch(() => {}) + .finally(() => unsaved === value && (unsaved = undefined)) + }, + signal: controller.signal, + changed: () => setTick((n) => n + 1), + }) + + const colors = () => { + const theme = context.theme + return { + text: theme.text.base, + muted: theme.text.muted, + up: theme.text.feedback?.success?.base ?? theme.text.base, + down: theme.text.feedback?.error?.base ?? theme.text.base, + brand: brandColor(context.themeMode), + } + } + + const toast = (message: string, variant: "info" | "error" = "info") => + context.ui.toast.show({ title: "Pulse", message, variant }) + const act = (action: () => string) => { + try { + toast(action()) + } catch (error) { + toast(error instanceof Error ? error.message : String(error), "error") + } + setTick((n) => n + 1) + } + + const showDetail = (symbol: string) => { + const shown = detail(watch, symbol) + if (shown) void context.ui.dialog.alert(shown) + } + const showAdd = async () => { + const value = await context.ui.dialog.prompt({ + title: "Add to Pulse", + placeholder: "AAPL, 0700.HK, ^GSPC or BTC/USDT", + }) + if (value?.trim()) act(() => watch.add(value)) + } + const showRemove = async () => { + const symbols: string[] = [...watch.preferences.symbols] + if (!symbols.length) return toast("Your watchlist is empty.") + const symbol = await context.ui.dialog.select({ + title: "Remove from Pulse", + options: symbols.map((value) => ({ title: value, value })), + }) + if (symbol) act(() => watch.remove(normalizeSymbol(symbol))) + } + + // The person's pick (kept in storage) wins over the plugin option; "bottom" by default. + const placement = (): Placement => + isPlacement(view.placement) ? view.placement : isPlacement(options?.placement) ? options.placement : "bottom" + const showPlacement = async () => { + const value = await context.ui.dialog.select({ + title: "Pulse quote band", + current: placement(), + options: (Object.keys(PLACEMENTS) as Placement[]).map((value) => ({ title: PLACEMENTS[value], value })), + }) + if (value) await saveView((draft) => void (draft.placement = value)) + } + + context.keymap.layer(() => ({ + mode: "global", + commands: [ + { id: "pulse.add", title: "Pulse: add a ticker", group: "Pulse", palette: true, slash: { name: "pulse-add" }, run: showAdd }, + { id: "pulse.remove", title: "Pulse: remove a ticker", group: "Pulse", palette: true, slash: { name: "pulse-remove" }, run: showRemove }, + { + id: "pulse.refresh", title: "Pulse: refresh quotes", group: "Pulse", palette: true, slash: { name: "pulse-refresh" }, + run: () => watch.refreshNow(), + }, + { + id: "pulse.pause", title: "Pulse: pause or resume refresh", group: "Pulse", palette: true, slash: { name: "pulse-pause" }, + run: () => act(() => watch.pause(!watch.preferences.paused)), + }, + { + id: "pulse.placement", title: "Pulse: move the quote band", group: "Pulse", palette: true, slash: { name: "pulse-band" }, + run: showPlacement, + }, + ], + })) + + const toggle = () => void saveView((draft) => void (draft.open = !draft.open)) + const band = (max?: number) => + + context.ui.slot({ + append: "sidebar.content", + render: () => ( + view.open !== false} + toggle={toggle} + onDetail={showDetail} + onLink={() => openSite("panel")} + /> + ), + }) + context.ui.slot({ + append: "prompt.footer", + render: () => ( + + {band(2)} + + ), + }) + context.ui.slot({ + append: "app", + render: () => ( + + {band()} + + ), + }) + + return () => { + controller.abort() + watch.stop() + } +} diff --git a/opencode/src/view.tsx b/opencode/src/view.tsx new file mode 100644 index 0000000..fd6b695 --- /dev/null +++ b/opencode/src/view.tsx @@ -0,0 +1,230 @@ +// The sidebar panel and the one-line quote band, shared by the opencode v1 and v2 +// hosts (v1.tsx, v2.tsx). Each host passes its own theme colors and actions. +import { createMemo, For, Show } from "solid-js" +import { spawn } from "node:child_process" +import { Watchlist } from "./watchlist.js" +import { PULSE_URLS, formatBandPrice, formatChange } from "./quotes.js" +import { SPARK_WIDTH, detailText, sparkline } from "./format.js" + +export const ID = "pulse-ticker" +export const VERSION = "0.2.0" +export const HEADERS = { "User-Agent": `Pulse-opencode/${VERSION}`, Accept: "application/json" } +// Pulse's blue: the bright one on dark themes, the text-safe one on light. +export const brandColor = (mode: string) => (mode === "light" ? "#1066C6" : "#6AB0FF") + +// Where the one-line quote band goes; the sidebar panel is always there. +export const PLACEMENTS = { + bottom: "Bottom line of the window", + right: "Right of the prompt's footer (first two)", + off: "Off (sidebar only)", +} as const +export type Placement = keyof typeof PLACEMENTS +export const isPlacement = (value: unknown): value is Placement => typeof value === "string" && value in PLACEMENTS + +export type Quote = { + symbol: string + name: string + price: number + changePercent: number | null + currency: string | null + timestamp: number + delaySeconds: number | null + series: number[] + open: number | null + high: number | null + low: number | null + previousClose: number | null + periods: unknown +} + +// What the views read from watchlist.js (plain JavaScript, shared with the Herdr mod). +export type Watch = { + preferences: { symbols: string[]; paused: boolean } + quotes: Record + errors: Record + message: string + loading: boolean + add(input: string): string + remove(symbol: string): string + pause(paused: boolean): string + refreshNow(): void + stop(): void + run(): Promise +} + +// Colors as each host's renderer takes them (RGBA in v1, strings or RGBA in v2). +export type Colors = { text: any; muted: any; up: any; down: any; brand: any } + +// The site, in the system's browser: the one program the plugin runs, and only on a click. +export function openSite(place: keyof typeof PULSE_URLS) { + const url = PULSE_URLS[place] + const [command, args] = + process.platform === "darwin" + ? ["open", [url]] + : process.platform === "win32" + ? ["cmd", ["/c", "start", "", url]] + : ["xdg-open", [url]] + try { + spawn(command, args as string[], { detached: true, stdio: "ignore" }).on("error", () => {}).unref() + } catch { + /* No browser to open: nothing else to do. */ + } +} + +/** The watchlist, refreshing until signal aborts; load and save go to the host's own storage. */ +export function createWatch(input: { + load: () => unknown + save: (preferences: unknown) => void + signal: AbortSignal + changed: () => void +}): Watch { + const { signal } = input + const watch: Watch = new Watchlist({ + load: input.load, + save: input.save, + // Read-only GETs to Yahoo Finance and Binance; see quotes.js for the two hosts. + fetch: (url: string) => fetch(url, { headers: HEADERS, signal }), + now: () => Date.now(), + sleep: (ms: number) => + new Promise((resolve) => { + const timer = setTimeout(resolve, ms) + signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true }) + }), + changed: input.changed, + }) + signal.addEventListener("abort", () => watch.stop(), { once: true }) + watch.run().catch(() => {}) + return watch +} + +export function startingList(options: Record | undefined) { + const given = options?.symbols + if (!Array.isArray(given)) return null + return { version: 1, symbols: given.filter((item) => typeof item === "string"), paused: false } +} + +/** Title and text of the detail dialog for one ticker, or null without a quote. */ +export function detail(watch: Watch, symbol: string) { + const quote = watch.quotes[symbol] + if (!quote) return null + return { + title: quote.name && quote.name !== symbol ? `${symbol} · ${quote.name}` : symbol, + message: detailText(quote, watch.errors[symbol], Date.now()), + } +} + +export function Panel(props: { + colors: () => Colors + watch: Watch + tick: () => number + open: () => boolean + toggle: () => void + onDetail: (symbol: string) => void + onLink: () => void +}) { + const c = () => props.colors() + const rows = createMemo(() => { + props.tick() + return props.watch.preferences.symbols.map((symbol: string) => ({ + symbol, + quote: props.watch.quotes[symbol], + error: props.watch.errors[symbol], + })) + }) + const status = createMemo(() => { + props.tick() + if (props.watch.preferences.paused) return "paused" + if (props.watch.loading && !Object.keys(props.watch.quotes).length) return "loading…" + return "" + }) + const message = createMemo(() => (props.tick(), props.watch.message)) + // Prices line up on the right: each one padded to the widest on the list. + const priceWidth = createMemo(() => + Math.max(0, ...rows().map((row) => (row.quote ? formatBandPrice(row.quote).length : 0))), + ) + const color = (change: number | null | undefined) => + change === null || change === undefined ? c().muted : change >= 0 ? c().up : c().down + + return ( + + + {props.open() ? "▼" : "▶"} + + Pulse + + {status()} + + + + + + {message()} + + 0} fallback={Add a ticker with /pulse-add}> + + {(row) => ( + props.onDetail(row.symbol)}> + + {row.symbol} + + + {row.error ? "unavailable" : "—"} + + } + > + {(quote) => ( + <> + + {sparkline(quote().series).padStart(SPARK_WIDTH)} + + + {formatBandPrice(quote()).padStart(priceWidth())} + + + {formatChange(quote().changePercent).padStart(7)} + + + )} + + + )} + + + + Pulse for Mac ↗ + + + + ) +} + +/** One line of quotes: symbol, price, change. Only what has a quote; cut at the edge. */ +export function Band(props: { colors: () => Colors; watch: Watch; tick: () => number; max?: number }) { + const c = () => props.colors() + const items = createMemo(() => { + props.tick() + return props.watch.preferences.symbols + .filter((symbol) => props.watch.quotes[symbol]) + .slice(0, props.max ?? Infinity) + .map((symbol) => props.watch.quotes[symbol]) + }) + const color = (change: number | null) => (change === null ? c().muted : change >= 0 ? c().up : c().down) + return ( + 0}> + + + {(quote, index) => ( + <> + {(index() ? " " : "") + quote.symbol} + {formatBandPrice(quote)} + {formatChange(quote.changePercent)} + + )} + + + + ) +} diff --git a/opencode/tests/pulse.test.mjs b/opencode/tests/pulse.test.mjs index eadda93..6ecac3b 100644 --- a/opencode/tests/pulse.test.mjs +++ b/opencode/tests/pulse.test.mjs @@ -58,5 +58,5 @@ test("the detail names its source and never calls an unknown delay real time", ( test("the User-Agent version matches package.json, which drives the npm release", () => { const { version } = JSON.parse(readFileSync(here("../package.json"), "utf8")); - assert.match(readFileSync(here("../src/tui.tsx"), "utf8"), new RegExp(`const VERSION = "${version.replace(/\./g, "\\.")}"`)); + assert.match(readFileSync(here("../src/view.tsx"), "utf8"), new RegExp(`const VERSION = "${version.replace(/\./g, "\\.")}"`)); });