diff --git a/.github/workflows/release-raycast.yml b/.github/workflows/release-raycast.yml deleted file mode 100644 index 91068db..0000000 --- a/.github/workflows/release-raycast.yml +++ /dev/null @@ -1,84 +0,0 @@ -name: Release Pulse for Raycast - -# Submits raycast/ to the Raycast Store: `ray publish` forks raycast/extensions -# under the approving account and opens (or updates) the submission PR there. -# -# Start it by pushing a tag raycast-v (e.g. raycast-v2026.11.03), -# or from the Actions tab. No token is stored anywhere: the job asks GitHub for a -# one-time device code, prints it in the log and the run summary, and waits for -# you to approve it at https://github.com/login/device (signed in with your -# passkey). The token it gets lives only in this job. -on: - push: - tags: ["raycast-v*"] - workflow_dispatch: - -permissions: - contents: read - -jobs: - publish: - if: github.repository == 'fatwang2/Pulse' - runs-on: ubuntu-latest - timeout-minutes: 30 - environment: raycast # add required reviewers on this environment to approve each submission - steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - with: - persist-credentials: false - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 - with: - node-version: '24' - - name: Test, lint and build - run: make test-raycast - - name: Sign in to GitHub with a device code and publish - working-directory: raycast - env: - # The Raycast CLI's own GitHub OAuth app, the same one `npm run publish` uses on a Mac. - RAYCAST_GITHUB_CLIENT_ID: e69bae0ec90f5e838555 - run: | - set -euo pipefail - # JSON bodies, exactly as the Raycast CLI sends them. - post() { curl -fsS -X POST "$1" -H 'Accept: application/json' -H 'Content-Type: application/json' -d "$2"; } - device="$(post https://github.com/login/device/code \ - "$(jq -nc --arg id "$RAYCAST_GITHUB_CLIENT_ID" '{client_id: $id, scope: "repo"}')")" - code="$(jq -r .user_code <<<"$device")" - device_code="$(jq -r .device_code <<<"$device")" - interval="$(jq -r .interval <<<"$device")" - expires="$(jq -r .expires_in <<<"$device")" - url="$(jq -r .verification_uri <<<"$device")" - echo "::notice title=Approve the Raycast submission::Open ${url} and enter ${code} (valid for $((expires / 60)) minutes)." - { - echo "### Approve the Raycast submission" - echo - echo "Open ${url}, sign in with your passkey, and enter **${code}**." - echo "The code is valid for $((expires / 60)) minutes." - } >> "$GITHUB_STEP_SUMMARY" - - token="" - deadline=$(( $(date +%s) + expires )) - while [ "$(date +%s)" -lt "$deadline" ]; do - sleep "$interval" - answer="$(post https://github.com/login/oauth/access_token \ - "$(jq -nc --arg id "$RAYCAST_GITHUB_CLIENT_ID" --arg code "$device_code" \ - '{client_id: $id, device_code: $code, grant_type: "urn:ietf:params:oauth:grant-type:device_code"}')")" - error="$(jq -r '.error // empty' <<<"$answer")" - case "$error" in - "") token="$(jq -r .access_token <<<"$answer")"; break ;; - authorization_pending) ;; - slow_down) interval=$(( interval + 5 )) ;; - *) echo "GitHub refused the device code: ${error}" >&2; exit 1 ;; - esac - done - if [ -z "$token" ]; then - echo "The device code expired before it was approved." >&2 - exit 1 - fi - echo "::add-mask::${token}" - - login="$(curl -fsS https://api.github.com/user -H "Authorization: Bearer ${token}" | jq -r .login)" - echo "Approved by ${login}." - git config --global user.name "${login}" - git config --global user.email "${login}@users.noreply.github.com" - # `ray publish` skips its own interactive GitHub sign-in when this is set. - GITHUB_ACCESS_TOKEN="$token" npx ray publish diff --git a/docs/raycast.md b/docs/raycast.md index 0f822d3..e47c607 100644 --- a/docs/raycast.md +++ b/docs/raycast.md @@ -17,14 +17,11 @@ - Follow Raycast's Store rules: US English UI, Title Case action titles, `CHANGELOG.md` with `{PR_MERGE_DATE}`, `package-lock.json` committed, `npm run lint` and `npm run build` clean before publishing. -- Releases go through `.github/workflows/release-raycast.yml` (tag - `raycast-v*` or manual run, environment `raycast`): GitHub sign-in by device - code approved with the owner's passkey, then `ray publish`. Never store a - GitHub token for it. +- Publish only from the owner's Mac mini (see Releasing). Never from CI or a + fresh machine, and never store a GitHub token. ## Development - ```sh npm install npm run dev # opens the extension in Raycast @@ -34,10 +31,19 @@ npm run lint ## Releasing -The Raycast Store takes extensions as pull requests to `raycast/extensions`. -`.github/workflows/release-raycast.yml` submits this folder: push a tag -`raycast-v` (for example `raycast-v2026.11.03`) or start it from the -Actions tab. After the `raycast` environment approval, the job prints a -one-time GitHub device code; open `https://github.com/login/device`, sign in -with your passkey and enter it. No token is stored. The first run opens a -draft PR; mark it "Ready for review". Later runs update the same submission. +The Raycast Store takes extensions as pull requests to `raycast/extensions`, +and `ray publish` opens or updates that pull request. It keeps its own clone +of the fork in `~/.config/raycast/public-extensions-fork` and updates the open +submission only from the machine holding that clone. A fresh machine (or a CI +runner) rebuilds the `ext/pulse` branch, which closes the open submission and +opens a new one. So publish from the Mac mini only: + +```sh +cd raycast +GIT_CONFIG_COUNT=2 \ + GIT_CONFIG_KEY_0=user.name GIT_CONFIG_VALUE_0=fatwang2 \ + GIT_CONFIG_KEY_1=user.email GIT_CONFIG_VALUE_1=fatwang2@users.noreply.github.com \ + GITHUB_ACCESS_TOKEN="$(gh auth token)" npx ray publish +``` + +The token is gh's existing sign-in and is used for this command only. diff --git a/raycast/src/lib/catalog.ts b/raycast/src/lib/catalog.ts index fb14ad2..901f422 100644 --- a/raycast/src/lib/catalog.ts +++ b/raycast/src/lib/catalog.ts @@ -42,11 +42,33 @@ export function validCatalog(value: unknown): value is CatalogDocument { return ( document?.schema === 1 && typeof document.generatedAt === "string" && + Array.isArray(document.markets) && Array.isArray(document.securities) && - Array.isArray(document.markets) + document.securities.every(validSecurity) && + (document.crypto === undefined || (Array.isArray(document.crypto) && document.crypto.every(validCoin))) ); } +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); +const optionalNames = (value: unknown) => value === undefined || isObject(value); +const optionalAliases = (value: unknown) => value === undefined || Array.isArray(value); + +// Every entry the index reads, so a malformed export never replaces the copy in hand. +function validSecurity(entry: unknown): boolean { + return ( + isObject(entry) && + typeof entry.m === "string" && + typeof entry.c === "string" && + optionalNames(entry.n) && + optionalAliases(entry.a) + ); +} + +function validCoin(entry: unknown): boolean { + return isObject(entry) && typeof entry.b === "string" && optionalNames(entry.n) && optionalAliases(entry.a); +} + export class CatalogStore { constructor( private readonly directory: string, diff --git a/raycast/src/search-symbol.tsx b/raycast/src/search-symbol.tsx index 117ee2e..e8ff4b2 100644 --- a/raycast/src/search-symbol.tsx +++ b/raycast/src/search-symbol.tsx @@ -25,6 +25,7 @@ import { MARKET_CURRENCIES, MARKET_FILTERS, MARKET_LABELS, + Market, PULSE_FOR_MAC_URL, isCryptoPair, normalizeTypedSymbol, @@ -78,9 +79,23 @@ function typedInstrument(query: string, index: SymbolIndex | undefined): Instrum } // A typed "^FTSE" is an index whatever its exchange, so the Indices filter keeps it. if (symbol.startsWith("^")) return { symbol, market: "index", kind: "index", name: symbol, exchange: null }; - return { symbol, market: "us", kind: "equity", name: symbol, exchange: null }; + const suffix = /\.([A-Z]+)$/.exec(symbol)?.[1]; + const market = (suffix && SUFFIX_MARKETS[suffix]) ?? "us"; + return { symbol, market, kind: "equity", name: symbol, exchange: null }; } +// The Yahoo suffixes of the markets the filter offers, so a typed `7203.T` stays under Japan. +const SUFFIX_MARKETS: Record = { + HK: "hk", + SS: "sh", + SZ: "sz", + T: "jp", + KS: "kr", + KQ: "kq", + TW: "tw", + TWO: "two", +}; + const changeColor = (value: number | null | undefined) => value === null || value === undefined ? Color.SecondaryText : value >= 0 ? Color.Green : Color.Red; @@ -115,14 +130,7 @@ export default function Command() { error: indexError, revalidate: reloadIndex, } = usePromise(loadIndex, [], { - onError: (error) => { - showToast({ - style: Toast.Style.Failure, - title: "Could not load the symbol list", - message: error.message, - primaryAction: { title: "Retry", onAction: () => reloadIndex() }, - }); - }, + failureToastOptions: { title: "Could not load the symbol list" }, }); const language: Language = readerLanguage(preferences.nameLanguage ?? "auto", searchText, SYSTEM_LOCALE); @@ -160,7 +168,11 @@ export default function Command() { const visible = useMemo(() => sections.flatMap((section) => section.items.map((item) => item.symbol)), [sections]); // List rows carry a price only while the detail pane is hidden; the pane prices the selected row itself. - const { data: rows, isLoading: rowsLoading } = useCachedPromise( + const { + data: priced, + isLoading: rowsLoading, + revalidate: repriceRows, + } = useCachedPromise( async (symbols: string[]) => { const crypto = symbols.filter(isCryptoPair); const stocks = symbols.filter((symbol) => !isCryptoPair(symbol)); @@ -172,14 +184,39 @@ export default function Command() { return Object.assign({}, ...each.map((result) => (result.status === "fulfilled" ? result.value : {}))); }), ]); - return { + const failed = [ + ...(stockRows.status === "rejected" ? ["Yahoo Finance"] : []), + ...(cryptoRows.status === "rejected" ? ["Binance"] : []), + ]; + const quotes = { ...(stockRows.status === "fulfilled" ? stockRows.value : {}), ...(cryptoRows.status === "fulfilled" ? cryptoRows.value : {}), } as Record; + // Nothing priced: fail outright, and the hook's toast offers Retry. + if (failed.length && Object.keys(quotes).length === 0) { + throw new Error(`${failed.join(" and ")} did not answer.`); + } + return { quotes, failed }; }, [visible], - { execute: !showingDetail && visible.length > 0, keepPreviousData: true }, + { + execute: !showingDetail && visible.length > 0, + keepPreviousData: true, + failureToastOptions: { title: "Could not load prices" }, + }, ); + const rows = priced?.quotes; + // Some rows priced and some not: keep the priced ones, and say which source failed. + const failedSources = priced?.failed.join(" and "); + useEffect(() => { + if (!failedSources) return; + showToast({ + style: Toast.Style.Failure, + title: "Some prices could not be loaded", + message: `${failedSources} did not answer.`, + primaryAction: { title: "Retry", onAction: () => repriceRows() }, + }); + }, [priced]); const remember = (symbol: string) => setRecent((current) => [symbol, ...current.filter((item) => item !== symbol)].slice(0, RECENT_LIMIT)); @@ -304,7 +341,6 @@ function InstrumentActions(props: { remember(instrument.symbol)} /> {instrument.name !== instrument.symbol && ( diff --git a/raycast/tests/catalog.test.ts b/raycast/tests/catalog.test.ts index 702dde3..58a370f 100644 --- a/raycast/tests/catalog.test.ts +++ b/raycast/tests/catalog.test.ts @@ -70,6 +70,22 @@ test("refuses a truncated or older file and keeps the copy in hand", async () => assert.equal(onDisk.generatedAt, "2026-11-02T00:00:00Z"); }); +test("refuses an export whose entries are malformed", async () => { + const directory = await mkdtemp(join(tmpdir(), "pulse-raycast-")); + const good = JSON.parse(catalog("2026-11-03T00:00:00Z", 100)); + const { fetcher } = fakeFetch([ + new Response(catalog("2026-11-02T00:00:00Z", 100), { headers: { etag: '"a"' } }), + new Response(JSON.stringify({ ...good, securities: [...good.securities, null] })), + new Response(JSON.stringify({ ...good, crypto: "BTC" })), + new Response(JSON.stringify({ ...good, securities: [...good.securities, { m: "us", c: 7 }] })), + ]); + const store = new CatalogStore(directory, fetcher); + const first = await store.refreshCatalog(null); + for (let attempt = 0; attempt < 3; attempt += 1) await assert.rejects(store.refreshCatalog(first)); + const onDisk = JSON.parse(await readFile(join(directory, "symbols-v1.json"), "utf8")); + assert.equal(onDisk.generatedAt, "2026-11-02T00:00:00Z"); +}); + test("keeps Binance's trading pairs as base and quote", async () => { const directory = await mkdtemp(join(tmpdir(), "pulse-raycast-")); const symbols = Array.from({ length: 150 }, (_, i) => ({