From 67494ca128190168a1a57587ce30f8e953b9c039 Mon Sep 17 00:00:00 2001 From: lixiangroir-Ideal <361820199+lixiangroir-Ideal@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:19:32 +0800 Subject: [PATCH 01/16] Add weather-news-board Mini App --- README.md | 1 + README.zh-CN.md | 1 + .../.minimax-plugin/plugin.json | 18 + .../weather-news-board/LICENSE | 21 + .../weather-news-board/README.md | 70 + .../weather-news-board/README.zh-CN.md | 57 + .../weather-news-board/icon.png | Bin 0 -> 1574 bytes .../miniapp/client/index.html | 1702 +++++++++++++++++ .../weather-news-board/miniapp/miniapp.json | 20 + .../miniapp/node/miniapp-api.ts | 641 +++++++ .../miniapp/node/server.mjs | 1324 +++++++++++++ .../weather-news-board/package.json | 6 + 12 files changed, 3861 insertions(+) create mode 100644 plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json create mode 100644 plugins/lixiangroir-ideal/weather-news-board/LICENSE create mode 100644 plugins/lixiangroir-ideal/weather-news-board/README.md create mode 100644 plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md create mode 100644 plugins/lixiangroir-ideal/weather-news-board/icon.png create mode 100644 plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html create mode 100644 plugins/lixiangroir-ideal/weather-news-board/miniapp/miniapp.json create mode 100644 plugins/lixiangroir-ideal/weather-news-board/miniapp/node/miniapp-api.ts create mode 100644 plugins/lixiangroir-ideal/weather-news-board/miniapp/node/server.mjs create mode 100644 plugins/lixiangroir-ideal/weather-news-board/package.json diff --git a/README.md b/README.md index c8d38743..86551113 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | --- | --- | --- | | [Postman Lite](plugins/ssugarr/postman-lite/) | A lightweight local API request tool: build requests, send them through a local proxy that sidesteps browser CORS limits, and inspect responses, with collections kept as plain JSON | [ssugarr](https://github.com/ssugarr) | | [Weekly Planner](plugins/alanhean/weekly-planner/) | A local weekly planner: add tasks with a date and a priority, review them day by day, tick them off, and track the week's completion rate | [Alanhean](https://github.com/Alanhean) | +| [天气 · 新闻看板](plugins/lixiangroir-ideal/weather-news-board/) | One dashboard page for live weather, A-share and gold, silver, crude oil and Bitcoin quotes, and six switchable news columns, with precious metals always shown in CNY per gram | [lixiangroir-Ideal](https://github.com/lixiangroir-Ideal) | | [DeepSeek Chat Migration](plugins/danielwalnut/deepseek-chat-migration/) | Preview official DeepSeek web exports locally, restore branches and attachments, and import selected conversations as native MiniMax Code sessions with a bundled importer | [DanielWalnut](https://github.com/DanielWalnut) | | [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | Run OpenFilm inside MiniMax Code with the desktop interface: Studio editor, chat column and local agents, with a web-Studio fallback | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | | [Dynamic Workflow Console](plugins/stevenjj33/workflow-console/) | Run and supervise MiniMax Code dynamic workflows from one page: live status, a stage-and-dependency flow graph, per-node output, approval and control, templates, and report export | [stevenjj33](https://github.com/stevenjj33) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 3d158767..3178b68a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -59,6 +59,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | --- | --- | --- | | [Postman Lite](plugins/ssugarr/postman-lite/README.zh-CN.md) | 轻量的本地 API 请求工具:构建请求、通过本地代理转发(绕过浏览器 CORS 限制)、查看响应,集合以纯 JSON 保存 | [ssugarr](https://github.com/ssugarr) | | [周计划](plugins/alanhean/weekly-planner/README.zh-CN.md) | 本地周计划:手动录入任务、日期与优先级,按天查看安排,勾选完成并跟踪本周完成率 | [Alanhean](https://github.com/Alanhean) | +| [天气 · 新闻看板](plugins/lixiangroir-ideal/weather-news-board/) | 一个看板页同时看实时天气、A 股与黄金白银原油比特币行情、六个可切换的新闻栏目,贵金属统一按人民币每克显示 | [lixiangroir-Ideal](https://github.com/lixiangroir-Ideal) | | [DeepSeek 会话迁移](plugins/danielwalnut/deepseek-chat-migration/README_ZH.md) | 在本机预览 DeepSeek 网页版官方导出包,恢复分支和附件,并用自带的导入脚本把选中对话导入成 MiniMax Code 原生会话 | [DanielWalnut](https://github.com/DanielWalnut) | | [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | 把 OpenFilm 装进 MiniMax Code:桌面版界面(Studio 编辑器 + 聊天栏 + 本地 agent),桌面模式不可用时回落网页版 | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | | [动态工作流控制台](plugins/stevenjj33/workflow-console/README.zh-CN.md) | 在一个页面里运行并盯住 MiniMax Code 动态工作流:实时状态、按阶段与依赖画出的流程图、节点输出、审核与控制、模板与报告导出 | [stevenjj33](https://github.com/stevenjj33) | diff --git a/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json b/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json new file mode 100644 index 00000000..20a99616 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "schemaVersion": 1, + "name": "weather-news-board", + "displayName": "天气 · 新闻看板", + "version": "1.0.0", + "description": "展示实时天气与国内要闻、今日头条热榜、知乎日报,支持随时手动刷新,并可自选股票与黄金、原油等国际品种行情。", + "author": "User", + "icon": "icon.png", + "category": "Productivity", + "exampleQueries": [ + "打开天气新闻看板", + "把看板里的城市换成杭州", + "在看板里加一下国际金价" + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/LICENSE b/plugins/lixiangroir-ideal/weather-news-board/LICENSE new file mode 100644 index 00000000..02f85002 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 lixiangroir-ideal + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/lixiangroir-ideal/weather-news-board/README.md b/plugins/lixiangroir-ideal/weather-news-board/README.md new file mode 100644 index 00000000..d35181b4 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/README.md @@ -0,0 +1,70 @@ +# 天气 · 新闻看板 + +A standalone Mini App that shows live weather, A-share and international commodity quotes, and six +switchable news columns in one dashboard page. + +- **实时天气** — current temperature, weather condition, apparent temperature, humidity and wind + speed, plus a three-day forecast with precipitation probability. The city can be typed in Chinese + (for example `南京`); **切换** cycles through the places that share that name. +- **自选股** — a personal watchlist of A-share codes and international symbols (gold, silver, crude + oil, Bitcoin futures, SGE gold 9999). Prices refresh on their own interval, separately from the + weather and news interval. +- **新闻** — six tabs: 要闻, 时政, 科技, 财经, 热榜 (Toutiao hot board) and 知乎日报. + +Precious metals are always shown in **CNY per gram**. The raw USD-per-ounce quote and the FX rate +used for the conversion are kept in the row's tooltip, so the displayed number and the source +figure can be compared. + +## Install and open + +1. Install the plugin in MiniMax Code. +2. Open the **天气 · 新闻看板** Mini App from the plugin entry, or ask the Agent to open it. + +The app needs no configuration, no account, and no build step. Everything it shows is fetched +live from public sources at runtime. + +In the watchlist, add a six-digit A-share code (`600519`), a prefixed code (`sh600519`, `sz000001`, +`bj430047`), or the name of a supported symbol (`黄金`, `伦敦金`, `黄金9999`, `白银`, `原油`, +`比特币`). Codes are validated against a fixed allow list on the server; anything else is +rejected. + +## Tested environment + +- MiniMax Code **3.1.19** on **Windows 11** (Windows 10.0.26200, x64), Node.js 24.16.0. +- Client acceptance exercised: published and opened the Mini App; confirmed the page is not blank + and that landmarks, headings, tabs, and controls are reachable; measured the 640 px layout + (two columns, weather card and watchlist card bottoms aligned at the same y); checked the + >= 900 px three-column layout and the dark theme; added and removed watchlist entries; + switched every news tab; confirmed that one auto-refresh cycle advances the quote timestamp and + the price; reloaded the page and confirmed the watchlist, the selected tab, and the theme + persisted. Console showed 0 errors and 0 warnings; the network showed no failed requests. +- Not verified: the Baidu hot-board fallback and the Sina/Tencent quote fallbacks were exercised + only against their endpoints directly, because the primary sources kept succeeding and the + fallback branches never ran in the live app. +- The package declares no `agentAccess`, `toolAccess`, `deviceAccess`, `hostAccess`, or + `surface.window`, so no minimum client version beyond the base Mini App runtime is required. + +## Data & access + +- **Files read** — `miniapp/client/index.html` from the installed package, served on the assigned + loopback port. +- **Files written** — `watchlist.json` in the Host-provided `context.dataDir`, written atomically + (temporary file plus rename). The directory location is opaque and chosen by the Host. +- **Browser storage** — `localStorage` holds view preferences only: the selected news tab, the two + refresh intervals, the current city, and the light/dark theme. No market or article data is + stored there. +- **Network hosts** (all read-only, outbound HTTPS from the Node service): + `wttr.in`, `geocoding-api.open-meteo.com`, `www.chinanews.com.cn`, `www.ithome.com`, + `sspai.com`, `www.yicai.com`, `www.toutiao.com`, `top.baidu.com`, `news-at.zhihu.com`, + `push2.eastmoney.com`, `hq.sinajs.cn`, `qt.gtimg.cn`. +- **Spawned processes** — none. All upstream calls are made with the Node runtime's own `fetch`. +- **Agent turns** — none. The app never starts an Agent run. +- **Conversations read** — none. +- **Tools called** — none. +- **Microphone, camera, notifications** — not used. +- **Host navigation read** — not used. +- **Declared access** — none beyond the standard Mini App runtime. The manifest declares no + `hostConnectorAccess` provider, no `agentAccess`, no `toolAccess`, no `deviceAccess`, and no + `hostAccess`. + +[简体中文](README.zh-CN.md) diff --git a/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md b/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md new file mode 100644 index 00000000..eaaabe81 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md @@ -0,0 +1,57 @@ +# 天气 · 新闻看板 + +一个独立运行的 Mini App,把实时天气、A 股与国际品种行情、六个可切换的新闻栏目放在同一页看板上。 + +- **实时天气** —— 当前温度、天气状况、体感温度、湿度、风速,以及带降水概率的三天预报。城市可以直接 + 输入中文(例如 `南京`),**切换** 按钮会在同名城市之间轮换。 +- **自选股** —— 自建的自选清单,支持 A 股代码与黄金、白银、原油、比特币期货、上海金 9999 等国际 + 品种。行情按自己的间隔自动刷新,与天气、新闻的刷新开关互相独立。 +- **新闻** —— 六个栏目:要闻、时政、科技、财经、热榜(今日头条)、知乎日报。 + +贵金属一律以**人民币 / 克**显示。原始的美元 / 盎司报价和换算所用汇率放在该行的悬停提示里, +方便和来源数值对照。 + +## 安装与打开 + +1. 在 MiniMax Code 中安装本插件。 +2. 从插件入口打开「天气 · 新闻看板」Mini App,或直接让 Agent 帮你打开。 + +本应用无需任何配置、账号或构建步骤,页面上的一切都是运行时实时抓取的。 + +自选股里可以填六位 A 股代码(`600519`)、带市场前缀的代码(`sh600519`、`sz000001`、`bj430047`), +或者支持的品种名称(`黄金`、`伦敦金`、`黄金9999`、`白银`、`原油`、`比特币`)。代码在服务端按固定 +白名单校验,其他输入一律拒绝。 + +## Tested environment + +- MiniMax Code **3.1.19**,**Windows 11**(Windows 10.0.26200,x64),Node.js 24.16.0。 +- 客户端验收覆盖:发布并打开 Mini App,确认页面非空白、地标、标题、标签页与控件均可访问;实测 + 640 px 布局(两列,天气卡与自选股卡底部精确对齐);检查 ≥ 900 px 三列布局与深色主题;增删 + 自选股;逐个切换新闻栏目;确认一个自动刷新周期后行情时间戳与价格确实跳动;刷新页面后自选股、 + 当前栏目与主题均保持。控制台 0 error / 0 warn,网络无失败请求。 +- 未验证:百度热榜兜底与新浪 / 腾讯行情备源只针对其接口单独做过直连验证,因为主源一直可用, + 运行时并未真正走到兜底分支。 +- 本包未声明 `agentAccess`、`toolAccess`、`deviceAccess`、`hostAccess` 与 `surface.window`, + 因此除基础 Mini App 运行时外没有更高的客户端版本要求。 + +## Data & access + +- **读取的文件** —— 安装包内的 `miniapp/client/index.html`,由分配到的回环端口提供。 +- **写入的文件** —— 宿主注入的 `context.dataDir` 下的 `watchlist.json`,采用「先写临时文件再改名」 + 的原子写法。该目录位置由宿主决定,插件不感知。 +- **浏览器存储** —— `localStorage` 只保存视图偏好:当前新闻栏目、两个刷新间隔、当前城市、浅色 / + 深色主题。不存放任何行情或文章数据。 +- **网络主机**(全部为 Node 侧发起的只读 HTTPS 出站请求):`wttr.in`、 + `geocoding-api.open-meteo.com`、`www.chinanews.com.cn`、`www.ithome.com`、`sspai.com`、 + `www.yicai.com`、`www.toutiao.com`、`top.baidu.com`、`news-at.zhihu.com`、 + `push2.eastmoney.com`、`hq.sinajs.cn`、`qt.gtimg.cn`。 +- **启动的子进程** —— 无。上游请求全部由 Node 运行时的 `fetch` 发出。 +- **Agent 回合** —— 无。本应用从不发起 Agent 运行。 +- **读取的会话** —— 无。 +- **调用的工具** —— 无。 +- **麦克风、摄像头、通知** —— 均未使用。 +- **宿主导航读取** —— 未使用。 +- **声明的访问权限** —— 除标准 Mini App 运行时外没有任何声明:未声明 `hostConnectorAccess` 提供方、 + `agentAccess`、`toolAccess`、`deviceAccess` 与 `hostAccess`。 + +[English](README.md) diff --git a/plugins/lixiangroir-ideal/weather-news-board/icon.png b/plugins/lixiangroir-ideal/weather-news-board/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..299a26cbf5c1427dffa9cd575cf721307d570765 GIT binary patch literal 1574 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H1|$#LC7xzrV7=|>;uumf=gr;N9Fb5F_7BDH zN*t40jx3m@A#jD`h{82~A;W#9hIKB=6V;QM-fp_!Iw3Du_^7z>7spdwD|5UT=(0U- z4vcs42{>&0A!&-l#UFng7Vv9zUfN`Qd~;|s@7+uz9O)JMQ;7Q z+VlNc*1f)P;(=w;neIK@5%Dq?bm#T^{r{9*@ia!gnj^~T2}4Q1*Th_Vu`>}GpIDCO z#4fN@Vt4rd)BClU(Q~fW#@QT3`o97jTK?xMOo;EM)AkEGZ>^la!>4}Tg|#orV!ID- z4G8cmi29Kul*I@Nov(+hUWIHbj*XAkN|#&6e?ev6^ZSxvcK?~yFA_-*H<;a0#(2g^ zzl72KdH~l2CW&?ibaY*)m{GcGsq4HCVQW8`+3MMAA9>%$$6x1gcEXjIh6=|UTHH*2 zPm^w)+0I})`*&FN5&Nu1Y+r6yc*L8(Sa9m$yrfKZ#~fa1&NHPdC8Y+RdyG?WF};29 zt~O0_E62oyX%mAzpJu)CiI9%EV`HT-k0aLM2a{@p^XrK&uP*%0esO=1w)UU=+zCGMvNmy= z|6P>ouW5@p2v)su`cxCfV?$ymt*7pfdX*%ncOdCuPzej4`!;F|NW(R z>9S1?D}6X`#NYh7GVkf}bgjz@`%TThovQS5e3ma}8>P8_foSNz|MS*u5I(ouy{)ZH zDAVlt_qYF?TCQcTsM{ODK6ko9)iJH7$x{Rh??u)A%=k6?)3WE!yQWM!akgaN_W!DX z-#&jmHN3X`^}*WR`-q(SpO3zY`t01fRdCqjHPcc83_B1GbPU2zNIsfpf)(T$7XRi5-O#h75#2n`^6HJMF!qC&lGw+h(&G*h? zk*k_rMVov+YqaeSTOYYZzjSt0F6+COd#ca&eqZ;_rtH&`lb%gyI!#lfHFBb5N}kls z$lZDCNY^>py$dH>z2A9YX;J*2GNpMejVH=I&vYJ{xB2|{X>r$mYq=dibJoiERAfK) zQ9W)K_T5@<--_8kB%7Wkzk0OuD!*pi4Mquhsb5FS-xaZWR zZ|9tq^y-Rf{wEFBD;u8QSW~|%f9dnxxlsofN1ZNZ>HPit!>su-YkBth3z|N4bh|s- zYxS08(KkMRy%ipDKxc+#k7En7+RrklI~Sdmo1bg6`PiN0n#CTy2vIV@izrM+Ju?Ht m|NpbhtN4MXJsYT)XJ&Z(ZtAoneFio_5e83JKbLh*2~7YK=FPVN literal 0 HcmV?d00001 diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html b/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html new file mode 100644 index 00000000..66b322d0 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html @@ -0,0 +1,1702 @@ + + + + + + 天气 · 新闻看板 + + + +
+
+
+

天气 · 新闻看板

+ 正在加载… +
+
+ + + + +
+
+ +
+
+
+
+

实时天气

+
+
+ +
+ + +
+
+
+

正在获取天气…

+
+
+ +
+
+

自选股

+ 更新 --:-- +
+
+
+ + +
+
+ + +
+
+
    +

    支持 A 股代码与黄金、原油等国际品种,非交易时段为最近成交价。

    +
    +
    + +
    +
    +

    新闻

    +
    + 更新于 --/-- --:-- + 加载中 +
    +
    +
    +
      +
      +
      +
      + + + + + + diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/miniapp.json b/plugins/lixiangroir-ideal/weather-news-board/miniapp/miniapp.json new file mode 100644 index 00000000..498d880a --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/miniapp.json @@ -0,0 +1,20 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/dashboard" + }, + "mcpEndpoints": [] +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/miniapp-api.ts b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..5276c6f8 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/miniapp-api.ts @@ -0,0 +1,641 @@ +/** + * Agent-facing Mini App runtime authoring declarations. + * + * Copy this file into a generated plugin for type checking. It contains no Host implementation; + * the Host injects runtime values through start(context). + * Keep the .ts filename: Electron packaging excludes .d.ts files from dependency assets. + */ +export type JsonPrimitive = null | boolean | number | string; +export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[]; +export type JsonObject = { readonly [key: string]: JsonValue }; + +declare const HOST_CONNECTOR_TOOL_REF: unique symbol; +export type HostConnectorToolRef = string & { + readonly [HOST_CONNECTOR_TOOL_REF]: 'HostConnectorToolRef'; +}; + +export interface HostConnectorTool { + readonly toolRef: HostConnectorToolRef; + readonly provider: string; + readonly name: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly outputSchema?: JsonValue; +} + +export interface HostConnectorListResult { + readonly tools: readonly HostConnectorTool[]; + readonly partial: boolean; +} + +export interface HostConnectorCallOptions { + readonly signal?: AbortSignal; +} + +export interface HostConnectorCallResult { + readonly invocationId: string; + /** + * Raw provider result; it is not normalized by the Host and may be an object, array, or primitive. + * A single text-block array is one provider shape, not a global Host transport contract. + * Decode only a probe-observed envelope; preserve every other value, including direct strings. + */ + readonly value: JsonValue; +} + +export interface HostConnectorClient { + /** Candidate-safe inventory only; available before and after activation. */ + list(options?: HostConnectorCallOptions): Promise; + /** Activation-only business dispatch; call from request handling, never start(context). */ + call( + toolRef: HostConnectorToolRef, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; +} + +export type HostConnectorErrorDisposition = + | 'not_dispatched' + | 'provider_reported' + | 'unknown_after_dispatch'; + +export type HostConnectorErrorCode = + | 'TOOL_REF_STALE' + | 'SERVICE_RESTARTED' + | 'REQUEST_CANCELLED' + | 'CONNECTOR_TIMEOUT' + | 'INVALID_ARGUMENTS' + | 'CONNECTOR_PROVIDER_ERROR' + | 'CONNECTOR_UNAVAILABLE' + /** The user switched this provider off for the Mini App; not dispatched. */ + | 'CONNECTOR_NOT_PERMITTED' + | 'CONNECTOR_OUTCOME_UNKNOWN'; + +export interface HostConnectorError extends Error { + readonly code: HostConnectorErrorCode; + readonly disposition: HostConnectorErrorDisposition; + readonly retryable: boolean; + readonly invocationId?: string; + readonly diagnostic?: { + readonly issues: readonly { + readonly path: string; + readonly constraint: string; + readonly limit?: number; + }[]; + }; +} + +/** What a call would meet now under the user's global permission rules; informational only. */ +export type MiniAppToolPermission = 'allow' | 'ask' | 'deny'; + +/** + * `name` is the runtime name an Agent sees (`mcp____`, `connector____`). + * Take it from `list()`; do not build it. + */ +export type MiniAppTool = + | { + readonly name: string; + readonly kind: 'connector'; + readonly provider: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + } + | { + readonly name: string; + readonly kind: 'mcp'; + /** Any installed MCP server: a Plugin's, the user's `mcp.json`, or a Host built-in one. */ + readonly server: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + }; + +export interface MiniAppToolListResult { + readonly tools: readonly MiniAppTool[]; + /** A source could not be listed; the listed tools are still callable. */ + readonly partial: boolean; +} + +export type MiniAppToolCallResult = + | { + readonly invocationId: string; + readonly kind: 'connector'; + /** Raw provider result, as in `HostConnectorCallResult.value`. */ + readonly value: JsonValue; + } + | { + readonly invocationId: string; + readonly kind: 'mcp'; + /** The MCP tool reported its own failure; `content` keeps its error text. */ + readonly isError: boolean; + /** MCP content blocks such as `{ type: 'text', text }`, passed through as JSON. */ + readonly content: readonly JsonValue[]; + readonly structuredContent?: JsonObject; + }; + +/** + * Thrown with the `HostConnectorError` shape; Connector tools keep their Connector codes too. The + * code names the cause; `disposition` alone says whether the tool may have run (`TOOL_TIMEOUT` and + * `REQUEST_CANCELLED` can be either `not_dispatched` or `unknown_after_dispatch`). + */ +export type MiniAppToolErrorCode = + | HostConnectorErrorCode + | 'INVALID_ARGUMENTS' + | 'TOOL_NOT_PERMITTED' + | 'TOOL_APPROVAL_REQUIRED' + | 'TOOL_REF_STALE' + | 'TOOL_UNAVAILABLE' + | 'TOOL_TIMEOUT' + | 'TOOL_RESULT_TOO_LARGE' + | 'TOOL_OUTCOME_UNKNOWN' + | 'MCP_SERVER_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'SERVICE_RESTARTED'; + +/** + * Present whenever the manifest declares `"toolAccess": ["call"]`, even when the user switched + * `tool:call` off: calls then fail with `TOOL_NOT_PERMITTED`. Every `call` is judged by the user's + * global permission rules: `deny` is `TOOL_NOT_PERMITTED`, `ask` shows a Host prompt, and nobody to + * ask is `TOOL_APPROVAL_REQUIRED`. `list` works before activation; call `call` only from request + * handling after activation. Connector tools time out after 30 s and MCP tools after at most 120 s, + * counted after any prompt. The Host never retries; reconcile an `unknown_after_dispatch` outcome + * before repeating a write. + */ +export interface MiniAppToolClient { + list(options?: HostConnectorCallOptions): Promise; + call( + name: string, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; + /** + * One Host prompt for the named tools (1–10, from `list()`) still at `ask`; the user ticks which + * to always allow. Resolves every name's state afterwards (for your UI only). When nobody can be + * asked it rejects with `TOOL_APPROVAL_REQUIRED` whose error carries `permissions`. With + * `tool:call` switched off it answers `deny` for every name without a prompt. + * Needs `capabilities.has('tool.request')`. + */ + request( + names: readonly string[], + options?: HostConnectorCallOptions, + ): Promise>; +} + +export interface MiniAppLogger { + debug(message: string, fields?: JsonObject): void; + info(message: string, fields?: JsonObject): void; + warn(message: string, fields?: JsonObject): void; + error(message: string, fields?: JsonObject): void; +} + +/** + * How the call's text ended: in its own turn (`finished` / `error` / `aborted`), or, only with + * `whenBusy`, joined into the turn that was already running (`steered`; that turn's own + * call gets the reply). + */ +export type MiniAppAgentRunStatus = 'finished' | 'error' | 'aborted' | 'steered'; + +/** + * The Desktop composer's follow-up behaviours while a session runs a turn. `queue`: the text runs + * as the next turn and the call follows it. `steer`: the running turn reads the text at its next + * input point (the call resolves `steered`), or, if it answered first, the text runs as the next + * turn and the call follows it. + */ +export type MiniAppAgentWhenBusy = 'queue' | 'steer'; + +export type MiniAppAgentQuestionMode = 'questionnaire' | 'feature-enable' | 'plan'; + +export interface MiniAppAgentQuestionOption { + readonly id: string; + readonly label: string; + readonly description?: string; +} + +export interface MiniAppAgentQuestionStep { + readonly id: string; + readonly header?: string; + readonly question: string; + readonly description?: string; + readonly selectionMode: 'single' | 'multiple'; + readonly options: readonly MiniAppAgentQuestionOption[]; + /** Free-text "other" is always accepted; see `MiniAppAgentQuestionAnswer.otherText`. */ + readonly allowOther: true; +} + +/** Same questionnaire the Host chat renders; render every step and answer each one. */ +export interface MiniAppAgentQuestionnaire { + readonly schemaVersion: 2; + readonly id: string; + readonly title?: string; + readonly steps: readonly MiniAppAgentQuestionStep[]; + readonly mode?: MiniAppAgentQuestionMode; + /** Plan review Markdown and other mode-specific data. */ + readonly modePayload?: JsonObject; + /** Unix ms; the request is withdrawn after this. */ + readonly expiresAt?: number; +} + +export interface MiniAppAgentQuestionAnswer { + readonly stepId: string; + readonly selectedOptionIds: readonly string[]; + readonly selectedOther: boolean; + readonly otherText?: string; + readonly skipped?: boolean; +} + +/** A model as the Host's composer selects it; take the values from `models()`. */ +export interface MiniAppAgentModelSelection { + readonly providerId: string; + readonly modelId: string; + /** `''` means thinking is off; it is preserved, distinct from an absent `variant`. */ + readonly variant?: string; + readonly thinking?: { readonly effort: string }; +} + +/** One model this user can use. */ +export interface MiniAppAgentModelOption { + readonly providerId: string; + readonly modelId: string; + readonly displayName: string; + readonly variants?: readonly string[]; + readonly thinking?: { readonly efforts: readonly string[]; readonly default?: string }; +} + +export interface MiniAppAgentModels { + readonly models: readonly MiniAppAgentModelOption[]; + /** What a Node-created session starts with. */ + readonly default: MiniAppAgentModelSelection; +} + +export interface MiniAppAgentAgentOption { + /** Canonical name; what `agent` takes. */ + readonly name: string; + readonly displayName: string; + /** The default agent. */ + readonly primary: boolean; +} + +export interface MiniAppAgentAgents { + readonly agents: readonly MiniAppAgentAgentOption[]; +} + +export interface MiniAppAgentRunResult { + /** Pass back in `run({ sessionId })` to continue the same conversation. */ + readonly sessionId: string; + /** Absent when no turn ran: an `answer` accepted without starting a continuation. */ + readonly turnId?: string; + /** The model the turn was dispatched with; absent when no turn ran or the text was steered. */ + readonly model?: MiniAppAgentModelSelection; + /** `aborted` only when the Host confirmed the abort; an unconfirmed one rejects with `AGENT_OUTCOME_UNKNOWN`. */ + readonly status: MiniAppAgentRunStatus; + /** Final assistant reply; absent when the turn produced none or did not finish. */ + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + /** Set when the turn ended waiting on a questionnaire; render `request` and continue with `agent.answer`. */ + readonly pendingQuestion?: { + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + }; +} + +/** + * Progress of one run. `turnId` matches the result's, except that a `permission.requested` raised + * by a delegated child session carries that child's own `sessionId` and `turnId`; `reply` with + * those, and do not filter events by the root turn. Ignore unknown `type` values: new event + * types may be added without notice. + * - `run.queued`: the call waits at 1-based `position`, for a run slot or, with + * `whenBusy: 'queue'`, in the session queue (a `whenBusy` call can get both); sent before the + * turn starts, so it has no `turnId` and names a session only when continuing one. + * - `message.pending` / `message.steered`: with `whenBusy: 'steer'`, the text was handed to the + * running turn, then read by it; `message.steered` is the call's last event. + * - `turn.started`: the Agent began the turn; `model` is the model it was dispatched with. + * - `text.delta`: a piece of the reply as it streams. + * - `message.committed`: one complete assistant message (a turn can have several). + * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. + * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` + * as the run result. + */ +/** + * Every event except `run.queued` names its session, so `reply` can be called from `onEvent` even + * before the `run` that created the session has returned. `answer` cannot: the paused `run` still holds the + * session's single-run slot while `question.requested` is delivered, so call `answer` only after + * that `run` resolves (an earlier call rejects with `BUSY`). Ignore event types you do not know. + */ +export type MiniAppAgentRunEvent = + | { readonly type: 'run.queued'; readonly sessionId?: string; readonly position: number } + | { + readonly type: 'message.pending' | 'message.steered'; + readonly sessionId: string; + readonly turnId: string; + } + | { + readonly type: 'turn.started'; + readonly sessionId: string; + readonly turnId: string; + readonly model: MiniAppAgentModelSelection; + } + | { + readonly type: 'text.delta'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'message.committed'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'tool.started'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + } + | { + readonly type: 'tool.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + readonly ok: boolean; + } + /** A tool call is waiting for approval; decide it with `agent.reply`. */ + | { + readonly type: 'permission.requested'; + readonly sessionId: string; + /** Absent when the runtime did not attribute the ask to a turn. */ + readonly turnId?: string; + readonly requestId: string; + readonly toolName: string; + readonly toolInput?: string; + readonly reason: string; + } + /** The turn paused on a questionnaire; continue with `agent.answer`. */ + | { + readonly type: 'question.requested'; + readonly sessionId: string; + readonly turnId?: string; + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + } + | { + readonly type: 'turn.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly status: Exclude; + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + }; + +/** `observe({ all: true })` only: the conversation's title, when it has one. */ +interface MiniAppAgentObservedTitle { + readonly title?: string; +} + +type MiniAppAgentRunEventOf = Extract< + MiniAppAgentRunEvent, + { readonly type: T } +>; + +/** + * What an observer receives: the run events without `run.queued` and without asks, which reach + * only the run that owns them. `turn.started.model` is present only when the Host could read it. + * Ignore unknown `type` values. + */ +export type MiniAppAgentObservedEvent = + | (Omit, 'model'> & { + readonly model?: MiniAppAgentModelSelection; + } & MiniAppAgentObservedTitle) + | MiniAppAgentRunEventOf<'text.delta' | 'tool.started' | 'tool.finished'> + | (MiniAppAgentRunEventOf<'message.committed'> & MiniAppAgentObservedTitle) + | (MiniAppAgentRunEventOf<'turn.finished'> & MiniAppAgentObservedTitle); + +/** + * `{ all: true }`: `turn.started`, `message.committed` (the final reply) and `turn.finished` of + * every user conversation, with its `title`. `{ sessionId }`: every progress event of that + * session, turn after turn. Exactly one of the two. + */ +export type MiniAppAgentObserveTarget = { readonly sessionId: string } | { readonly all: true }; + +/** One of the user's conversations; `running` while a turn is in flight. */ +export interface MiniAppAgentSessionSummary { + readonly sessionId: string; + readonly title?: string; + /** The Agent the session runs. */ + readonly agent: string; + readonly status: 'idle' | 'running' | 'error' | 'aborted'; + /** The conversation's project directory (absolute) as recorded; it may no longer exist. */ + readonly workspaceDir: string; + /** True when the conversation has no project and runs in the default workspace. */ + readonly isDefaultWorkspace: boolean; + /** Unix ms. */ + readonly createdAtMs: number; + /** Unix ms. */ + readonly updatedAtMs: number; +} + +export interface MiniAppAgentSessionDetail extends MiniAppAgentSessionSummary { + /** The conversation's current model; absent when the Host has none recorded. */ + readonly model?: MiniAppAgentModelSelection; + /** Only while `status` is `error` and the Host recorded a message. */ + readonly error?: { readonly message: string }; + /** Final text of the latest Agent reply, if any. */ + readonly lastAssistantText?: string; +} + +export interface MiniAppAgentSessions { + /** The 50 most recently updated user conversations (no Mini App, scheduled or sub-Agent ones). */ + readonly sessions: readonly MiniAppAgentSessionSummary[]; +} + +export interface MiniAppAgentRunOptions { + readonly signal?: AbortSignal; + readonly onEvent?: (event: MiniAppAgentRunEvent) => void; +} + +export type MiniAppAgentErrorCode = + | 'NOT_PERMITTED' + | 'BUSY' + | 'SESSION_NOT_FOUND' + | 'INVALID_ARGUMENTS' + | 'AGENT_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'AGENT_OUTCOME_UNKNOWN' + | 'REQUEST_NOT_FOUND'; + +export interface MiniAppAgentError extends Error { + readonly code: MiniAppAgentErrorCode; + /** + * True when nothing was started and the same call may be retried later. + * `AGENT_OUTCOME_UNKNOWN` is never retryable: the turn may have run. + */ + readonly retryable: boolean; + /** + * Set on every `BUSY`: the session is running a turn, compacting, or has messages queued ahead + * (the text reached no turn), the wait queue is full, the per-minute start cap was hit, or + * `observe` found 4 observers already running. + */ + readonly reason?: 'session_busy' | 'queue_full' | 'rate_limited' | 'observer_limit'; +} + +/** + * Present when the manifest declares `agentAccess` (`"session.run"` and/or `"session.read"`). + * `run` / `reply` / `answer` / `models` / `agents` / `create` need `session.run`; `observe` and + * `sessions` need `session.read` except for this Mini App's own sessions (see + * agent-interaction.md). + * A new Node session uses the primary Agent unless `agent` names one from `agents()`, and works in + * this Mini App's own Agent directory and on the runtime default model; + * continuing a session keeps its Agent, directory and model (unless `model` switches it), including + * one a page created using its host chat's Agent, project directory and model; a session never + * changes its Agent. Runs one turn with that Agent's full capabilities + * (files, shell, Skills, MCP including this Mini App's own), and resolves when the turn ends. + * + * Interaction is yours to render: pass `onEvent` and handle `permission.requested` with + * `reply` and `question.requested` with `answer`. A permission request waits only while + * someone can answer it: this run passed `onEvent`, or a page of this Mini App currently has + * the session open in a chat side panel via `open`. Otherwise it is denied (the model is told + * why), and a questionnaire ends the turn with `result.pendingQuestion`. A run waiting on a + * permission is released by `cancel`/abort, process exit or republish. Up to `agentConcurrency` + * runs (default 4) per Mini App run at once; further `run` / `answer` calls wait in order (up to + * four times that many, see `run.queued`), and aborting a waiting call rejects it with + * `REQUEST_CANCELLED`. A `whenBusy` call on a session that already has a call in flight shares + * that call's slot. Cancelling a queued `whenBusy` text removes it (`REQUEST_CANCELLED`); a steered + * text cannot be withdrawn (`AGENT_OUTCOME_UNKNOWN`, the running turn goes on). + */ +export interface MiniAppAgentClient { + run( + input: { + readonly text: string; + readonly sessionId?: string; + /** + * Switch the session to this model before the turn (validated like the composer validates a + * new session's model: it must be one `models()` lists; unusable is `INVALID_ARGUMENTS`, + * missing BYOK credentials end the turn with `status: 'error'`); the session keeps it. Omit to use the session's current model. + */ + readonly model?: MiniAppAgentModelSelection; + /** + * Only when starting a session (no `sessionId`): an agent `name` from `agents()`. Passing it + * with `sessionId` is `INVALID_ARGUMENTS`. + */ + readonly agent?: string; + /** + * Only with `sessionId`: what to do when that session is already running a turn; on an idle + * session the call starts a turn as usual. Omit to reject with `BUSY` (`session_busy`). + */ + readonly whenBusy?: MiniAppAgentWhenBusy; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Decide a pending permission request. Never writes the user's global rules. Node replies + * have 16 separate pending slots; `run` / `answer` / `models` / `agents` / `create` and Connector + * requests share another 16. Filling that ordinary budget still permits replies. A full reply + * budget rejects with retryable `AGENT_UNAVAILABLE`. + */ + reply(input: { + readonly sessionId: string; + readonly requestId: string; + readonly decision: 'allowOnce' | 'deny'; + }): Promise; + /** + * Answer a questionnaire; the continuation turn is observed like `run`. Rejects with + * `AGENT_OUTCOME_UNKNOWN` when the answer was recorded but the continuation turn was not observed. + */ + answer( + input: { + readonly sessionId: string; + readonly requestId: string; + readonly answers: readonly MiniAppAgentQuestionAnswer[]; + /** Same as `run`'s `model`, applied before the continuation turn. */ + readonly model?: MiniAppAgentModelSelection; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Returns the model catalog and runtime `default`. Pass `default` directly as `model` to + * `run` / `answer`. For a catalog entry, extract `providerId` / `modelId`, add a selected `variant` + * if needed and preserve `variant: ''`. If thinking is supported, select an effort from + * `thinking.efforts` and pass `thinking: { effort }`. + */ + models(): Promise; + /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + agents(): Promise; + /** + * Create a session (agent, this Mini App's Agent directory, the runtime default model) without + * running a turn, and return its `sessionId`; continue it with `run({ sessionId })`. A page's + * `create` binds the session to its chat instead, and its `sessionId` can be continued here. + * Takes no Host run slot but uses the ordinary Node request budget. `agent` picks the session's + * agent from `agents()`; a session never changes it. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). No request timeout; abort + * `signal` to stop, after which `onEvent` gets nothing more. Resolves when the subscription + * ended: `signal` aborted, the session was deleted, the process is stopping or being replaced, + * or `session.read` was switched off. + * Rejects with a `MiniAppAgentError` when it could not start or failed: `INVALID_ARGUMENTS` (not + * exactly one target), `NOT_PERMITTED`, `SESSION_NOT_FOUND`, retryable `BUSY` past 4 observers + * per Mini App (`reason: 'observer_limit'`) or `AGENT_UNAVAILABLE`. Observers use no run slots + * and no ordinary request budget. Check `context.capabilities?.has('agent.observe')` first. + */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; + /** Check `context.capabilities?.has('agent.sessions')` first. */ + sessions(): Promise; + /** + * One conversation with its model and latest reply. `sessionId` is required: Node serves every + * tab, so it has no current chat; a page passes its chat's id (from its own `session()`). + * Check `context.capabilities?.has('agent.session')`. + */ + session(sessionId: string): Promise; +} + +export interface MiniAppLifecycle { + dispose(): void | Promise; +} + +export interface MiniAppContext { + readonly pluginId: string; + readonly pluginRoot: string; + readonly dataDir: string; + readonly listen: Readonly<{ readonly host: '127.0.0.1'; readonly port: number }>; + readonly signal: AbortSignal; + readonly logger: MiniAppLogger; + /** + * Synchronous probe of Host features, fixed per Host version. It says nothing about this + * Mini App's manifest or authorization: `has('agent.run')` is true on a Host that supports the + * Agent API even when `context.agent` is absent because `agentAccess` was not declared. + * Older Hosts do not inject `capabilities`; check `context.capabilities?.has(...)`. + */ + readonly capabilities?: MiniAppHostCapabilities; + /** + * Present when the manifest declares a `hostConnectorAccess` provider; a provider the user + * switched off is missing from `list()` and its calls fail with `CONNECTOR_NOT_PERMITTED`. + */ + readonly hostConnector?: HostConnectorClient; + /** Installed MCP and Connector tools, each call judged by the user's permission rules. */ + readonly tool?: MiniAppToolClient; + /** + * Present when the manifest declares `agentAccess: ["session.run"]`; while the user has it + * switched off, calls fail with `NOT_PERMITTED`. + */ + readonly agent?: MiniAppAgentClient; +} + +export interface MiniAppHostCapabilities { + has(name: string): boolean; +} + +export interface MiniAppModule { + /** Resolve only after the listener accepts connections and every route is installed. */ + start(context: MiniAppContext): Promise; +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/server.mjs b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/server.mjs new file mode 100644 index 00000000..0139dc25 --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/node/server.mjs @@ -0,0 +1,1324 @@ +// @ts-check + +/** + * 天气 · 新闻看板 —— Mini App Node 运行时 + * + * 职责: + * - 聚合天气、6 个新闻栏目、自选股行情(A股 + 国际品种) + * - 自选股持久化到 context.dataDir(原子写) + * - 只暴露白名单路由;所有外部取数都在 Node 侧完成 + */ + +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { join } from 'node:path'; + +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ +/** @typedef {import('./miniapp-api.js').MiniAppLifecycle} MiniAppLifecycle */ + +const USER_AGENT = + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'; + +const UPSTREAM_TIMEOUT = 15000; +const QUOTE_TTL = 15_000; +const CONTENT_TTL = 60_000; +const FX_TTL = 30_000; +const MAX_WATCHLIST = 12; +const MAX_BODY_BYTES = 4096; +const GRAMS_PER_OUNCE = 31.1034768; + +/* ------------------------------------------------------------------ * + * 通用取数工具 + * ------------------------------------------------------------------ */ + +/** + * @param {string} url + * @param {{headers?: Record, encoding?: string, timeout?: number}} [options] + * @returns {Promise} + */ +async function httpText(url, options = {}) { + const response = await fetch(url, { + headers: { 'user-agent': USER_AGENT, accept: '*/*', ...(options.headers ?? {}) }, + redirect: 'follow', + signal: AbortSignal.timeout(options.timeout ?? UPSTREAM_TIMEOUT), + }); + if (!response.ok) throw new Error(`upstream_status_${response.status}`); + const buffer = await response.arrayBuffer(); + return new TextDecoder(options.encoding ?? 'utf-8').decode(buffer); +} + +/** + * @param {string} url + * @param {{headers?: Record, timeout?: number}} [options] + * @returns {Promise} + */ +async function httpJson(url, options = {}) { + const text = await httpText(url, options); + try { + return JSON.parse(text); + } catch { + throw new Error('invalid_json'); + } +} + +/* ------------------------------------------------------------------ * + * 文本清洗 + * ------------------------------------------------------------------ */ + +const NAMED_ENTITIES = { + amp: '&', + lt: '<', + gt: '>', + quot: '"', + apos: "'", + nbsp: ' ', + ldquo: '“', + rdquo: '”', + lsquo: '‘', + rsquo: '’', + mdash: '—', + ndash: '–', + hellip: '…', + middot: '·', + times: '×', + copy: '©', +}; + +/** + * @param {string} value + * @returns {string} + */ +function decodeEntities(value) { + return value.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g, (match, entity) => { + if (entity.charCodeAt(0) === 35) { + const isHex = entity[1] === 'x' || entity[1] === 'X'; + const code = Number.parseInt(isHex ? entity.slice(2) : entity.slice(1), isHex ? 16 : 10); + if (!Number.isFinite(code) || code < 0 || code > 0x10ffff) return match; + try { + return String.fromCodePoint(code); + } catch { + return match; + } + } + const mapped = NAMED_ENTITIES[entity.toLowerCase()]; + return mapped === undefined ? match : mapped; + }); +} + +/** + * 去标签、解实体、压空白、截断。 + * @param {string} value + * @param {number} [limit] + * @returns {string} + */ +function cleanText(value, limit = 120) { + if (!value) return ''; + const plain = decodeEntities(String(value)) + .replace(//gi, ' ') + .replace(//gi, ' ') + .replace(/<[^>]*>/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + if (plain.length <= limit) return plain; + return `${plain.slice(0, limit).replace(/[\s,.;:!?,。、;:!?]+$/u, '')}…`; +} + +/** + * @param {string} body + * @param {string} tag + * @returns {string} + */ +function pickTag(body, tag) { + const match = body.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${tag}>`, 'i')); + if (!match) return ''; + let value = match[1].trim(); + const cdata = value.match(/^$/); + if (cdata) value = cdata[1]; + return value.trim(); +} + +/** + * @param {string} body + * @returns {string} + */ +function pickLink(body) { + const text = pickTag(body, 'link'); + if (/^https?:\/\//i.test(text)) return text; + const href = body.match(/]*\bhref=["']([^"']+)["'][^>]*>/i); + if (href) return href[1]; + const guid = pickTag(body, 'guid'); + return /^https?:\/\//i.test(guid) ? guid : ''; +} + +/** + * 解析 RSS 2.0 / Atom 条目。 + * @param {string} xml + * @param {string} sourceName + */ +function parseFeed(xml, sourceName) { + /** @type {Array<{title:string, description:string, url:string, source:string, publishedAt:string|null}>} */ + const items = []; + const pattern = /<(item|entry)\b[^>]*>([\s\S]*?)<\/\1>/gi; + let match; + while ((match = pattern.exec(xml)) !== null) { + const body = match[2]; + const title = cleanText(pickTag(body, 'title'), 90); + if (!title) continue; + const published = + pickTag(body, 'pubDate') || + pickTag(body, 'published') || + pickTag(body, 'updated') || + pickTag(body, 'dc:date'); + items.push({ + title, + description: cleanText( + pickTag(body, 'description') || pickTag(body, 'content:encoded') || pickTag(body, 'summary'), + 110, + ), + url: pickLink(body), + source: sourceName, + publishedAt: published ? toIso(published) : null, + }); + } + return items; +} + +/** + * 把 RSS / 中文相对时间转成 ISO 字符串,无法解析返回 null。 + * @param {string} raw + * @returns {string|null} + */ +function toIso(raw) { + const value = String(raw || '').trim(); + if (!value) return null; + const now = Date.now(); + const minute = /^(\d+)\s*分钟前$/.exec(value); + if (minute) return new Date(now - Number(minute[1]) * 60_000).toISOString(); + const hour = /^(\d+)\s*小时前$/.exec(value); + if (hour) return new Date(now - Number(hour[1]) * 3_600_000).toISOString(); + const yesterday = /^昨天\s*(\d{1,2}):(\d{2})$/.exec(value); + if (yesterday) { + const date = new Date(now); + date.setDate(date.getDate() - 1); + date.setHours(Number(yesterday[1]), Number(yesterday[2]), 0, 0); + return date.toISOString(); + } + const monthDay = /^(\d{2})-(\d{2})\s+(\d{1,2}):(\d{2})$/.exec(value); + if (monthDay) { + const date = new Date(now); + date.setMonth(Number(monthDay[1]) - 1, Number(monthDay[2])); + date.setHours(Number(monthDay[3]), Number(monthDay[4]), 0, 0); + if (date.getTime() > now + 86_400_000) date.setFullYear(date.getFullYear() - 1); + return date.toISOString(); + } + const parsed = Date.parse(value); + if (Number.isFinite(parsed)) return new Date(parsed).toISOString(); + return null; +} + +/* ------------------------------------------------------------------ * + * 天气 + * ------------------------------------------------------------------ */ + +/** WWO 天气码 → 中文描述 + 图标键 */ +const WEATHER_META = { + 113: ['晴', 'sun'], + 116: ['局部多云', 'partly'], + 119: ['多云', 'cloud'], + 122: ['阴', 'overcast'], + 143: ['薄雾', 'fog'], + 149: ['烟霾', 'haze'], + 176: ['局部有雨', 'rain'], + 179: ['吹雪', 'snow'], + 182: ['暴雪', 'snow'], + 185: ['冻雾', 'fog'], + 200: ['雷阵雨', 'thunder'], + 227: ['大风', 'wind'], + 248: ['冻毛毛雨', 'rain'], + 263: ['局部毛毛雨', 'drizzle'], + 266: ['毛毛雨', 'drizzle'], + 281: ['冻雨', 'rain'], + 284: ['强冻毛毛雨', 'rain'], + 293: ['局部小雨', 'rain'], + 296: ['小雨', 'rain'], + 299: ['中雨', 'rain'], + 302: ['中雨', 'rain'], + 305: ['阵雨', 'rain'], + 308: ['大雨', 'rain'], + 311: ['轻冻雨', 'rain'], + 314: ['强冻雨', 'rain'], + 317: ['轻雨夹雪', 'sleet'], + 320: ['强雨夹雪', 'sleet'], + 323: ['局部小雪', 'snow'], + 326: ['小雪', 'snow'], + 329: ['局部中雪', 'snow'], + 332: ['中雪', 'snow'], + 335: ['局部大雪', 'snow'], + 338: ['大雪', 'snow'], + 350: ['冰粒', 'sleet'], + 353: ['小阵雨', 'rain'], + 356: ['强阵雨', 'rain'], + 359: ['暴雨', 'rain'], + 362: ['轻阵性雨夹雪', 'sleet'], + 365: ['强阵性雨夹雪', 'sleet'], + 368: ['小阵雪', 'snow'], + 371: ['强阵雪', 'snow'], + 374: ['阵性冰粒', 'sleet'], + 377: ['强阵性冰粒', 'sleet'], + 386: ['阵雨伴雪', 'sleet'], + 389: ['强阵雨伴雪', 'sleet'], +}; + +/** + * @param {number|string} code + * @returns {{desc:string, icon:string}} + */ +function weatherMeta(code) { + const key = Number(code); + const entry = WEATHER_META[key]; + return entry ? { desc: entry[0], icon: entry[1] } : { desc: '未知', icon: 'cloud' }; +} + +/** + * @param {string} cityName + */ +async function geocodeCity(cityName) { + const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent( + cityName, + )}&count=8&language=zh&format=json`; + const json = await httpJson(url); + const results = Array.isArray(json?.results) ? json.results : []; + return results.map((item) => ({ + id: String(item.id ?? ''), + name: String(item.name ?? ''), + admin1: String(item.admin1 ?? ''), + country: String(item.country ?? ''), + latitude: Number(item.latitude), + longitude: Number(item.longitude), + })); +} + +/** + * @param {{latitude:number, longitude:number}} candidate + */ +async function fetchWeatherAt(candidate) { + const url = `https://wttr.in/${candidate.latitude},${candidate.longitude}?format=j1`; + const json = await httpJson(url, { timeout: 20_000 }); + const current = json?.current_condition?.[0]; + const area = json?.nearest_area?.[0]; + const days = Array.isArray(json?.weather) ? json.weather : []; + if (!current || days.length === 0) throw new Error('weather_shape'); + + const meta = weatherMeta(current.weatherCode); + const utcHour = new Date().getUTCHours(); + const localHour = (utcHour + Math.round(candidate.longitude / 15) + 24) % 24; + + const forecast = days.slice(0, 3).map((day, index) => { + const hourly = Array.isArray(day.hourly) ? day.hourly : []; + const slots = index === 0 ? hourly.filter((slot) => Number(slot.time) / 100 >= localHour) : hourly; + const pool = slots.length ? slots : hourly; + const probability = pool.reduce((max, slot) => Math.max(max, Number(slot.chanceofrain) || 0), 0); + const mid = hourly[Math.floor(hourly.length / 2)] ?? hourly[0] ?? {}; + const dayMeta = weatherMeta(mid.weatherCode ?? current.weatherCode); + return { + date: String(day.date ?? ''), + label: index === 0 ? '今天' : index === 1 ? '明天' : '后天', + high: Number(day.maxtempC ?? 0), + low: Number(day.mintempC ?? 0), + probability, + desc: dayMeta.desc, + icon: dayMeta.icon, + }; + }); + + return { + // 优先用中文地名(open-meteo geocoding language=zh),再退回 wttr.in 的英文地名。 + city: candidate.name || String(area?.areaName?.[0]?.value ?? ''), + region: candidate.admin1 || String(area?.region?.[0]?.value ?? ''), + country: candidate.country || String(area?.country?.[0]?.value ?? ''), + latitude: candidate.latitude, + longitude: candidate.longitude, + current: { + temp: Number(current.temp_C ?? 0), + feels: Number(current.FeelsLikeC ?? 0), + humidity: Number(current.humidity ?? 0), + windSpeed: Number(current.windspeedKmph ?? 0), + precipitation: Number(current.precipMM ?? 0), + desc: meta.desc, + icon: meta.icon, + observationTime: String(current.observation_time ?? ''), + }, + forecast, + }; +} + +/** + * @param {string} cityName + * @param {number} pick + * @param {boolean} refresh + */ +async function loadWeather(cityName, pick, refresh) { + const key = cityName || '南京'; + const cached = contentCache.get(`weather:${key}`); + if (!refresh && cached && Date.now() - cached.at < CONTENT_TTL) { + const candidates = cached.value.candidates ?? []; + const index = Math.min(Math.max(pick, 0), Math.max(candidates.length - 1, 0)); + const selected = candidates[index]; + if (selected) return { ...cached.value.data, candidates, index }; + } + + const candidates = await geocodeCity(key); + if (candidates.length === 0) throw new Error('city_not_found'); + const index = Math.min(Math.max(pick, 0), candidates.length - 1); + const selected = candidates[index]; + const data = await fetchWeatherAt(selected); + contentCache.set(`weather:${key}`, { + at: Date.now(), + value: { query: key, candidates, data }, + }); + lastGoodWeather = { candidates, data }; + return { ...data, candidates, index }; +} + +/* ------------------------------------------------------------------ * + * 新闻栏目 + * ------------------------------------------------------------------ */ + +const NEWS_DEFINITIONS = { + headlines: { label: '要闻', feeds: [{ url: 'https://www.chinanews.com.cn/rss/importnews.xml', name: '中新网' }] }, + politics: { label: '时政', feeds: [{ url: 'https://www.chinanews.com.cn/rss/china.xml', name: '中新网' }] }, + tech: { + label: '科技', + feeds: [ + { url: 'https://www.ithome.com/rss/', name: 'IT之家' }, + { url: 'https://sspai.com/feed', name: '少数派' }, + ], + }, + finance: { label: '财经', yicaiCids: [54, 53] }, + hot: { label: '热榜' }, + stories: { label: '知乎日报' }, +}; + +/** + * @param {string} url + * @param {string} sourceName + */ +async function fetchFeed(url, sourceName) { + const xml = await httpText(url); + return parseFeed(xml, sourceName); +} + +/** + * 科技栏目:两个源合并去重,交替穿插。 + * @returns {Promise} + */ +async function fetchTech() { + const [ithome, sspai] = await Promise.allSettled([ + fetchFeed('https://www.ithome.com/rss/', 'IT之家'), + fetchFeed('https://sspai.com/feed', '少数派'), + ]); + const lists = [ithome.status === 'fulfilled' ? ithome.value : [], sspai.status === 'fulfilled' ? sspai.value : []]; + const seen = new Set(); + const merged = []; + const max = Math.max(lists[0]?.length ?? 0, lists[1]?.length ?? 0); + for (let index = 0; index < max; index += 1) { + for (const list of lists) { + const item = list[index]; + if (!item || seen.has(item.title)) continue; + seen.add(item.title); + merged.push(item); + } + } + if (merged.length === 0) throw new Error('tech_empty'); + return merged; +} + +/** + * @param {number} cid + */ +async function fetchYicai(cid) { + const url = `https://www.yicai.com/api/ajax/getlistbycid?cid=${cid}&page=1&pagesize=12`; + const json = await httpJson(url, { headers: { referer: 'https://www.yicai.com/' } }); + const list = Array.isArray(json) ? json : Array.isArray(json?.data) ? json.data : []; + return list + .map((item) => { + const link = String(item.ShareUrl ?? ''); + const relative = String(item.url ?? ''); + return { + title: cleanText(String(item.NewsTitle ?? ''), 90), + description: cleanText(String(item.NewsNotes ?? ''), 110), + url: link || (relative ? `https://www.yicai.com${relative}` : ''), + source: '第一财经', + publishedAt: toIso(String(item.pubDate ?? '')), + publishedLabel: String(item.pubDate ?? ''), + }; + }) + .filter((item) => item.title); +} + +/** + * 热榜:今日头条为主,百度兜底。 + */ +async function fetchHotBoard() { + try { + const json = await httpJson('https://www.toutiao.com/hot-event/hot-board/?origin=toutiao_pc', { + headers: { referer: 'https://www.toutiao.com/' }, + }); + const data = Array.isArray(json?.data) ? json.data : []; + const items = data + .map((item, index) => ({ + rank: index + 1, + title: cleanText(String(item.Title ?? ''), 80), + score: Number(item.HotValue) || 0, + url: item.ClusterIdStr ? `https://www.toutiao.com/trending/${String(item.ClusterIdStr)}/` : String(item.Url ?? ''), + category: String(item.InterestCategory ?? ''), + })) + .filter((item) => item.title); + if (items.length === 0) throw new Error('toutiao_empty'); + return { sourceName: '今日头条', items }; + } catch (error) { + const json = await httpJson('https://top.baidu.com/api/board?platform=pc&tab=realtime', { + headers: { referer: 'https://top.baidu.com/board?tab=realtime' }, + }); + const content = json?.data?.cards?.[0]?.content; + const list = Array.isArray(content) ? content : []; + const items = list + .map((item, index) => ({ + rank: index + 1, + title: cleanText(String(item.query ?? item.word ?? ''), 80), + score: Number(item.hotScore) || 0, + url: String(item.rawUrl ?? item.url ?? ''), + category: String(item.hotTag ?? ''), + })) + .filter((item) => item.title); + if (items.length === 0) throw new Error('hot_empty'); + return { sourceName: '百度', items }; + } +} + +/** + * @returns {Promise} + */ +async function fetchZhihuStories() { + const json = await httpJson('https://news-at.zhihu.com/api/4/news/latest'); + const stories = [ + ...(Array.isArray(json?.stories) ? json.stories : []), + ...(Array.isArray(json?.top_stories) ? json.top_stories : []), + ]; + const seen = new Set(); + const items = []; + for (const story of stories) { + const id = String(story.id ?? story.url ?? ''); + if (!id || seen.has(id)) continue; + seen.add(id); + items.push({ + title: cleanText(String(story.title ?? ''), 90), + description: cleanText(String(story.hint ?? ''), 110), + url: String(story.url ?? ''), + source: '知乎日报', + publishedAt: null, + }); + } + if (items.length === 0) throw new Error('zhihu_empty'); + return items; +} + +/** + * @param {string} key + */ +async function loadNews(key) { + const definition = NEWS_DEFINITIONS[key]; + if (!definition) throw new Error('unknown_source'); + const cached = contentCache.get(`news:${key}`); + if (cached && Date.now() - cached.at < CONTENT_TTL) return cached.value; + + /** @type {{sourceName:string, items:any[], status:string, updatedAt?:string}} */ + let result; + if (key === 'hot') { + const hot = await fetchHotBoard(); + result = { sourceName: hot.sourceName, items: hot.items, status: 'ok' }; + } else if (key === 'stories') { + result = { sourceName: '知乎日报', items: await fetchZhihuStories(), status: 'ok' }; + } else if (key === 'tech') { + result = { sourceName: 'IT之家 · 少数派', items: await fetchTech(), status: 'ok' }; + } else if (key === 'finance') { + const groups = await Promise.allSettled(definition.yicaiCids.map((cid) => fetchYicai(cid))); + const items = []; + const seen = new Set(); + for (const group of groups) { + if (group.status !== 'fulfilled') continue; + for (const item of group.value) { + if (seen.has(item.title)) continue; + seen.add(item.title); + items.push(item); + } + } + if (items.length === 0) throw new Error('finance_empty'); + result = { sourceName: '第一财经', items, status: 'ok' }; + } else { + const feeds = definition.feeds ?? []; + const groups = await Promise.allSettled(feeds.map((feed) => fetchFeed(feed.url, feed.name))); + const items = []; + const seen = new Set(); + for (const group of groups) { + if (group.status !== 'fulfilled') continue; + for (const item of group.value) { + if (seen.has(item.title)) continue; + seen.add(item.title); + items.push(item); + } + } + if (items.length === 0) throw new Error('feed_empty'); + result = { sourceName: feeds.map((feed) => feed.name).join(' · '), items, status: 'ok' }; + } + + result.updatedAt = new Date().toISOString(); + contentCache.set(`news:${key}`, { at: Date.now(), value: result }); + return result; +} + +/* ------------------------------------------------------------------ * + * 行情 + * ------------------------------------------------------------------ */ + +const STOCK_FIELDS = 'f43,f44,f45,f46,f47,f48,f57,f58,f59,f60,f86,f169,f170'; + +/** + * 预定义国际品种。aliases 用于中文输入匹配(大小写不敏感)。 + * @type {Record} + */ +const COMMODITY_SPECS = { + XAU: { + code: 'XAU', + name: '伦敦金', + unit: '元/克', + kind: 'metal', + hf: 'hf_XAU', + aliases: ['黄金', '金价', '伦敦金', '现货黄金', '国际金价', 'xau', 'gold'], + }, + XAG: { + code: 'XAG', + name: '伦敦银', + unit: '元/克', + kind: 'metal', + hf: 'hf_XAG', + aliases: ['白银', '银价', '伦敦银', '现货白银', 'xag', 'silver'], + }, + GC: { + code: 'GC', + name: '纽约黄金', + unit: '元/克', + kind: 'metal', + hf: 'hf_GC', + aliases: ['纽约黄金', '纽约金', 'comex黄金', 'gc'], + }, + SI: { + code: 'SI', + name: '纽约白银', + unit: '元/克', + kind: 'metal', + hf: 'hf_SI', + aliases: ['纽约白银', 'comex白银', 'si'], + }, + CL: { + code: 'CL', + name: '纽约原油', + unit: '美元/桶', + kind: 'oil', + hf: 'hf_CL', + aliases: ['原油', '石油', '国际原油', '纽约原油', 'crude', 'cl', 'oil'], + }, + BTC: { + code: 'BTC', + name: '比特币期货', + unit: '美元', + kind: 'crypto', + hf: 'hf_BTC', + aliases: ['比特币', '比特币期货', 'btc', 'bitcoin'], + }, + AU9999: { + code: 'AU9999', + name: '黄金9999', + unit: '元/克', + kind: 'native', + em: '118.Au9999', + decimals: 2, + aliases: ['黄金9999', '沪金', '9999', 'au9999', '黄金9999克'], + }, +}; + +/** + * 6 位数字 → 市场前缀。 + * @param {string} digits + * @returns {string} + */ +function marketOf(digits) { + const head = digits.charAt(0); + if (head === '6' || head === '9') return 'sh'; + if (head === '0' || head === '2' || head === '3') return 'sz'; + if (head === '4' || head === '8') return 'bj'; + return 'sh'; +} + +/** + * @param {string} code + * @returns {string} + */ +function secidOf(code) { + const market = code.slice(0, 2); + const digits = code.slice(2); + const prefix = market === 'sh' ? '1.' : '0.'; + return `${prefix}${digits}`; +} + +/** + * 输入白名单解析:6 位数字 / sh|sz|bj 前缀 / 品种别名。 + * @param {string} raw + * @returns {{code:string, kind:'stock'|'commodity'}|null} + */ +function resolveInput(raw) { + const value = String(raw ?? '').trim(); + if (!value || value.length > 32) return null; + const compact = value.replace(/\s+/g, ''); + const lower = compact.toLowerCase(); + + for (const spec of Object.values(COMMODITY_SPECS)) { + if (spec.code.toLowerCase() === lower) return { code: spec.code, kind: 'commodity' }; + if (spec.aliases.some((alias) => alias.toLowerCase() === lower)) { + return { code: spec.code, kind: 'commodity' }; + } + } + + const prefixed = /^(sh|sz|bj)([0-9]{6})$/.exec(lower); + if (prefixed) return { code: `${prefixed[1]}${prefixed[2]}`, kind: 'stock' }; + + if (/^[0-9]{6}$/.test(compact)) { + return { code: `${marketOf(compact)}${compact}`, kind: 'stock' }; + } + return null; +} + +/** + * @param {string} secid + */ +async function fetchEastmoneyQuote(secid) { + const url = `https://push2.eastmoney.com/api/qt/stock/get?ut=fa5fd1943c7b386f172d6893dbfba10b&invt=2&fields=${STOCK_FIELDS}&secid=${secid}`; + const json = await httpJson(url); + const data = json?.data; + if (!data || typeof data.f43 !== 'number' || data.f43 === 0) throw new Error('empty_quote'); + const factor = 10 ** (data.f59 || 2); + return { + name: String(data.f58 ?? ''), + code: String(data.f57 ?? ''), + price: data.f43 / factor, + prevClose: Number(data.f60 ?? 0) / factor, + change: Number(data.f169 ?? 0) / factor, + changePercent: Number(data.f170 ?? 0) / factor, + high: Number(data.f44 ?? 0) / factor, + low: Number(data.f45 ?? 0) / factor, + open: Number(data.f46 ?? 0) / factor, + volume: Number(data.f47 ?? 0), + amount: Number(data.f48 ?? 0), + updatedAt: data.f86 ? new Date(data.f86 * 1000).toISOString() : null, + provider: '东方财富', + }; +} + +/** + * 新浪 A 股备源(GBK + Referer)。 + * @param {string} code + */ +async function fetchSinaStock(code) { + const text = await httpText(`https://hq.sinajs.cn/list=${code}`, { + encoding: 'gbk', + headers: { referer: 'https://finance.sina.com.cn/' }, + }); + const match = text.match(/="([^"]*)"/); + const fields = match ? match[1].split(',') : []; + if (fields.length < 32) throw new Error('empty_quote'); + const price = Number(fields[3]); + const prevClose = Number(fields[2]); + if (!Number.isFinite(price) || price === 0) throw new Error('empty_quote'); + const date = fields[30] ?? ''; + const time = fields[31] ?? ''; + return { + name: String(fields[0] ?? ''), + code: code.slice(2), + price, + prevClose, + change: price - prevClose, + changePercent: prevClose ? ((price - prevClose) / prevClose) * 100 : 0, + high: Number(fields[4] ?? 0), + low: Number(fields[5] ?? 0), + open: Number(fields[1] ?? 0), + volume: Number(fields[8] ?? 0), + amount: Number(fields[9] ?? 0), + updatedAt: date && time ? new Date(`${date}T${time}:00+08:00`).toISOString() : null, + provider: '新浪财经', + }; +} + +/** + * 腾讯 A 股备源(GBK,无需 Referer)。时间字段用 14 位数字锚点定位。 + * @param {string} code + */ +async function fetchTencentStock(code) { + const text = await httpText(`https://qt.gtimg.cn/q=${code}`, { encoding: 'gbk' }); + const match = text.match(/="([^"]*)"/); + const fields = match ? match[1].split('~') : []; + if (fields.length < 32) throw new Error('empty_quote'); + const price = Number(fields[3]); + const prevClose = Number(fields[4]); + if (!Number.isFinite(price) || price === 0) throw new Error('empty_quote'); + const anchor = fields.findIndex((value) => /^\d{14}$/.test(value)); + const change = anchor > 0 ? Number(fields[anchor + 1]) : price - prevClose; + const changePercent = anchor > 0 ? Number(fields[anchor + 2]) : prevClose ? ((price - prevClose) / prevClose) * 100 : 0; + const stamp = anchor > 0 ? fields[anchor] : ''; + const updatedAt = stamp + ? new Date( + `${stamp.slice(0, 4)}-${stamp.slice(4, 6)}-${stamp.slice(6, 8)}T${stamp.slice(8, 10)}:${stamp.slice( + 10, + 12, + )}:${stamp.slice(12, 14)}+08:00`, + ).toISOString() + : null; + return { + name: String(fields[1] ?? ''), + code: String(fields[2] ?? ''), + price, + prevClose, + change: Number.isFinite(change) ? change : 0, + changePercent: Number.isFinite(changePercent) ? changePercent : 0, + high: anchor > 0 ? Number(fields[anchor + 3]) : 0, + low: anchor > 0 ? Number(fields[anchor + 4]) : 0, + open: Number(fields[5] ?? 0), + volume: 0, + amount: 0, + updatedAt, + provider: '腾讯财经', + }; +} + +/** + * 新浪国际品种主源(GBK + Referer)。 + * @param {string} hfCode + */ +async function fetchSinaCommodity(hfCode) { + const text = await httpText(`https://hq.sinajs.cn/list=${hfCode}`, { + encoding: 'gbk', + headers: { referer: 'https://finance.sina.com.cn/' }, + }); + const match = text.match(/="([^"]*)"/); + const fields = match ? match[1].split(',') : []; + if (fields.length < 14) throw new Error('empty_quote'); + const price = Number(fields[0]); + const prevClose = Number(fields[7]); + if (!Number.isFinite(price) || price === 0) throw new Error('empty_quote'); + return { + name: String(fields[13] ?? ''), + price, + prevClose, + change: price - prevClose, + changePercent: prevClose ? ((price - prevClose) / prevClose) * 100 : 0, + high: Number(fields[4] ?? 0), + low: Number(fields[5] ?? 0), + open: Number(fields[8] ?? 0), + updatedAt: fields[12] && fields[6] ? `${fields[12]}T${fields[6]}+08:00` : null, + provider: '新浪财经', + }; +} + +/** + * 腾讯国际品种备源。 + * @param {string} hfCode + */ +async function fetchTencentCommodity(hfCode) { + const text = await httpText(`https://qt.gtimg.cn/q=${hfCode}`, { encoding: 'gbk' }); + const match = text.match(/="([^"]*)"/); + const fields = match ? match[1].split(',') : []; + if (fields.length < 14) throw new Error('empty_quote'); + const price = Number(fields[0]); + const prevClose = Number(fields[7]); + if (!Number.isFinite(price) || price === 0) throw new Error('empty_quote'); + return { + name: String(fields[13] ?? ''), + price, + prevClose, + change: price - prevClose, + changePercent: prevClose ? ((price - prevClose) / prevClose) * 100 : 0, + high: Number(fields[4] ?? 0), + low: Number(fields[5] ?? 0), + open: Number(fields[8] ?? 0), + updatedAt: fields[12] && fields[6] ? `${fields[12]}T${fields[6]}+08:00` : null, + provider: '腾讯财经', + }; +} + +/** + * 美元兑人民币汇率。 + * @param {boolean} refresh + */ +async function loadFxRate(refresh) { + const cached = contentCache.get('fx'); + if (!refresh && cached && Date.now() - cached.at < FX_TTL) return cached.value; + try { + const quote = await fetchEastmoneyQuote('133.USDCNH'); + if (quote.price > 3 && quote.price < 10) { + const value = { rate: quote.price, label: '美元兑离岸人民币', provider: '东方财富' }; + contentCache.set('fx', { at: Date.now(), value }); + return value; + } + throw new Error('fx_range'); + } catch (error) { + const text = await httpText('https://hq.sinajs.cn/list=fx_susdcny', { + encoding: 'gbk', + headers: { referer: 'https://finance.sina.com.cn/' }, + }); + const match = text.match(/="([^"]*)"/); + const fields = match ? match[1].split(',') : []; + const rate = Number(fields[1]); + if (!Number.isFinite(rate) || rate <= 3 || rate >= 10) throw new Error('fx_unavailable'); + const value = { rate, label: '美元兑人民币', provider: '新浪财经' }; + contentCache.set('fx', { at: Date.now(), value }); + return value; + } +} + +/** + * A 股行情:东财主源,新浪 / 腾讯备源。 + * @param {string} code + */ +async function fetchStockQuote(code) { + let quote; + try { + quote = await fetchEastmoneyQuote(secidOf(code)); + } catch (error) { + try { + quote = await fetchSinaStock(code); + } catch (secondError) { + quote = await fetchTencentStock(code); + } + } + // 保留自选股里的规范代码(如 sh600519),供应商原始代码放在 symbol。 + return { ...quote, symbol: quote.code, code }; +} + +/** + * 国际品种行情。贵金属统一折算为人民币/克。 + * @param {string} code + */ +async function fetchCommodityQuote(code) { + const spec = COMMODITY_SPECS[code]; + let raw; + if (spec.em) { + raw = await fetchEastmoneyQuote(spec.em); + } else { + try { + raw = await fetchSinaCommodity(spec.hf); + } catch (error) { + raw = await fetchTencentCommodity(spec.hf); + } + } + + if (spec.kind === 'metal') { + const fx = await loadFxRate(false); + const gramPrice = (raw.price * fx.rate) / GRAMS_PER_OUNCE; + const gramPrev = (raw.prevClose * fx.rate) / GRAMS_PER_OUNCE; + return { + code, + name: spec.name, + price: gramPrice, + prevClose: gramPrev, + change: gramPrice - gramPrev, + changePercent: raw.prevClose ? ((raw.price - raw.prevClose) / raw.prevClose) * 100 : 0, + high: (raw.high * fx.rate) / GRAMS_PER_OUNCE, + low: (raw.low * fx.rate) / GRAMS_PER_OUNCE, + unit: spec.unit, + decimals: 2, + updatedAt: raw.updatedAt, + provider: raw.provider, + title: `原始报价 ${raw.price} 美元/盎司(昨收 ${raw.prevClose})|汇率 ${fx.rate}(${fx.label})|${raw.provider}`, + }; + } + + return { + code, + name: spec.name, + price: raw.price, + prevClose: raw.prevClose, + change: raw.change, + changePercent: raw.changePercent, + high: raw.high, + low: raw.low, + unit: spec.unit, + decimals: spec.decimals ?? 2, + updatedAt: raw.updatedAt, + provider: raw.provider, + title: spec.kind === 'native' ? '上海黄金交易所原生报价(人民币元/克)' : '', + }; +} + +/** + * @param {string} code + * @param {MiniAppContext} context + * @param {boolean} refresh + */ +async function getQuote(code, context, refresh) { + const cached = quoteCache.get(code); + if (!refresh && cached && Date.now() - cached.at < QUOTE_TTL) return cached.value; + try { + const value = COMMODITY_SPECS[code] + ? await fetchCommodityQuote(code) + : await fetchStockQuote(code); + quoteCache.set(code, { at: Date.now(), value }); + return value; + } catch (error) { + context.logger.warn('miniapp.quote.failed', { code }); + if (cached) return { ...cached.value, stale: true }; + return { code, name: code, error: 'quote_unavailable' }; + } +} + +/** + * 股票池与商品池分开取数。 + * @param {string[]} codes + * @param {MiniAppContext} context + * @param {boolean} refresh + */ +async function fetchAllQuotes(codes, context, refresh) { + const stockPool = codes.filter((code) => !COMMODITY_SPECS[code]); + const commodityPool = codes.filter((code) => Boolean(COMMODITY_SPECS[code])); + const [stocks, commodities] = await Promise.all([ + Promise.all(stockPool.map((code) => getQuote(code, context, refresh))), + Promise.all(commodityPool.map((code) => getQuote(code, context, refresh))), + ]); + const map = new Map(); + for (const item of [...stocks, ...commodities]) map.set(item.code, item); + return codes.map((code) => map.get(code) ?? { code, error: 'quote_unavailable' }); +} + +/* ------------------------------------------------------------------ * + * 自选股持久化 + * ------------------------------------------------------------------ */ + +/** + * @param {string} dataDir + * @param {MiniAppContext} context + */ +function createWatchlistStore(dataDir, context) { + const file = join(dataDir, 'watchlist.json'); + /** @type {string[]} */ + let codes = []; + + return { + async load() { + try { + const raw = await readFile(file, 'utf8'); + const parsed = JSON.parse(raw); + const list = Array.isArray(parsed?.codes) ? parsed.codes : []; + codes = list + .map((code) => resolveInput(code)) + .filter((resolved) => Boolean(resolved)) + .map((resolved) => /** @type {{code:string}} */ (resolved).code); + } catch { + codes = []; + } + return codes; + }, + list() { + return [...codes]; + }, + async save(next) { + codes = [...next]; + try { + await mkdir(dataDir, { recursive: true }); + const temporary = `${file}.tmp`; + await writeFile(temporary, JSON.stringify({ codes, updatedAt: new Date().toISOString() }, null, 2), 'utf8'); + await rename(temporary, file); + } catch (error) { + context.logger.warn('miniapp.watchlist.persist_failed', {}); + } + }, + }; +} + +/* ------------------------------------------------------------------ * + * HTTP 层 + * ------------------------------------------------------------------ */ + +/** @type {Map} */ +const contentCache = new Map(); +/** @type {Map} */ +const quoteCache = new Map(); +/** @type {{candidates:any[], data:any}|null} */ +let lastGoodWeather = null; + +/** + * @param {import('node:http').ServerResponse} response + * @param {number} status + * @param {any} payload + */ +function sendJson(response, status, payload) { + const body = JSON.stringify(payload); + response.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + 'content-length': Buffer.byteLength(body), + }); + response.end(body); +} + +/** + * @param {import('node:http').IncomingMessage} request + * @returns {Promise} + */ +async function readBody(request) { + const chunks = []; + let size = 0; + for await (const chunk of request) { + size += chunk.length; + if (size > MAX_BODY_BYTES) throw new Error('body_too_large'); + chunks.push(chunk); + } + return Buffer.concat(chunks).toString('utf8'); +} + +/** + * @param {MiniAppContext} context + * @param {{list: () => string[], save: (next: string[]) => Promise}} watchlist + * @param {import('node:http').IncomingMessage} request + * @param {import('node:http').ServerResponse} response + */ +async function handleRequest(context, watchlist, request, response) { + const url = new URL(request.url ?? '/', 'http://miniapp.local'); + const path = url.pathname; + const method = request.method ?? 'GET'; + const refresh = url.searchParams.get('refresh') === '1'; + + if (method === 'GET' && path === '/dashboard') { + const html = await readFile(join(context.pluginRoot, 'miniapp/client/index.html')); + response.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': 'no-store', + 'content-length': html.length, + }); + response.end(html); + return; + } + + if (method === 'GET' && path === '/api/health') { + sendJson(response, 200, { ok: true }); + return; + } + + if (method === 'GET' && path === '/api/board') { + const source = url.searchParams.get('source') ?? 'weather'; + if (source === 'weather') { + try { + const city = url.searchParams.get('city') ?? '南京'; + const pick = Number(url.searchParams.get('pick') ?? '0') || 0; + const data = await loadWeather(city, pick, refresh); + sendJson(response, 200, { ok: true, source, updatedAt: new Date().toISOString(), data }); + } catch (error) { + context.logger.warn('miniapp.weather.failed', {}); + if (lastGoodWeather) { + sendJson(response, 200, { + ok: true, + source, + updatedAt: new Date().toISOString(), + stale: true, + warning: 'source_error', + message: '天气来源异常,已保留上一次数据', + data: lastGoodWeather.data, + }); + return; + } + sendJson(response, 200, { + ok: true, + source, + updatedAt: new Date().toISOString(), + warning: 'source_error', + message: '天气来源异常,请稍后重试', + data: null, + }); + } + return; + } + + if (NEWS_DEFINITIONS[source]) { + try { + const data = await loadNews(source); + sendJson(response, 200, { ok: true, source, updatedAt: data.updatedAt, data }); + } catch (error) { + context.logger.warn('miniapp.news.failed', { source }); + const cached = contentCache.get(`news:${source}`); + if (cached) { + sendJson(response, 200, { + ok: true, + source, + updatedAt: cached.value.updatedAt, + stale: true, + warning: 'source_error', + message: '新闻来源异常,已保留上一次数据', + data: cached.value, + }); + return; + } + sendJson(response, 200, { + ok: true, + source, + updatedAt: new Date().toISOString(), + warning: 'source_error', + message: '新闻来源异常,请稍后重试', + data: { label: NEWS_DEFINITIONS[source].label, items: [], status: 'error' }, + }); + } + return; + } + + sendJson(response, 400, { ok: false, error: 'invalid_code', message: '未知的栏目标识' }); + return; + } + + if (method === 'GET' && path === '/api/stocks') { + const codes = watchlist.list(); + const stocks = await fetchAllQuotes(codes, context, refresh); + sendJson(response, 200, { + ok: true, + updatedAt: new Date().toISOString(), + watchlist: codes, + stocks, + }); + return; + } + + if (method === 'POST' && path === '/api/watchlist') { + let payload; + try { + const raw = await readBody(request); + payload = JSON.parse(raw); + } catch { + sendJson(response, 400, { ok: false, error: 'invalid_code', message: '请求体无效或超过 4KB' }); + return; + } + + const action = String(payload?.action ?? ''); + const rawCode = String(payload?.code ?? ''); + if (action !== 'add' && action !== 'remove') { + sendJson(response, 400, { ok: false, error: 'invalid_code', message: '不支持的操作' }); + return; + } + + const resolved = resolveInput(rawCode); + if (!resolved) { + sendJson(response, 400, { + ok: false, + error: 'invalid_code', + message: '仅支持 6 位 A 股代码、sh/sz/bj 前缀代码或黄金、原油等预定义品种', + }); + return; + } + + const codes = watchlist.list(); + if (action === 'add') { + if (codes.includes(resolved.code)) { + const stocks = await fetchAllQuotes(codes, context, true); + sendJson(response, 200, { ok: true, message: '已在自选股中', watchlist: codes, stocks }); + return; + } + if (codes.length >= MAX_WATCHLIST) { + sendJson(response, 400, { + ok: false, + error: 'watchlist_full', + message: `自选股最多 ${MAX_WATCHLIST} 个,请先移除一个`, + }); + return; + } + codes.push(resolved.code); + } else { + const index = codes.indexOf(resolved.code); + if (index >= 0) codes.splice(index, 1); + } + + await watchlist.save(codes); + let stocks = []; + try { + stocks = await fetchAllQuotes(codes, context, true); + } catch (error) { + context.logger.warn('miniapp.watchlist.quote_failed', {}); + } + sendJson(response, 200, { + ok: true, + message: action === 'add' ? '已添加' : '已移除', + watchlist: codes, + stocks, + }); + return; + } + + sendJson(response, 404, { ok: false, error: 'invalid_code', message: '接口不存在' }); +} + +/** + * @param {MiniAppContext} context + */ +export async function start(context) { + const watchlist = createWatchlistStore(context.dataDir, context); + await watchlist.load(); + + const server = createServer((request, response) => { + handleRequest(context, watchlist, request, response).catch((error) => { + context.logger.warn('miniapp.request.failed', {}); + if (!response.headersSent) { + sendJson(response, 500, { ok: false, error: 'invalid_code', message: '服务内部异常,请稍后重试' }); + } else { + response.end(); + } + }); + }); + + await listen(server, context.listen.host, context.listen.port); + context.logger.info('miniapp.runtime.listening', {}); + + let disposed = false; + const dispose = async () => { + if (disposed) return; + disposed = true; + context.signal.removeEventListener('abort', onAbort); + contentCache.clear(); + quoteCache.clear(); + await close(server); + }; + const onAbort = () => { + void dispose(); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} + +/** + * @param {import('node:http').Server} server + * @param {string} host + * @param {number} port + */ +function listen(server, host, port) { + return new Promise((resolve, reject) => { + const onError = (error) => reject(error); + server.once('error', onError); + server.listen(port, host, () => { + server.off('error', onError); + resolve(); + }); + }); +} + +/** + * @param {import('node:http').Server} server + */ +function close(server) { + return new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); +} diff --git a/plugins/lixiangroir-ideal/weather-news-board/package.json b/plugins/lixiangroir-ideal/weather-news-board/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/lixiangroir-ideal/weather-news-board/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +} From 56b37e6220b969f6cc8fe86da88fa5e83e99f5fa Mon Sep 17 00:00:00 2001 From: lixiangroir-Ideal <361820199+lixiangroir-Ideal@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:36:58 +0800 Subject: [PATCH 02/16] =?UTF-8?q?fix(weather-news-board):=20=E5=B8=83?= =?UTF-8?q?=E5=B1=80=E6=8C=89=E5=AE=B9=E5=99=A8=E5=AE=BD=E5=BA=A6=E8=87=AA?= =?UTF-8?q?=E9=80=82=E5=BA=94=EF=BC=8C=E8=87=AA=E9=80=89=E8=82=A1=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E5=A4=9A=E5=88=97=E7=BD=91=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 用 CSS 容器查询替换视口媒体查询,按应用实际可用宽度在一栏 / 两栏 / 三栏之间重排 - 自选股改为网格布局,脚本按可用宽度与条目总数计算列数,全部条目始终留在卡片内 - 天气卡不再被拉伸成大块空白,窄卡片自动切换紧凑排版 - 版本号 1.0.0 -> 1.0.1 --- .../.minimax-plugin/plugin.json | 2 +- .../weather-news-board/README.md | 20 ++- .../weather-news-board/README.zh-CN.md | 14 +- .../miniapp/client/index.html | 167 +++++++++++++++--- 4 files changed, 168 insertions(+), 35 deletions(-) diff --git a/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json b/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json index 20a99616..fd0ff307 100644 --- a/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json +++ b/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "name": "weather-news-board", "displayName": "天气 · 新闻看板", - "version": "1.0.0", + "version": "1.0.1", "description": "展示实时天气与国内要闻、今日头条热榜、知乎日报,支持随时手动刷新,并可自选股票与黄金、原油等国际品种行情。", "author": "User", "icon": "icon.png", diff --git a/plugins/lixiangroir-ideal/weather-news-board/README.md b/plugins/lixiangroir-ideal/weather-news-board/README.md index d35181b4..53310ce4 100644 --- a/plugins/lixiangroir-ideal/weather-news-board/README.md +++ b/plugins/lixiangroir-ideal/weather-news-board/README.md @@ -8,9 +8,13 @@ switchable news columns in one dashboard page. (for example `南京`); **切换** cycles through the places that share that name. - **自选股** — a personal watchlist of A-share codes and international symbols (gold, silver, crude oil, Bitcoin futures, SGE gold 9999). Prices refresh on their own interval, separately from the - weather and news interval. + weather and news interval. The list is laid out as a grid that reflows to the width the app is + actually given, so every entry stays on screen instead of pushing the rest below the fold. - **新闻** — six tabs: 要闻, 时政, 科技, 财经, 热榜 (Toutiao hot board) and 知乎日报. +The whole page reacts to the width of its container rather than to the window size, so it looks the +same whether it is opened in a narrow side panel or on a wide screen. + Precious metals are always shown in **CNY per gram**. The raw USD-per-ounce quote and the FX rate used for the conversion are kept in the row's tooltip, so the displayed number and the source figure can be compared. @@ -32,12 +36,14 @@ rejected. - MiniMax Code **3.1.19** on **Windows 11** (Windows 10.0.26200, x64), Node.js 24.16.0. - Client acceptance exercised: published and opened the Mini App; confirmed the page is not blank - and that landmarks, headings, tabs, and controls are reachable; measured the 640 px layout - (two columns, weather card and watchlist card bottoms aligned at the same y); checked the - >= 900 px three-column layout and the dark theme; added and removed watchlist entries; - switched every news tab; confirmed that one auto-refresh cycle advances the quote timestamp and - the price; reloaded the page and confirmed the watchlist, the selected tab, and the theme - persisted. Console showed 0 errors and 0 warnings; the network showed no failed requests. + and that landmarks, headings, tabs, and controls are reachable; drove the layout through CSS + container queries at 420 px, 640 px, 1100 px, and 1440 px container widths and confirmed the + dashboard reflows from one column to two to three, that every watchlist entry stays inside its + card, that no width produces horizontal overflow, and that the watchlist packs into as many + columns as the available width allows; checked the dark theme; added and removed watchlist + entries; switched every news tab; confirmed that one auto-refresh cycle advances the quote + timestamp and the price; reloaded the page and confirmed the watchlist, the selected tab, and the + theme persisted. Console showed 0 errors and 0 warnings; the network showed no failed requests. - Not verified: the Baidu hot-board fallback and the Sina/Tencent quote fallbacks were exercised only against their endpoints directly, because the primary sources kept succeeding and the fallback branches never ran in the live app. diff --git a/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md b/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md index eaaabe81..470dc84d 100644 --- a/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md +++ b/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md @@ -5,9 +5,12 @@ - **实时天气** —— 当前温度、天气状况、体感温度、湿度、风速,以及带降水概率的三天预报。城市可以直接 输入中文(例如 `南京`),**切换** 按钮会在同名城市之间轮换。 - **自选股** —— 自建的自选清单,支持 A 股代码与黄金、白银、原油、比特币期货、上海金 9999 等国际 - 品种。行情按自己的间隔自动刷新,与天气、新闻的刷新开关互相独立。 + 品种。行情按自己的间隔自动刷新,与天气、新闻的刷新开关互相独立。列表按应用实际拿到的宽度自动 + 排成多列,条目再多也不会被挤出可视区域。 - **新闻** —— 六个栏目:要闻、时政、科技、财经、热榜(今日头条)、知乎日报。 +整页依据**容器宽度**而不是窗口宽度重排,因此无论开在窄侧边栏还是宽屏下,观感保持一致。 + 贵金属一律以**人民币 / 克**显示。原始的美元 / 盎司报价和换算所用汇率放在该行的悬停提示里, 方便和来源数值对照。 @@ -25,10 +28,11 @@ ## Tested environment - MiniMax Code **3.1.19**,**Windows 11**(Windows 10.0.26200,x64),Node.js 24.16.0。 -- 客户端验收覆盖:发布并打开 Mini App,确认页面非空白、地标、标题、标签页与控件均可访问;实测 - 640 px 布局(两列,天气卡与自选股卡底部精确对齐);检查 ≥ 900 px 三列布局与深色主题;增删 - 自选股;逐个切换新闻栏目;确认一个自动刷新周期后行情时间戳与价格确实跳动;刷新页面后自选股、 - 当前栏目与主题均保持。控制台 0 error / 0 warn,网络无失败请求。 +- 客户端验收覆盖:发布并打开 Mini App,确认页面非空白、地标、标题、标签页与控件均可访问;用 + 420 px、640 px、1100 px、1440 px 四种容器宽度驱动布局,确认看板依次由一栏重排到两栏、三栏, + 全部自选股条目都留在卡片内、任何宽度都不出现横向溢出、自选股按可用宽度排成尽可能多的列; + 检查深色主题;增删自选股;逐个切换新闻栏目;确认一个自动刷新周期后行情时间戳与价格确实跳动; + 刷新页面后自选股、当前栏目与主题均保持。控制台 0 error / 0 warn,网络无失败请求。 - 未验证:百度热榜兜底与新浪 / 腾讯行情备源只针对其接口单独做过直连验证,因为主源一直可用, 运行时并未真正走到兜底分支。 - 本包未声明 `agentAccess`、`toolAccess`、`deviceAccess`、`hostAccess` 与 `surface.window`, diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html b/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html index 66b322d0..40c814b0 100644 --- a/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html @@ -80,6 +80,12 @@ display: none !important; } + /* 布局按可用容器宽度自适应,而非视口宽度 */ + .app-shell { + container-type: inline-size; + container-name: app; + width: 100%; + } .app { max-width: 1440px; margin: 0 auto; @@ -251,12 +257,13 @@ display: grid; grid-template-columns: minmax(0, 1fr); gap: 16px; + align-items: start; } .top-grid { display: grid; - grid-template-columns: clamp(150px, 30%, 190px) minmax(0, 1fr); + grid-template-columns: minmax(0, 1fr); gap: 16px; - align-items: stretch; + align-items: start; } .card { background: var(--mcode-surface); @@ -311,10 +318,8 @@ width: 100%; } .weather-body { - flex: 1; display: flex; flex-direction: column; - justify-content: space-between; gap: 12px; } .weather-main { @@ -464,15 +469,19 @@ list-style: none; margin: 0; padding: 0; - display: flex; - flex-direction: column; - gap: 2px; - flex: 1; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(min(100%, 196px), 1fr)); + gap: 4px 8px; + align-content: start; + flex: 0 0 auto; } .stock-row { position: relative; - padding: 7px 8px; + container-type: inline-size; + container-name: tile; + padding: 6px 8px; border-radius: 8px; + min-width: 0; transition: background 150ms ease-out; } .stock-row:hover { @@ -482,6 +491,7 @@ display: flex; align-items: center; gap: 6px; + min-width: 0; } .stock-name { font-size: 13.5px; @@ -489,12 +499,14 @@ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + min-width: 0; } .stock-code { font-size: 11px; color: var(--mcode-text-subtle); font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; white-space: nowrap; + flex: none; } .stock-remove { margin-left: auto; @@ -522,10 +534,22 @@ .stock-bottom { display: flex; align-items: baseline; - gap: 8px; + gap: 4px 8px; margin-top: 2px; flex-wrap: wrap; } + .stock-quote { + display: inline-flex; + align-items: baseline; + gap: 3px; + min-width: 0; + } + .stock-deltas { + display: inline-flex; + align-items: baseline; + gap: 8px; + flex-wrap: wrap; + } .stock-price { font-size: 18px; line-height: 24px; @@ -564,12 +588,14 @@ color: var(--mcode-text-muted); } .stock-empty { + grid-column: 1 / -1; padding: 10px 2px; font-size: 12.5px; color: var(--mcode-text-muted); } .hint { - margin: 8px 0 0; + margin: auto 0 0; + padding-top: 8px; font-size: 11.5px; line-height: 17px; color: var(--mcode-text-subtle); @@ -783,22 +809,63 @@ color: #ffffff; } - /* ---------- 响应式 ---------- */ - @media (min-width: 900px) { + /* ---------- 响应式(按容器宽度自适应,不依赖视口宽度) ---------- */ + @container app (min-width: 560px) { + .top-grid { + grid-template-columns: clamp(184px, 30%, 268px) minmax(0, 1fr); + } + } + @container app (min-width: 900px) { .board { - grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); - align-items: start; + grid-template-columns: minmax(210px, 0.55fr) minmax(320px, 1.25fr) minmax(280px, 1.5fr); } .top-grid { - grid-template-columns: 270px minmax(0, 1fr); + display: contents; } } - @media (max-width: 560px) { + @container app (max-width: 559px) { .app { - padding: 16px 16px 28px; + padding: 14px 14px 24px; } - .top-grid { - grid-template-columns: minmax(0, 1fr); + } + @container tile (max-width: 190px) { + .stock-name { + font-size: 12.5px; + } + .stock-code { + font-size: 10px; + } + } + @container tile (max-width: 168px) { + .stock-price { + font-size: 16px; + line-height: 22px; + } + } + @container tile (max-width: 140px) { + .stock-code { + display: none; + } + } + /* 不支持容器查询时退回视口断点 */ + @supports not (container-type: inline-size) { + @media (min-width: 900px) { + .board { + grid-template-columns: minmax(210px, 0.55fr) minmax(320px, 1.25fr) minmax(280px, 1.5fr); + } + .top-grid { + display: contents; + } + } + @media (min-width: 560px) { + .top-grid { + grid-template-columns: clamp(184px, 30%, 268px) minmax(0, 1fr); + } + } + @media (max-width: 559px) { + .app { + padding: 14px 14px 24px; + } } } @media (prefers-reduced-motion: reduce) { @@ -811,7 +878,8 @@ -
      +
      +

      天气 · 新闻看板

      @@ -905,6 +973,7 @@

      新闻

        +
        @@ -1413,6 +1482,46 @@

        新闻

        } /* ================= 自选股 ================= */ + var STOCK_MIN_COL = 150; + var STOCK_COL_GAP = 8; + + /** + * 按可用宽度与条目总数计算最优列数。 + * 先保证行数最少;行数相同时选择末行留白更少的方案, + * 使全部条目在任意容器宽度下都能完整排布。 + */ + function layoutStockList() { + var list = el.stockList; + var count = list.children.length; + var width = list.clientWidth; + if (!count || !width) { + list.style.gridTemplateColumns = ''; + return; + } + var maxCols = Math.max( + 1, + Math.floor((width + STOCK_COL_GAP) / (STOCK_MIN_COL + STOCK_COL_GAP)), + ); + var limit = Math.min(maxCols, count); + var best = 1; + var bestRows = Infinity; + var bestEmpty = Infinity; + for (var cols = limit; cols >= 1; cols -= 1) { + var rows = Math.ceil(count / cols); + var empty = cols * rows - count; + if (rows < bestRows) { + bestRows = rows; + bestEmpty = empty; + best = cols; + } else if (rows === bestRows && empty < bestEmpty) { + bestEmpty = empty; + best = cols; + } + } + var next = 'repeat(' + best + ', minmax(0, 1fr))'; + if (list.style.gridTemplateColumns !== next) list.style.gridTemplateColumns = next; + } + function renderStocks() { var items = state.stocks.length ? state.stocks @@ -1423,6 +1532,7 @@

        新闻

        if (!items.length) { el.stockList.innerHTML = '
      • 还没有自选股。输入 6 位 A 股代码,或输入「黄金」「原油」等品种名称后点击「添加」。
      • '; + layoutStockList(); return; } @@ -1470,10 +1580,12 @@

        新闻

        REMOVE_ICON + '
        ' + '
        ' + - '' + + '' + esc(fmtNumber(item.price, decimals)) + '' + (item.unit ? '' + esc(item.unit) + '' : '') + + '' + + '' + '' + @@ -1486,6 +1598,7 @@

        新闻

        arrow + esc(fmtSigned(percent, 2)) + '%
        ' + + '
        ' + '
        ' + '' ); @@ -1493,6 +1606,7 @@

        新闻

        .join(''); el.stocksUpdated.textContent = '更新 ' + fmtClock(state.stocksUpdatedAt); + layoutStockList(); } var REMOVE_ICON = @@ -1680,6 +1794,15 @@

        新闻

        el.cityInput.value = state.city; } + /* 容器宽度变化时重新排布自选股 */ + if (window.ResizeObserver) { + var stockObserver = new ResizeObserver(function () { + layoutStockList(); + }); + stockObserver.observe(el.stockList); + } + window.addEventListener('resize', layoutStockList); + restoreViewState(); applyTheme(); renderTabs(); From f99cdde74e22fecf87831542a448358a2b8587ef Mon Sep 17 00:00:00 2001 From: lixiangroir-Ideal <361820199+lixiangroir-Ideal@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:03:14 +0800 Subject: [PATCH 03/16] =?UTF-8?q?feat(weather-news-board):=20=E7=9C=8B?= =?UTF-8?q?=E6=9D=BF=E5=B0=BA=E5=AF=B8=E5=8F=AF=E6=89=8B=E5=8A=A8=E6=8B=96?= =?UTF-8?q?=E5=8A=A8=EF=BC=8C=E5=A4=A9=E6=B0=94=E5=8D=A1=E4=B8=8E=E8=87=AA?= =?UTF-8?q?=E9=80=89=E8=82=A1=E5=8D=A1=E6=8C=89=E5=8F=AF=E7=94=A8=E7=A9=BA?= =?UTF-8?q?=E9=97=B4=E5=AF=B9=E9=BD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 右下角新增尺寸手柄:拖动调整看板宽度与高度上限,双击复位,尺寸存入 localStorage - 天气卡按相邻自选股卡的高度挑选逐时预报档位,两卡并排时高度差为 0 - 服务端补充逐时预报、气压、能见度、云量与日出日落 - 自选股卡新增涨跌条目计数 - 版本号 1.0.1 -> 1.0.2 --- .../.minimax-plugin/plugin.json | 2 +- .../weather-news-board/README.md | 23 +- .../weather-news-board/README.zh-CN.md | 19 +- .../miniapp/client/index.html | 469 +++++++++++++++++- .../miniapp/node/server.mjs | 32 ++ 5 files changed, 521 insertions(+), 24 deletions(-) diff --git a/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json b/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json index fd0ff307..eb4eb894 100644 --- a/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json +++ b/plugins/lixiangroir-ideal/weather-news-board/.minimax-plugin/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "name": "weather-news-board", "displayName": "天气 · 新闻看板", - "version": "1.0.1", + "version": "1.0.2", "description": "展示实时天气与国内要闻、今日头条热榜、知乎日报,支持随时手动刷新,并可自选股票与黄金、原油等国际品种行情。", "author": "User", "icon": "icon.png", diff --git a/plugins/lixiangroir-ideal/weather-news-board/README.md b/plugins/lixiangroir-ideal/weather-news-board/README.md index 53310ce4..66630f9b 100644 --- a/plugins/lixiangroir-ideal/weather-news-board/README.md +++ b/plugins/lixiangroir-ideal/weather-news-board/README.md @@ -8,12 +8,19 @@ switchable news columns in one dashboard page. (for example `南京`); **切换** cycles through the places that share that name. - **自选股** — a personal watchlist of A-share codes and international symbols (gold, silver, crude oil, Bitcoin futures, SGE gold 9999). Prices refresh on their own interval, separately from the - weather and news interval. The list is laid out as a grid that reflows to the width the app is - actually given, so every entry stays on screen instead of pushing the rest below the fold. + weather and news interval, and the card ends with a count of the rising, falling and unchanged + entries. - **新闻** — six tabs: 要闻, 时政, 科技, 财经, 热榜 (Toutiao hot board) and 知乎日报. The whole page reacts to the width of its container rather than to the window size, so it looks the -same whether it is opened in a narrow side panel or on a wide screen. +same whether it is opened in a narrow side panel or on a wide screen. The watchlist is laid out as a +grid that reflows to the available width, so every entry stays on screen instead of pushing the rest +below the fold. + +A size handle sits in the bottom-right corner: drag it to set the dashboard width and its height +limit (the dashboard scrolls inside once the limit is reached), and double-click it to go back to the +automatic size. When the weather card and the watchlist card sit side by side they keep the same +height, and the space that frees up is filled row by row with the hourly forecast. Precious metals are always shown in **CNY per gram**. The raw USD-per-ounce quote and the FX rate used for the conversion are kept in the row's tooltip, so the displayed number and the source @@ -40,7 +47,11 @@ rejected. container queries at 420 px, 640 px, 1100 px, and 1440 px container widths and confirmed the dashboard reflows from one column to two to three, that every watchlist entry stays inside its card, that no width produces horizontal overflow, and that the watchlist packs into as many - columns as the available width allows; checked the dark theme; added and removed watchlist + columns as the available width allows; measured a height difference of 0 px between the weather + card and the watchlist card in the two-column layout, with the hourly forecast growing and + shrinking to the space that is actually free; dragged the size handle in the bottom-right corner + and confirmed that the dashboard width, its height limit, and the stored size all follow, and that + a double-click restores the automatic size; checked the dark theme; added and removed watchlist entries; switched every news tab; confirmed that one auto-refresh cycle advances the quote timestamp and the price; reloaded the page and confirmed the watchlist, the selected tab, and the theme persisted. Console showed 0 errors and 0 warnings; the network showed no failed requests. @@ -57,8 +68,8 @@ rejected. - **Files written** — `watchlist.json` in the Host-provided `context.dataDir`, written atomically (temporary file plus rename). The directory location is opaque and chosen by the Host. - **Browser storage** — `localStorage` holds view preferences only: the selected news tab, the two - refresh intervals, the current city, and the light/dark theme. No market or article data is - stored there. + refresh intervals, the current city, the light/dark theme, and the dashboard width and height + limit that the size handle was dragged to. No market or article data is stored there. - **Network hosts** (all read-only, outbound HTTPS from the Node service): `wttr.in`, `geocoding-api.open-meteo.com`, `www.chinanews.com.cn`, `www.ithome.com`, `sspai.com`, `www.yicai.com`, `www.toutiao.com`, `top.baidu.com`, `news-at.zhihu.com`, diff --git a/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md b/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md index 470dc84d..1b7288bc 100644 --- a/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md +++ b/plugins/lixiangroir-ideal/weather-news-board/README.zh-CN.md @@ -5,11 +5,16 @@ - **实时天气** —— 当前温度、天气状况、体感温度、湿度、风速,以及带降水概率的三天预报。城市可以直接 输入中文(例如 `南京`),**切换** 按钮会在同名城市之间轮换。 - **自选股** —— 自建的自选清单,支持 A 股代码与黄金、白银、原油、比特币期货、上海金 9999 等国际 - 品种。行情按自己的间隔自动刷新,与天气、新闻的刷新开关互相独立。列表按应用实际拿到的宽度自动 - 排成多列,条目再多也不会被挤出可视区域。 + 品种。行情按自己的间隔自动刷新,与天气、新闻的刷新开关互相独立;卡片底部给出涨、跌、平的条目 + 计数。 - **新闻** —— 六个栏目:要闻、时政、科技、财经、热榜(今日头条)、知乎日报。 -整页依据**容器宽度**而不是窗口宽度重排,因此无论开在窄侧边栏还是宽屏下,观感保持一致。 +贵金属一律以**人民币 / 克**显示。原始的美元 / 盎司报价和换算所用汇率放在该行的悬停提示里, +方便和来源数值对照。 + +整页依据**容器宽度**而不是窗口宽度重排,因此无论开在窄侧边栏还是宽屏下,观感保持一致。看板右下角 +有一个尺寸手柄:拖动可以调整看板的宽度与高度上限(高度受限时内容在看板内滚动),双击恢复自适应。 +天气卡与自选股卡并排时高度保持一致,多出来的空间由逐时预报(未来若干个三小时档位)逐条填满。 贵金属一律以**人民币 / 克**显示。原始的美元 / 盎司报价和换算所用汇率放在该行的悬停提示里, 方便和来源数值对照。 @@ -31,8 +36,10 @@ - 客户端验收覆盖:发布并打开 Mini App,确认页面非空白、地标、标题、标签页与控件均可访问;用 420 px、640 px、1100 px、1440 px 四种容器宽度驱动布局,确认看板依次由一栏重排到两栏、三栏, 全部自选股条目都留在卡片内、任何宽度都不出现横向溢出、自选股按可用宽度排成尽可能多的列; - 检查深色主题;增删自选股;逐个切换新闻栏目;确认一个自动刷新周期后行情时间戳与价格确实跳动; - 刷新页面后自选股、当前栏目与主题均保持。控制台 0 error / 0 warn,网络无失败请求。 + 在两栏布局下实测天气卡与自选股卡高度差为 0,逐时预报按可用空间增减档位;拖动右下角尺寸手柄, + 确认看板宽度、高度上限随之改变且尺寸写入本地存储,双击后恢复自适应;检查深色主题;增删自选股; + 逐个切换新闻栏目;确认一个自动刷新周期后行情时间戳与价格确实跳动;刷新页面后自选股、当前栏目 + 与主题均保持。控制台 0 error / 0 warn,网络无失败请求。 - 未验证:百度热榜兜底与新浪 / 腾讯行情备源只针对其接口单独做过直连验证,因为主源一直可用, 运行时并未真正走到兜底分支。 - 本包未声明 `agentAccess`、`toolAccess`、`deviceAccess`、`hostAccess` 与 `surface.window`, @@ -44,7 +51,7 @@ - **写入的文件** —— 宿主注入的 `context.dataDir` 下的 `watchlist.json`,采用「先写临时文件再改名」 的原子写法。该目录位置由宿主决定,插件不感知。 - **浏览器存储** —— `localStorage` 只保存视图偏好:当前新闻栏目、两个刷新间隔、当前城市、浅色 / - 深色主题。不存放任何行情或文章数据。 + 深色主题,以及用户拖动尺寸手柄设定的看板宽度与高度上限。不存放任何行情或文章数据。 - **网络主机**(全部为 Node 侧发起的只读 HTTPS 出站请求):`wttr.in`、 `geocoding-api.open-meteo.com`、`www.chinanews.com.cn`、`www.ithome.com`、`sspai.com`、 `www.yicai.com`、`www.toutiao.com`、`top.baidu.com`、`news-at.zhihu.com`、 diff --git a/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html b/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html index 40c814b0..9fe8b3d6 100644 --- a/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html +++ b/plugins/lixiangroir-ideal/weather-news-board/miniapp/client/index.html @@ -82,13 +82,13 @@ /* 布局按可用容器宽度自适应,而非视口宽度 */ .app-shell { - container-type: inline-size; - container-name: app; width: 100%; } .app { - max-width: 1440px; - margin: 0 auto; + container-type: inline-size; + container-name: app; + max-width: var(--app-width, 1440px); + margin: 0 auto 0 0; padding: 20px 24px 32px; } @@ -258,12 +258,15 @@ grid-template-columns: minmax(0, 1fr); gap: 16px; align-items: start; + max-height: var(--board-max-h, none); + overflow-y: auto; + overflow-x: hidden; } .top-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: 16px; - align-items: start; + align-items: stretch; } .card { background: var(--mcode-surface); @@ -318,9 +321,69 @@ width: 100%; } .weather-body { + flex: 1; + min-height: 0; + display: flex; + } + .weather-inner { + flex: 1; + min-height: 0; display: flex; flex-direction: column; gap: 12px; + justify-content: space-between; + } + .weather-hourly { + display: flex; + flex-direction: column; + gap: 4px; + } + .weather-hour { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 8px; + border-radius: 8px; + background: var(--mcode-surface-muted); + font-size: 12px; + } + .hour-time { + width: 64px; + flex: none; + font-size: 11.5px; + color: var(--mcode-text-muted); + font-variant-numeric: tabular-nums; + white-space: nowrap; + } + .hour-day { + color: var(--mcode-text-subtle); + margin-right: 2px; + } + .hour-icon { + width: 16px; + height: 16px; + flex: none; + color: var(--mcode-text-muted); + } + .hour-temp { + font-weight: 600; + font-variant-numeric: tabular-nums; + min-width: 30px; + } + .hour-desc { + flex: 1; + min-width: 0; + color: var(--mcode-text-muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .hour-rain { + flex: none; + font-size: 11px; + color: var(--mcode-text-subtle); + font-variant-numeric: tabular-nums; + white-space: nowrap; } .weather-main { display: flex; @@ -445,6 +508,14 @@ .forecast-day { width: 24px; } + .hour-desc, + .hour-rain, + .hour-day { + display: none; + } + .hour-time { + width: 44px; + } } /* ---------- 自选股卡 ---------- */ @@ -593,6 +664,27 @@ font-size: 12.5px; color: var(--mcode-text-muted); } + .stocks-summary { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; + margin-top: 10px; + font-size: 11.5px; + color: var(--mcode-text-muted); + } + .summary-item { + display: inline-flex; + align-items: center; + gap: 4px; + font-variant-numeric: tabular-nums; + } + .summary-item.is-up { + color: var(--mcode-up); + } + .summary-item.is-down { + color: var(--mcode-down); + } .hint { margin: auto 0 0; padding-top: 8px; @@ -809,6 +901,41 @@ color: #ffffff; } + /* ---------- 尺寸手柄 ---------- */ + .resize-grip { + position: fixed; + right: max(18px, calc(100% - var(--app-width, 100%))); + bottom: 10px; + width: 26px; + height: 26px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 8px; + border: 1px solid var(--mcode-border); + background: var(--mcode-surface); + color: var(--mcode-text-subtle); + box-shadow: var(--mcode-shadow); + cursor: nwse-resize; + z-index: 30; + user-select: none; + touch-action: none; + padding: 0; + transition: color 150ms ease-out; + } + .resize-grip:hover { + color: var(--mcode-accent); + } + .resize-grip.is-active { + color: var(--mcode-accent); + border-color: var(--mcode-accent); + } + .resize-grip svg { + width: 15px; + height: 15px; + pointer-events: none; + } + /* ---------- 响应式(按容器宽度自适应,不依赖视口宽度) ---------- */ @container app (min-width: 560px) { .top-grid { @@ -842,7 +969,7 @@ line-height: 22px; } } - @container tile (max-width: 140px) { + @container tile (max-width: 120px) { .stock-code { display: none; } @@ -928,7 +1055,9 @@

        实时天气

        -

        正在获取天气…

        +
        +

        正在获取天气…

        +
        @@ -957,6 +1086,7 @@

        自选股

          +

          支持 A 股代码与黄金、原油等国际品种,非交易时段为最近成交价。

          @@ -976,6 +1106,21 @@

          新闻

          + + + + + +