diff --git a/README.md b/README.md index 1a78e881..0343acf4 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | MiniApp | What it does | Author | | --- | --- | --- | +| [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) | | [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) | @@ -98,6 +99,15 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | [Plugin Listing Workbench](plugins/zhuyankarl/submission-workbench/) | Prepare a plugin submission: fill in the manifest and listing fields, check every required field and cross-file consistency, then download a reviewable listing package that names what is missing; a bundled Skill gives the Agent the same checklist | [zhuyankarl](https://github.com/zhuyankarl) | | [WeChat Article Studio](plugins/xiaobinger/wechat-mp-article-studio/) | Plan a WeChat Official Account article: cover and illustration slots rendered as real images, a duplication check against your previous piece, versioned drafts with publish states, and paste-ready inline-styled HTML. Publishing stays blocked until account authorisation, material access and a publish interface are confirmed; with no interface connected it only ever saves a draft. Requires MiniMax Code 3.1.6 or later | [xiaobinger](https://github.com/xiaobinger) | +
+Preview: Weekly Planner + +![Weekly Planner showing the weekly progress panel and one day's task list with synthetic data](plugins/alanhean/weekly-planner/docs/preview.png) + +The preview uses synthetic data. The app interface is currently in Chinese. See its [README](plugins/alanhean/weekly-planner/README.md) for installation, data access, and compatibility notes. + +
+
Preview: Cutline diff --git a/README.zh-CN.md b/README.zh-CN.md index 19c1ac99..c9dbf240 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -57,6 +57,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | MiniApp | 功能 | 作者 | | --- | --- | --- | +| [周计划](plugins/alanhean/weekly-planner/README.zh-CN.md) | 本地周计划:手动录入任务、日期与优先级,按天查看安排,勾选完成并跟踪本周完成率 | [Alanhean](https://github.com/Alanhean) | | [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) | @@ -98,6 +99,15 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | [插件上架材料工作台](plugins/zhuyankarl/submission-workbench/README.zh-CN.md) | 填写插件清单与上架信息,逐项核对必填字段与内容一致性,生成可审核的上架材料包并标出缺失项;内置 Skill 让 Agent 拿到同一套检查清单 | [zhuyankarl](https://github.com/zhuyankarl) | | [公众号图文工作台](plugins/xiaobinger/wechat-mp-article-studio/README.zh-CN.md) | 输入主题、正文、封面与插图需求,选一个视觉风格,产出封面与插图方案、与上一篇的查重结论、带版本和发布状态的草稿箱,以及可以直接粘贴进公众号的内联样式 HTML;发布前必须确认账号授权、素材范围与可用发布接口,没接接口时只存草稿。需要 MiniMax Code 3.1.6 或更高版本 | [xiaobinger](https://github.com/xiaobinger) | +
+预览:周计划 + +![周计划,使用合成数据展示本周进度面板与当天的任务列表](plugins/alanhean/weekly-planner/docs/preview.png) + +预览使用合成数据。应用界面目前为中文。安装、数据访问与兼容性说明见其 [README](plugins/alanhean/weekly-planner/README.zh-CN.md)。 + +
+
预览:Cutline diff --git a/plugins/alanhean/weekly-planner/.minimax-plugin/plugin.json b/plugins/alanhean/weekly-planner/.minimax-plugin/plugin.json new file mode 100644 index 00000000..ba02efdc --- /dev/null +++ b/plugins/alanhean/weekly-planner/.minimax-plugin/plugin.json @@ -0,0 +1,17 @@ +{ + "schemaVersion": 1, + "name": "weekly-planner", + "displayName": "Weekly Planner", + "version": "1.0.0", + "description": "A local weekly planner: add tasks with a date and a priority, review them day by day, mark them done, and track the week's progress. Data stays on your machine.", + "author": "Alanhean", + "icon": "icon.png", + "category": "Productivity", + "exampleQueries": [ + "Open Weekly Planner to see today's tasks.", + "Add a task to this week's plan in Weekly Planner." + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/alanhean/weekly-planner/LICENSE b/plugins/alanhean/weekly-planner/LICENSE new file mode 100644 index 00000000..01bbd3a1 --- /dev/null +++ b/plugins/alanhean/weekly-planner/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Alan + +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/alanhean/weekly-planner/README.md b/plugins/alanhean/weekly-planner/README.md new file mode 100644 index 00000000..2aed8fd0 --- /dev/null +++ b/plugins/alanhean/weekly-planner/README.md @@ -0,0 +1,78 @@ +# Weekly Planner (`weekly-planner`) + +A local weekly planner that runs inside MiniMax Code. Add tasks by hand with a date and a +priority, walk through the week day by day, tick tasks off, and watch the week's completion +rate update. Everything is stored on your own machine; nothing is sent anywhere. + +![Weekly Planner showing the weekly progress panel and one day's task list](docs/preview.png) + +[中文说明](./README.zh-CN.md) + +## Install + +Copy this directory, including the hidden `.minimax-plugin/`, into the MiniMax Code plugins +directory as `weekly-planner/` (`~/.minimax/plugins/weekly-planner/` by default; the root +README's Install section explains where that directory is). Restart MiniMax Code and ask the +Agent to "Open Weekly Planner". + +## What it does + +- **Add a task** — a title, a date, a priority (high / medium / low) and an optional note. +- **View it by day** — one tab per weekday with that day's task count; step to the previous or + next week, or jump back to the current week. +- **View the whole week** — every day of the week grouped together, each with its completion + count. +- **Mark a task done** — tick the checkbox; the day's count, the week's totals and the + completion rate update immediately. +- **Edit and delete** — any task can be edited or removed, and deletion asks for confirmation + first. +- **Weekly progress** — the week's task count, completed count, completion rate and a per-day + distribution, always on screen. + +## Tested environment + +- MiniMax Code 3.1.19 on Windows 11 (26H2, build 26300). Installed as a local Mini App + package, opened through the Agent, page rendered. +- Client acceptance exercised: create a task, edit it, tick it done, filter by completion + state, switch between the day and week views, step between weeks, delete a task, and confirm + that the task list survives a page reload. Light and dark themes were checked. The Node + service was exercised directly as well: validation rejects an empty title, an impossible + date and an unknown priority; a request that tries to escape the client directory is + refused; and the stored plan is read back after a restart. +- Not verified: two windows editing the same plan at the same time. The stored file is + replaced as a whole, so the last write wins rather than merging per task. + +## Data & access + +- Files: reads its own `miniapp/client/*` files. Writes one file, `tasks.json`, in the + Host-owned runtime data directory (`context.dataDir`); that location is opaque and managed + by MiniMax Code. Writes are atomic (a temporary file plus a rename), so an interrupted + write cannot leave a half-written file. A file that cannot be parsed is kept as a backup and + reported in the page instead of being silently dropped. +- Network: none. The page only talks to its own Node service on the Host-assigned loopback + port. +- Processes: none. +- Agent turns: none. Conversations read: none. Tools called: none. +- Microphone, camera and notifications: not used. Host navigation read: not used. +- State: the task list lives in `tasks.json` inside the Host-owned data directory. The page + keeps only view preferences (selected day, view mode, completion filter) in the browser's + local storage, and saves them when the page is hidden. + +## Files + +```text +.minimax-plugin/plugin.json Plugin manifest +package.json Mini App declaration +miniapp/miniapp.json Payload roots, Node entry, page route +miniapp/client/index.html The page served at /plan +miniapp/client/styles.css Styles, light and dark themes +miniapp/client/app.js Page logic: rendering, dialogs, API calls +miniapp/node/server.mjs Node entry: start(context) → { dispose } +miniapp/node/miniapp-api.ts Type declarations for the runtime context +icon.png Plugin icon +docs/preview.png Preview screenshot (synthetic data) +``` + +## License + +[MIT](./LICENSE) diff --git a/plugins/alanhean/weekly-planner/README.zh-CN.md b/plugins/alanhean/weekly-planner/README.zh-CN.md new file mode 100644 index 00000000..67286d78 --- /dev/null +++ b/plugins/alanhean/weekly-planner/README.zh-CN.md @@ -0,0 +1,66 @@ +# 周计划(`weekly-planner`) + +运行在 MiniMax Code 里的本地周计划工具。手动录入任务、日期和优先级,按天查看安排,勾选完成, +随时看到本周完成率。所有数据都存在你自己的电脑上,不会上传到任何地方。 + +![周计划:本周进度面板与当天的任务列表](docs/preview.png) + +[English](./README.md) + +## 安装 + +把整个目录(含隐藏的 `.minimax-plugin/`)复制到 MiniMax Code 的插件目录,命名为 +`weekly-planner/`(默认是 `~/.minimax/plugins/weekly-planner/`,具体位置见仓库根 README 的 +安装章节)。重启 MiniMax Code 后,让 Agent 打开「周计划」即可。 + +## 能做什么 + +- **录入任务**:填写标题、日期、优先级(高 / 中 / 低)和可选备注。 +- **按天查看**:周一到周日各一个标签并显示当天任务数,可翻到上一周、下一周,或回到本周。 +- **整周查看**:一周七天分组展示,每组标出当天完成情况。 +- **标记完成**:勾选复选框,当天计数、本周总数和完成率立即更新。 +- **编辑与删除**:任意任务都能编辑或删除,删除前会二次确认。 +- **本周进度**:本周任务数、已完成数、完成率进度条和每日完成分布,常驻在页面上方。 + +## 测试环境 + +- MiniMax Code 3.1.19,Windows 11(26H2,build 26300)。以本地 Mini App 包安装,通过 Agent + 打开,页面正常渲染。 +- 客户端验收覆盖:新建任务、编辑任务、勾选完成、按完成状态筛选、按天与整周视图切换、翻周、 + 删除任务,并确认刷新页面后任务仍在;同时检查了浅色与深色两套主题。Node 服务也单独验证过: + 空标题、不存在的日期、非法优先级都会被拒绝,试图越出客户端目录的请求返回 404,重启后计划 + 数据能读回。 +- 未验证:两个窗口同时编辑同一份计划。落盘是整份文件替换,后写入的一方覆盖先写入的一方, + 不会按任务逐条合并。 + +## 数据与权限 + +- 文件:只读取自身的 `miniapp/client/*`。只写入一个文件 `tasks.json`,位于宿主提供的运行时 + 数据目录(`context.dataDir`),该目录由 MiniMax Code 管理,位置对外不透明。写入是原子的 + (先写临时文件再重命名),中途被打断不会留下写坏的文件。若文件内容无法解析,会保留成备份 + 并在页面上提示,而不是悄悄丢弃。 +- 网络:不访问任何外部服务。页面只与自己的 Node 服务通信,走的是宿主分配的回环端口。 +- 进程:不派生任何子进程。 +- Agent 对话轮次:不运行。读取会话:不读取。调用工具:不调用。 +- 麦克风、摄像头、通知:均未使用。读取宿主导航状态:未使用。 +- 状态:任务清单存放在宿主数据目录的 `tasks.json` 里。页面只在浏览器 localStorage 中保存视图 + 偏好(当前选中日期、视图模式、完成状态筛选),并在页面隐藏时写入。 + +## 文件 + +```text +.minimax-plugin/plugin.json 插件清单 +package.json Mini App 声明 +miniapp/miniapp.json 负载根目录、Node 入口、页面路由 +miniapp/client/index.html /plan 上提供的页面 +miniapp/client/styles.css 样式,含浅色与深色主题 +miniapp/client/app.js 页面逻辑:渲染、弹窗、接口调用 +miniapp/node/server.mjs Node 入口:start(context) → { dispose } +miniapp/node/miniapp-api.ts 运行时上下文的类型声明 +icon.png 插件图标 +docs/preview.png 预览截图(合成数据) +``` + +## 许可 + +[MIT](./LICENSE) diff --git a/plugins/alanhean/weekly-planner/docs/preview.png b/plugins/alanhean/weekly-planner/docs/preview.png new file mode 100644 index 00000000..3090b5ca Binary files /dev/null and b/plugins/alanhean/weekly-planner/docs/preview.png differ diff --git a/plugins/alanhean/weekly-planner/icon.png b/plugins/alanhean/weekly-planner/icon.png new file mode 100644 index 00000000..299a26cb Binary files /dev/null and b/plugins/alanhean/weekly-planner/icon.png differ diff --git a/plugins/alanhean/weekly-planner/miniapp/client/app.js b/plugins/alanhean/weekly-planner/miniapp/client/app.js new file mode 100644 index 00000000..e0d367bf --- /dev/null +++ b/plugins/alanhean/weekly-planner/miniapp/client/app.js @@ -0,0 +1,833 @@ +'use strict'; + +/** + * 周计划 Mini App — 页面逻辑。 + * 页面只负责展示与交互;所有数据读写都走 Node 领域服务(/api/*)。 + */ + +const WEEKDAYS = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']; +const PRIORITY_LABEL = { high: '高优先级', medium: '中优先级', low: '低优先级' }; +const FILTER_LABEL = { all: '全部任务', todo: '未完成', done: '已完成' }; +const VIEW_STORAGE_KEY = 'weekly-planner:view'; + +/* ---------------------------------------------------------------- 工具函数 */ + +function $(id) { + return document.getElementById(id); +} + +function el(tag, props = {}, children = []) { + const node = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value === null || value === undefined || value === false) continue; + if (key === 'class') node.className = value; + else if (key === 'text') node.textContent = value; + else if (key.startsWith('on')) node.addEventListener(key.slice(2).toLowerCase(), value); + else node.setAttribute(key, value === true ? '' : String(value)); + } + for (const child of [].concat(children)) { + if (child === null || child === undefined || child === false) continue; + node.append(typeof child === 'string' ? document.createTextNode(child) : child); + } + return node; +} + +function pad2(value) { + return String(value).padStart(2, '0'); +} + +function toDateKey(date) { + return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`; +} + +function fromDateKey(key) { + const [year, month, day] = key.split('-').map(Number); + return new Date(year, month - 1, day); +} + +function isDateKey(value) { + return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value); +} + +function startOfWeek(date) { + const day = new Date(date.getFullYear(), date.getMonth(), date.getDate()); + const weekday = day.getDay(); + day.setDate(day.getDate() + (weekday === 0 ? -6 : 1 - weekday)); + return day; +} + +function addDays(date, count) { + const next = new Date(date.getFullYear(), date.getMonth(), date.getDate()); + next.setDate(next.getDate() + count); + return next; +} + +function dayDiff(later, earlier) { + const a = Date.UTC(later.getFullYear(), later.getMonth(), later.getDate()); + const b = Date.UTC(earlier.getFullYear(), earlier.getMonth(), earlier.getDate()); + return Math.round((a - b) / 86400000); +} + +function todayKey() { + return toDateKey(new Date()); +} + +function formatDateKey(key) { + const date = fromDateKey(key); + return `${date.getMonth() + 1}月${date.getDate()}日`; +} + +function formatFullDate(key) { + const date = fromDateKey(key); + return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`; +} + +/* ------------------------------------------------------------------- 状态 */ + +const state = { + tasks: [], + warning: null, + view: 'day', + filter: 'all', + weekStart: startOfWeek(new Date()), + selectedDate: todayKey(), + editingId: null, + loading: true, +}; + +let pendingDeleteId = null; +let toastTimer = null; +let focusTaskId = null; +let focusTabDate = null; + +/* --------------------------------------------------------------- DOM 引用 */ + +const dom = { + addTaskButton: $('add-task-button'), + prevWeekButton: $('prev-week-button'), + nextWeekButton: $('next-week-button'), + thisWeekButton: $('this-week-button'), + weekRange: $('week-range'), + viewTabs: Array.from(document.querySelectorAll('[data-view]')), + filterButtons: Array.from(document.querySelectorAll('[data-filter]')), + dayPanel: $('day-panel'), + weekPanel: $('week-panel'), + dayTabs: $('day-tabs'), + dayTitle: $('day-title'), + dayMeta: $('day-meta'), + taskList: $('task-list'), + dayEmpty: $('day-empty'), + emptyTitle: $('empty-title'), + emptyText: $('empty-text'), + loadingState: $('loading-state'), + weekGroups: $('week-groups'), + weekMeta: $('week-meta'), + progressSummary: $('progress-summary'), + progressBar: $('progress-bar'), + progressFill: $('progress-fill'), + kpiTotal: $('kpi-total'), + kpiDone: $('kpi-done'), + kpiRate: $('kpi-rate'), + dayDistribution: $('day-distribution'), + errorBanner: $('error-banner'), + errorText: $('error-text'), + retryButton: $('retry-button'), + toast: $('toast'), + scrim: $('dialog-scrim'), + dialog: $('task-dialog'), + dialogTitle: $('task-dialog-title'), + dialogSubtitle: $('task-dialog-subtitle'), + form: $('task-form'), + titleInput: $('task-title'), + dateInput: $('task-date'), + noteInput: $('task-note'), + dialogError: $('dialog-error'), + submitButton: $('task-submit-button'), + cancelButton: $('task-cancel-button'), + confirmDialog: $('confirm-dialog'), + confirmText: $('confirm-text'), + confirmOk: $('confirm-ok-button'), + confirmCancel: $('confirm-cancel-button'), +}; + +const noticeBanner = el('p', { class: 'banner banner--notice', role: 'status' }); +noticeBanner.hidden = true; +dom.errorBanner.parentNode.insertBefore(noticeBanner, dom.errorBanner); + +/* ------------------------------------------------------------- 数据访问层 */ + +async function apiRequest(method, path, body) { + const options = { method, headers: { accept: 'application/json' } }; + if (body !== undefined) { + options.headers['content-type'] = 'application/json'; + options.body = JSON.stringify(body); + } + const response = await fetch(path, options); + let payload = null; + try { + payload = await response.json(); + } catch { + payload = null; + } + if (!response.ok) { + throw new Error( + payload && typeof payload.message === 'string' ? payload.message : '操作失败,请稍后重试。', + ); + } + return payload; +} + +function applySnapshot(snapshot) { + if (!snapshot) return; + if (Array.isArray(snapshot.tasks)) state.tasks = snapshot.tasks; + state.warning = typeof snapshot.warning === 'string' ? snapshot.warning : null; +} + +async function loadTasks() { + state.loading = true; + render(); + try { + const snapshot = await apiRequest('GET', '/api/state'); + applySnapshot(snapshot); + hideError(); + } catch (error) { + showError(error.message); + } finally { + state.loading = false; + render(); + } +} + +/* ---------------------------------------------------------------- 渲染层 */ + +function weekTasks() { + const start = toDateKey(state.weekStart); + const end = toDateKey(addDays(state.weekStart, 6)); + return state.tasks.filter((task) => task.date >= start && task.date <= end); +} + +function applyFilter(tasks) { + if (state.filter === 'todo') return tasks.filter((task) => !task.done); + if (state.filter === 'done') return tasks.filter((task) => task.done); + return tasks; +} + +function render() { + renderWeekLabel(); + renderProgress(); + renderDayTabs(); + renderDayView(); + renderWeekView(); + renderViewMode(); + renderNotice(); + applyFocus(); +} + +function renderWeekLabel() { + const end = addDays(state.weekStart, 6); + dom.weekRange.textContent = `${formatDateKey(toDateKey(state.weekStart))} - ${formatDateKey(toDateKey(end))}`; +} + +function renderProgress() { + const tasks = weekTasks(); + const done = tasks.filter((task) => task.done).length; + const total = tasks.length; + const rate = total === 0 ? 0 : Math.round((done / total) * 100); + + dom.kpiTotal.textContent = String(total); + dom.kpiDone.textContent = String(done); + dom.kpiRate.textContent = `${rate}%`; + + dom.progressFill.style.width = `${rate}%`; + dom.progressFill.classList.toggle('is-complete', total > 0 && done === total); + dom.progressBar.setAttribute('aria-valuenow', String(rate)); + dom.progressBar.setAttribute( + 'aria-valuetext', + total === 0 ? '本周暂无任务' : `本周 ${total} 项任务,已完成 ${done} 项,完成率 ${rate}%`, + ); + dom.progressSummary.textContent = + total === 0 + ? '本周还没有安排任务' + : `${formatDateKey(toDateKey(state.weekStart))} 起 · 已完成 ${done} / ${total} 项`; + + dom.dayDistribution.replaceChildren( + ...Array.from({ length: 7 }, (_, index) => { + const date = addDays(state.weekStart, index); + const key = toDateKey(date); + const dayTasks = state.tasks.filter((task) => task.date === key); + const dayDone = dayTasks.filter((task) => task.done).length; + const ratio = dayTasks.length === 0 ? 0 : Math.round((dayDone / dayTasks.length) * 100); + const fill = el('span', { class: 'dist-item__fill' }); + fill.style.width = `${ratio}%`; + return el( + 'li', + { + class: 'dist-item', + title: `${WEEKDAYS[index]} ${formatDateKey(key)}:${dayDone}/${dayTasks.length} 完成`, + }, + [ + el('span', { class: 'dist-item__label', text: WEEKDAYS[index] }), + el('span', { class: 'dist-item__bar' }, [fill]), + el('span', { + class: 'dist-item__value', + text: dayTasks.length === 0 ? '—' : `${dayDone}/${dayTasks.length}`, + }), + ], + ); + }), + ); +} + +function renderDayTabs() { + const today = todayKey(); + dom.dayTabs.replaceChildren( + ...Array.from({ length: 7 }, (_, index) => { + const date = addDays(state.weekStart, index); + const key = toDateKey(date); + const dayTasks = state.tasks.filter((task) => task.date === key); + const selected = key === state.selectedDate; + const tab = el( + 'button', + { + type: 'button', + class: 'day-tab', + id: `day-tab-${key}`, + role: 'tab', + 'aria-selected': selected ? 'true' : 'false', + 'aria-controls': 'day-panel', + 'aria-label': `${WEEKDAYS[index]} ${formatDateKey(key)},${dayTasks.length} 项任务`, + tabindex: selected ? '0' : '-1', + 'data-date': key, + }, + [ + el('span', { class: 'day-tab__weekday', text: WEEKDAYS[index] }), + el('span', { class: 'day-tab__date', text: `${date.getMonth() + 1}/${date.getDate()}` }), + key === today ? el('span', { class: 'day-tab__today', text: '今天' }) : null, + el('span', { class: 'day-tab__count', text: `${dayTasks.length} 项` }), + ], + ); + return tab; + }), + ); +} + +function renderDayView() { + const key = state.selectedDate; + const dayTasks = state.tasks.filter((task) => task.date === key); + const visible = applyFilter(dayTasks); + + dom.dayTitle.textContent = `${formatFullDate(key)} ${WEEKDAYS[(dayDiff(fromDateKey(key), state.weekStart) + 7) % 7]}`; + dom.dayMeta.textContent = + state.filter === 'all' + ? `共 ${dayTasks.length} 项任务` + : `${FILTER_LABEL[state.filter]} · ${visible.length} / ${dayTasks.length} 项`; + + dom.taskList.replaceChildren(...visible.map(renderTaskItem)); + + dom.dayEmpty.hidden = visible.length > 0 || state.loading; + if (dayTasks.length === 0) { + dom.emptyTitle.textContent = '这一天还没有任务'; + dom.emptyText.textContent = '点击右上角“新建任务”,把要做的事情添加进来。'; + } else { + dom.emptyTitle.textContent = + state.filter === 'done' ? '这一天没有已完成的任务' : '这一天没有未完成的任务'; + dom.emptyText.textContent = '换个筛选条件,或切回“全部”查看这一天的安排。'; + } + dom.loadingState.hidden = !state.loading; +} + +function renderWeekView() { + const tasks = weekTasks(); + const visible = applyFilter(tasks); + dom.weekMeta.textContent = + state.filter === 'all' + ? `共 ${tasks.length} 项任务` + : `${FILTER_LABEL[state.filter]} · ${visible.length} / ${tasks.length} 项`; + + const groups = Array.from({ length: 7 }, (_, index) => { + const date = addDays(state.weekStart, index); + const key = toDateKey(date); + const dayTasks = visible.filter((task) => task.date === key); + const done = dayTasks.filter((task) => task.done).length; + + const head = el('div', { class: 'week-group__head' }, [ + el('h3', { class: 'week-group__title', text: `${WEEKDAYS[index]} · ${formatDateKey(key)}` }), + el('span', { + class: 'week-group__meta', + text: dayTasks.length === 0 ? '无任务' : `${done} / ${dayTasks.length} 完成`, + }), + ]); + + const body = + dayTasks.length === 0 + ? [el('p', { class: 'week-group__empty', text: '这一天没有安排任务。' })] + : [el('ul', { class: 'task-list' }, dayTasks.map(renderTaskItem))]; + + return el('section', { class: 'week-group' }, [head, ...body]); + }); + + dom.weekGroups.replaceChildren(...groups); +} + +function renderViewMode() { + const isDay = state.view === 'day'; + dom.dayPanel.hidden = !isDay; + dom.weekPanel.hidden = isDay; + for (const tab of dom.viewTabs) { + const active = tab.dataset.view === state.view; + tab.setAttribute('aria-selected', active ? 'true' : 'false'); + tab.tabIndex = active ? 0 : -1; + } + for (const button of dom.filterButtons) { + button.setAttribute('aria-pressed', button.dataset.filter === state.filter ? 'true' : 'false'); + } +} + +function renderNotice() { + if (!state.warning) { + noticeBanner.hidden = true; + noticeBanner.textContent = ''; + return; + } + noticeBanner.textContent = state.warning; + noticeBanner.hidden = false; +} + +function applyFocus() { + if (focusTabDate) { + const tab = dom.dayTabs.querySelector(`[data-date="${focusTabDate}"]`); + focusTabDate = null; + if (tab) { + tab.focus(); + return; + } + } + if (focusTaskId) { + const panel = state.view === 'day' ? dom.dayPanel : dom.weekPanel; + const input = panel.querySelector(`input[data-task-id="${focusTaskId}"]`); + focusTaskId = null; + if (input) input.focus(); + } +} + +function renderTaskItem(task) { + const item = el('li', { class: task.done ? 'task-item is-done' : 'task-item' }); + + const checkbox = el('input', { + type: 'checkbox', + 'data-task-id': task.id, + 'aria-label': `${task.done ? '标记未完成' : '标记完成'}:${task.title}`, + }); + checkbox.checked = task.done; + + const meta = el('div', { class: 'task-meta' }, [ + el('span', { class: `pill pill--${task.priority}`, text: PRIORITY_LABEL[task.priority] }), + el('time', { datetime: task.date, text: formatDateKey(task.date) }), + task.done ? el('span', { class: 'pill pill--done', text: '已完成' }) : null, + task.note ? el('span', { class: 'task-note', text: task.note }) : null, + ]); + + const body = el('div', { class: 'task-body' }, [ + el('p', { class: 'task-title', text: task.title }), + meta, + ]); + + const actions = el('div', { class: 'task-actions' }, [ + iconButton('edit', '编辑任务', 'edit', task.id), + iconButton('trash', '删除任务', 'delete', task.id), + ]); + + item.append(el('label', { class: 'task-check' }, [checkbox]), body, actions); + return item; +} + +const ICON_PATHS = { + edit: ['M12 20h9', 'M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z'], + trash: ['M3 6h18', 'M8 6V4h8v2', 'M19 6l-1 14H6L5 6', 'M10 11v6', 'M14 11v6'], +}; + +function iconButton(name, label, action, taskId) { + const button = el('button', { + type: 'button', + class: action === 'delete' ? 'icon-action icon-action--danger' : 'icon-action', + 'aria-label': label, + title: label, + 'data-action': action, + 'data-task-id': taskId, + }); + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('class', 'icon'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('aria-hidden', 'true'); + svg.setAttribute('fill', 'none'); + svg.setAttribute('stroke', 'currentColor'); + svg.setAttribute('stroke-width', '1.8'); + svg.setAttribute('stroke-linecap', 'round'); + svg.setAttribute('stroke-linejoin', 'round'); + for (const d of ICON_PATHS[name] ?? []) { + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute('d', d); + svg.append(path); + } + button.append(svg); + return button; +} + +/* ----------------------------------------------------------------- 交互 */ + +/** + * 打开对话框。 + * 文档不可见时(窗口在后台)浏览器会拒绝 showModal(),此时降级为非模态打开, + * 保证新建、编辑、删除在任何窗口状态下都可用。 + */ +function showDialog(dialog) { + let modal = false; + if (typeof dialog.showModal === 'function') { + try { + dialog.showModal(); + modal = true; + } catch { + modal = false; + } + } + if (!modal) { + dialog.setAttribute('open', ''); + dom.scrim.hidden = false; + } + return modal; +} + +function hideDialog(dialog) { + if (dialog.open) { + try { + dialog.close(); + } catch { + dialog.removeAttribute('open'); + } + } + dom.scrim.hidden = true; +} + +function selectDate(key) { + if (!isDateKey(key)) return; + state.selectedDate = key; + saveViewState(); + render(); +} + +function shiftWeek(delta) { + const offset = dayDiff(fromDateKey(state.selectedDate), state.weekStart); + state.weekStart = addDays(state.weekStart, delta * 7); + const clamped = Math.min(Math.max(offset, 0), 6); + state.selectedDate = toDateKey(addDays(state.weekStart, clamped)); + saveViewState(); + render(); +} + +function goToThisWeek() { + state.weekStart = startOfWeek(new Date()); + state.selectedDate = todayKey(); + saveViewState(); + render(); +} + +async function toggleTask(task, done) { + focusTaskId = task.id; + try { + const snapshot = await apiRequest('PATCH', `/api/tasks/${encodeURIComponent(task.id)}`, { done }); + applySnapshot(snapshot); + } catch (error) { + showError(error.message); + } + render(); +} + +function openTaskDialog(task) { + state.editingId = task ? task.id : null; + dom.dialogTitle.textContent = task ? '编辑任务' : '新建任务'; + dom.dialogSubtitle.textContent = task + ? '可以修改标题、日期、优先级或备注。' + : '记录一件本周要做的事。'; + dom.titleInput.value = task ? task.title : ''; + dom.dateInput.value = task + ? task.date + : state.view === 'day' + ? state.selectedDate + : todayKey(); + dom.noteInput.value = task ? task.note : ''; + const radio = dom.form.querySelector(`input[name="priority"][value="${task ? task.priority : 'medium'}"]`); + if (radio) radio.checked = true; + dom.dialogError.hidden = true; + dom.submitButton.textContent = task ? '保存修改' : '保存任务'; + showDialog(dom.dialog); + dom.titleInput.focus(); +} + +function openConfirmDialog(task) { + pendingDeleteId = task.id; + dom.confirmText.textContent = `「${task.title}」将被永久删除,此操作无法撤销。`; + showDialog(dom.confirmDialog); + dom.confirmCancel.focus(); +} + +function showDialogError(message) { + dom.dialogError.textContent = message; + dom.dialogError.hidden = false; +} + +function showError(message) { + dom.errorText.textContent = message; + dom.errorBanner.hidden = false; +} + +function hideError() { + dom.errorBanner.hidden = true; + dom.errorText.textContent = ''; +} + +function showToast(message) { + dom.toast.textContent = message; + dom.toast.hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { + dom.toast.hidden = true; + }, 2600); +} + +/* ------------------------------------------------------- 视图状态(本地) */ + +function saveViewState() { + try { + localStorage.setItem( + VIEW_STORAGE_KEY, + JSON.stringify({ + view: state.view, + filter: state.filter, + weekStart: toDateKey(state.weekStart), + selectedDate: state.selectedDate, + }), + ); + } catch { + /* 视图状态持久化失败不影响主流程 */ + } +} + +function loadViewState() { + try { + const raw = localStorage.getItem(VIEW_STORAGE_KEY); + if (!raw) return; + const saved = JSON.parse(raw); + if (saved.view === 'day' || saved.view === 'week') state.view = saved.view; + if (['all', 'todo', 'done'].includes(saved.filter)) state.filter = saved.filter; + if (isDateKey(saved.weekStart)) state.weekStart = startOfWeek(fromDateKey(saved.weekStart)); + if (isDateKey(saved.selectedDate)) state.selectedDate = saved.selectedDate; + const start = toDateKey(state.weekStart); + const end = toDateKey(addDays(state.weekStart, 6)); + if (state.selectedDate < start || state.selectedDate > end) { + state.selectedDate = start; + } + } catch { + /* 忽略损坏的视图状态 */ + } +} + +/* --------------------------------------------------------------- 事件绑定 */ + +/** + * 任务行与日期标签每次渲染都会被重建,因此事件统一委托在稳定的 document 上, + * 避免重绘正好发生在按下与抬起之间时丢失点击。 + */ +let pointerActionHandled = false; + +function runTaskAction(element) { + const task = state.tasks.find((item) => item.id === element.dataset.taskId); + if (!task) return false; + if (element.dataset.action === 'edit') { + openTaskDialog(task); + return true; + } + if (element.dataset.action === 'delete') { + openConfirmDialog(task); + return true; + } + return false; +} + +document.addEventListener('pointerdown', (event) => { + const element = + event.target instanceof Element ? event.target.closest('[data-action]') : null; + pointerActionHandled = element ? runTaskAction(element) : false; +}); + +document.addEventListener('click', (event) => { + const target = event.target instanceof Element ? event.target : null; + if (!target) return; + + const actionElement = target.closest('[data-action]'); + if (actionElement) { + if (pointerActionHandled) { + pointerActionHandled = false; + return; + } + runTaskAction(actionElement); + return; + } + + const dayTab = target.closest('.day-tab'); + if (dayTab && dayTab.dataset.date) selectDate(dayTab.dataset.date); +}); + +document.addEventListener('change', (event) => { + const target = event.target; + if (!(target instanceof HTMLInputElement)) return; + if (!target.matches('input[data-task-id]')) return; + const task = state.tasks.find((item) => item.id === target.dataset.taskId); + if (!task) return; + void toggleTask(task, target.checked); +}); + +dom.addTaskButton.addEventListener('click', () => openTaskDialog(null)); +dom.prevWeekButton.addEventListener('click', () => shiftWeek(-1)); +dom.nextWeekButton.addEventListener('click', () => shiftWeek(1)); +dom.thisWeekButton.addEventListener('click', goToThisWeek); +dom.retryButton.addEventListener('click', () => void loadTasks()); + +for (const tab of dom.viewTabs) { + tab.addEventListener('click', () => { + state.view = tab.dataset.view === 'week' ? 'week' : 'day'; + saveViewState(); + render(); + }); + tab.addEventListener('keydown', (event) => { + if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return; + event.preventDefault(); + const next = state.view === 'day' ? 'week' : 'day'; + state.view = next; + saveViewState(); + render(); + const target = dom.viewTabs.find((item) => item.dataset.view === next); + if (target) target.focus(); + }); +} + +for (const button of dom.filterButtons) { + button.addEventListener('click', () => { + state.filter = button.dataset.filter; + saveViewState(); + render(); + }); +} + +dom.dayTabs.addEventListener('keydown', (event) => { + if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return; + event.preventDefault(); + const delta = event.key === 'ArrowRight' ? 1 : -1; + const index = (dayDiff(fromDateKey(state.selectedDate), state.weekStart) + delta + 7) % 7; + const key = toDateKey(addDays(state.weekStart, index)); + state.selectedDate = key; + focusTabDate = key; + saveViewState(); + render(); +}); + +dom.form.addEventListener('submit', async (event) => { + event.preventDefault(); + const title = dom.titleInput.value.trim(); + if (!title) { + showDialogError('请填写任务标题。'); + dom.titleInput.focus(); + return; + } + const date = dom.dateInput.value; + if (!isDateKey(date)) { + showDialogError('请选择有效日期。'); + dom.dateInput.focus(); + return; + } + const checked = dom.form.querySelector('input[name="priority"]:checked'); + const priority = checked ? checked.value : 'medium'; + const note = dom.noteInput.value.trim(); + + dom.submitButton.disabled = true; + try { + if (state.editingId) { + const snapshot = await apiRequest('PATCH', `/api/tasks/${encodeURIComponent(state.editingId)}`, { + title, + date, + priority, + note, + }); + applySnapshot(snapshot); + hideDialog(dom.dialog); + showToast('任务已更新'); + } else { + const snapshot = await apiRequest('POST', '/api/tasks', { title, date, priority, note }); + applySnapshot(snapshot); + // 新任务可能落在别的周:把视图切到它所在的日期,避免“任务不见了”。 + state.weekStart = startOfWeek(fromDateKey(date)); + state.selectedDate = date; + saveViewState(); + hideDialog(dom.dialog); + showToast('任务已添加'); + } + hideError(); + render(); + } catch (error) { + showDialogError(error.message); + } finally { + dom.submitButton.disabled = false; + } +}); + +dom.cancelButton.addEventListener('click', () => hideDialog(dom.dialog)); +dom.confirmCancel.addEventListener('click', () => { + pendingDeleteId = null; + hideDialog(dom.confirmDialog); +}); +dom.scrim.addEventListener('click', () => { + if (dom.confirmDialog.open) { + pendingDeleteId = null; + hideDialog(dom.confirmDialog); + } else if (dom.dialog.open) { + hideDialog(dom.dialog); + } +}); +document.addEventListener('keydown', (event) => { + if (event.key !== 'Escape') return; + if (dom.confirmDialog.open) { + pendingDeleteId = null; + hideDialog(dom.confirmDialog); + } else if (dom.dialog.open) { + hideDialog(dom.dialog); + } +}); + +dom.confirmOk.addEventListener('click', async () => { + const id = pendingDeleteId; + pendingDeleteId = null; + hideDialog(dom.confirmDialog); + if (!id) return; + try { + const snapshot = await apiRequest('DELETE', `/api/tasks/${encodeURIComponent(id)}`); + applySnapshot(snapshot); + hideError(); + render(); + showToast('任务已删除'); + } catch (error) { + showError(error.message); + } +}); + +document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') { + saveViewState(); + return; + } + void loadTasks(); +}); + +/* ------------------------------------------------------------------ 启动 */ + +loadViewState(); +render(); +void loadTasks(); diff --git a/plugins/alanhean/weekly-planner/miniapp/client/index.html b/plugins/alanhean/weekly-planner/miniapp/client/index.html new file mode 100644 index 00000000..083bf007 --- /dev/null +++ b/plugins/alanhean/weekly-planner/miniapp/client/index.html @@ -0,0 +1,225 @@ + + + + + + 周计划 + + + +
+ + +
+
+ +
+ 本周 + +
+ +
+ +
+ +
+ + +
+ +
+ + + +
+
+ +
+
+

本周进度

+ 正在统计… +
+
+
+

本周任务

+

0

+
+
+

已完成

+

0

+
+
+

完成率

+

0%

+
+
+
+
+
+
    +
    + + + +
    +
    +
    +
    +

    本周

    + +
    +
      + +

      正在加载本机计划…

      +
      + + +
      +
      + + + + +
      +

      新建任务

      +

      记录一件本周要做的事。

      + +
      + + +
      + +
      +
      + + +
      +
      + 优先级 +
      + + + +
      +
      +
      + +
      + + +
      + + + +
      + + +
      +
      +
      + + +

      删除任务

      +

      删除后无法恢复,确认删除这条任务吗?

      +
      + + +
      +
      + + + + + + diff --git a/plugins/alanhean/weekly-planner/miniapp/client/styles.css b/plugins/alanhean/weekly-planner/miniapp/client/styles.css new file mode 100644 index 00000000..3f155361 --- /dev/null +++ b/plugins/alanhean/weekly-planner/miniapp/client/styles.css @@ -0,0 +1,966 @@ +/* 周计划 Mini App — 视觉基线:MiniMax Code 工作台风格 */ + +:root, +[data-theme='light'] { + --mcode-bg: #ffffff; + --mcode-bg-secondary: #f5f5f5; + --mcode-surface: #ffffff; + --mcode-surface-muted: #fafafa; + --mcode-text: #171717; + --mcode-text-muted: #666666; + --mcode-text-subtle: #adadad; + --mcode-border: #0a0a0a14; + --mcode-border-strong: #0a0a0af2; + --mcode-accent: #0094fc; + --mcode-success: #04b54b; + --mcode-warning: #f56811; + --mcode-danger: #f73646; + --mcode-primary-action-bg: #171717; + --mcode-primary-action-text: #ffffff; + --mcode-accent-soft: #e8f4fe; + --mcode-success-soft: #e8f7ee; + --mcode-warning-soft: #fdf1e7; + --mcode-danger-soft: #fdecee; +} + +[data-theme='dark'] { + --mcode-bg: #171717; + --mcode-bg-secondary: #1c1c1c; + --mcode-surface: #262626; + --mcode-surface-muted: #262626; + --mcode-text: #ededed; + --mcode-text-muted: #949494; + --mcode-text-subtle: #666666; + --mcode-border: #ffffff14; + --mcode-border-strong: #fffffff2; + --mcode-accent: #0077d9; + --mcode-success: #009c3d; + --mcode-warning: #e25507; + --mcode-danger: #e31937; + --mcode-primary-action-bg: #ffffff; + --mcode-primary-action-text: #171717; + --mcode-accent-soft: #10273a; + --mcode-success-soft: #14301f; + --mcode-warning-soft: #3a2818; + --mcode-danger-soft: #3a1c20; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme='light']) { + --mcode-bg: #171717; + --mcode-bg-secondary: #1c1c1c; + --mcode-surface: #262626; + --mcode-surface-muted: #262626; + --mcode-text: #ededed; + --mcode-text-muted: #949494; + --mcode-text-subtle: #666666; + --mcode-border: #ffffff14; + --mcode-border-strong: #fffffff2; + --mcode-accent: #0077d9; + --mcode-success: #009c3d; + --mcode-warning: #e25507; + --mcode-danger: #e31937; + --mcode-primary-action-bg: #ffffff; + --mcode-primary-action-text: #171717; + --mcode-accent-soft: #10273a; + --mcode-success-soft: #14301f; + --mcode-warning-soft: #3a2818; + --mcode-danger-soft: #3a1c20; + } +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +[hidden] { + display: none !important; +} + +html, +body { + margin: 0; + padding: 0; +} + +body { + background: var(--mcode-bg-secondary); + color: var(--mcode-text); + font-family: ui-sans-serif, -apple-system, system-ui, 'Segoe UI', Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +.app { + max-width: 1080px; + margin: 0 auto; + padding: 24px 24px 48px; +} + +h1, +h2, +h3, +p, +ul { + margin: 0; +} + +ul { + padding: 0; + list-style: none; +} + +.icon { + width: 16px; + height: 16px; + fill: none; + stroke: currentColor; + stroke-width: 1.8; + stroke-linecap: round; + stroke-linejoin: round; + flex: none; +} + +.icon--lg { + width: 28px; + height: 28px; + stroke-width: 1.5; +} + +/* ---------- 页头 ---------- */ + +.page-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 20px; +} + +.page-title { + font-size: 18px; + line-height: 28px; + font-weight: 600; + letter-spacing: 0.01em; +} + +.page-subtitle { + margin-top: 4px; + color: var(--mcode-text-muted); + font-size: 13px; +} + +/* ---------- 容器 ---------- */ + +.panel { + background: var(--mcode-surface); + border: 1px solid var(--mcode-border); + border-radius: 12px; + padding: 16px 20px; +} + +.panel__head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12px; + margin-bottom: 14px; +} + +.panel__title { + font-size: 16px; + line-height: 24px; + font-weight: 500; +} + +.panel__meta, +.section-meta { + color: var(--mcode-text-muted); + font-size: 12px; +} + +.section-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12px; + padding: 4px 0 12px; +} + +.section-title { + font-size: 16px; + line-height: 24px; + font-weight: 500; +} + +/* ---------- 按钮 ---------- */ + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + height: 36px; + padding: 0 14px; + border: 1px solid transparent; + border-radius: 8px; + background: transparent; + color: var(--mcode-text); + font-family: inherit; + font-size: 14px; + font-weight: 500; + line-height: 1; + cursor: pointer; + transition: background-color 150ms ease-out, border-color 150ms ease-out, color 150ms ease-out; +} + +.btn-sm { + height: 28px; + padding: 0 10px; + font-size: 13px; +} + +.btn-primary { + background: var(--mcode-primary-action-bg); + color: var(--mcode-primary-action-text); +} + +.btn-primary:hover { + opacity: 0.88; +} + +.btn-secondary { + background: var(--mcode-surface-muted); + border-color: var(--mcode-border); + color: var(--mcode-text); +} + +.btn-secondary:hover { + border-color: var(--mcode-border-strong); +} + +.btn-ghost { + color: var(--mcode-text-muted); +} + +.btn-ghost:hover { + color: var(--mcode-accent); + background: var(--mcode-surface-muted); +} + +.btn-danger { + background: var(--mcode-danger); + color: #ffffff; +} + +.btn-danger:hover { + opacity: 0.9; +} + +.btn:focus-visible, +.icon-btn:focus-visible, +.segmented button:focus-visible, +.day-tab:focus-visible, +.icon-action:focus-visible, +.input:focus-visible { + outline: 2px solid var(--mcode-accent); + outline-offset: 1px; +} + +.icon-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface); + color: var(--mcode-text-muted); + cursor: pointer; + transition: background-color 150ms ease-out, color 150ms ease-out; +} + +.icon-btn:hover { + background: var(--mcode-surface-muted); + color: var(--mcode-text); +} + +.icon-action { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: 1px solid transparent; + border-radius: 6px; + background: transparent; + color: var(--mcode-text-subtle); + cursor: pointer; + transition: background-color 150ms ease-out, color 150ms ease-out; +} + +.icon-action:hover { + background: var(--mcode-surface-muted); + color: var(--mcode-text); +} + +.icon-action--danger:hover { + background: var(--mcode-danger-soft); + color: var(--mcode-danger); +} + +/* ---------- 工具栏 ---------- */ + +.toolbar { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; + margin-bottom: 16px; + padding: 12px 20px; +} + +.toolbar__spacer { + flex: 1 1 auto; +} + +.week-nav { + display: flex; + align-items: center; + gap: 8px; +} + +.week-nav__center { + display: flex; + align-items: center; + gap: 4px; +} + +.week-range { + font-size: 14px; + font-weight: 500; + white-space: nowrap; +} + +.segmented { + display: inline-flex; + gap: 2px; + padding: 3px; + background: var(--mcode-surface-muted); + border: 1px solid var(--mcode-border); + border-radius: 8px; +} + +.segmented button { + height: 28px; + padding: 0 12px; + border: 1px solid transparent; + border-radius: 6px; + background: transparent; + color: var(--mcode-text-muted); + font-family: inherit; + font-size: 13px; + line-height: 1; + cursor: pointer; + transition: background-color 150ms ease-out, color 150ms ease-out; +} + +.segmented button:hover { + color: var(--mcode-text); +} + +.segmented button[aria-selected='true'], +.segmented button[aria-pressed='true'] { + background: var(--mcode-surface); + border-color: var(--mcode-border); + color: var(--mcode-text); + font-weight: 500; +} + +/* ---------- 进度面板 ---------- */ + +.progress-panel { + margin-bottom: 16px; +} + +.kpi-row { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 16px; + margin-bottom: 14px; +} + +.kpi { + min-width: 0; +} + +.kpi__label { + color: var(--mcode-text-muted); + font-size: 12px; +} + +.kpi__value { + font-size: 24px; + line-height: 30px; + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.progress-bar { + height: 8px; + border-radius: 999px; + background: var(--mcode-surface-muted); + border: 1px solid var(--mcode-border); + overflow: hidden; +} + +.progress-bar__fill { + height: 100%; + width: 0; + border-radius: 999px; + background: var(--mcode-accent); + transition: width 250ms ease-out; +} + +.progress-bar__fill.is-complete { + background: var(--mcode-success); +} + +.day-distribution { + display: grid; + grid-template-columns: repeat(7, minmax(0, 1fr)); + gap: 10px; + margin-top: 16px; +} + +.dist-item { + display: flex; + flex-direction: column; + gap: 6px; + min-width: 0; +} + +.dist-item__label { + color: var(--mcode-text-muted); + font-size: 12px; + white-space: nowrap; +} + +.dist-item__bar { + display: block; + height: 4px; + border-radius: 999px; + background: var(--mcode-surface-muted); + border: 1px solid var(--mcode-border); + overflow: hidden; +} + +.dist-item__fill { + display: block; + height: 100%; + width: 0; + background: var(--mcode-accent); + transition: width 250ms ease-out; +} + +.dist-item__value { + color: var(--mcode-text-subtle); + font-size: 11px; + font-variant-numeric: tabular-nums; +} + +/* ---------- 日期标签页 ---------- */ + +.day-tabs { + display: flex; + gap: 8px; + overflow-x: auto; + padding-bottom: 14px; + scrollbar-width: thin; +} + +.day-tab { + display: flex; + flex-direction: column; + align-items: center; + gap: 2px; + min-width: 64px; + padding: 8px 10px; + border: 1px solid var(--mcode-border); + border-radius: 10px; + background: var(--mcode-surface); + color: var(--mcode-text-muted); + font-family: inherit; + cursor: pointer; + transition: background-color 150ms ease-out, border-color 150ms ease-out, color 150ms ease-out; +} + +.day-tab:hover { + background: var(--mcode-surface-muted); + color: var(--mcode-text); +} + +.day-tab[aria-selected='true'] { + background: var(--mcode-accent-soft); + border-color: var(--mcode-accent); + color: var(--mcode-text); +} + +.day-tab__weekday { + font-size: 13px; + font-weight: 500; +} + +.day-tab__date { + font-size: 12px; + color: var(--mcode-text-muted); + font-variant-numeric: tabular-nums; +} + +.day-tab[aria-selected='true'] .day-tab__date { + color: var(--mcode-text-muted); +} + +.day-tab__count { + font-size: 11px; + color: var(--mcode-text-subtle); + font-variant-numeric: tabular-nums; +} + +.day-tab__today { + font-size: 10px; + color: var(--mcode-accent); + font-weight: 500; +} + +/* ---------- 任务列表 ---------- */ + +.task-list { + border-top: 1px solid var(--mcode-border); +} + +.task-item { + display: flex; + align-items: flex-start; + gap: 12px; + padding: 12px 2px; + border-bottom: 1px solid var(--mcode-border); +} + +.task-item:last-child { + border-bottom: none; +} + +.task-check { + display: inline-flex; + align-items: center; + padding-top: 2px; +} + +.task-check input { + width: 16px; + height: 16px; + margin: 0; + accent-color: var(--mcode-accent); + cursor: pointer; +} + +.task-body { + flex: 1 1 auto; + min-width: 0; +} + +.task-title { + font-size: 14px; + line-height: 22px; + font-weight: 500; + overflow-wrap: anywhere; +} + +.task-item.is-done .task-title { + color: var(--mcode-text-subtle); + text-decoration: line-through; +} + +.task-meta { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-top: 4px; + color: var(--mcode-text-muted); + font-size: 12px; +} + +.task-note { + color: var(--mcode-text-subtle); + overflow-wrap: anywhere; +} + +.task-actions { + display: flex; + gap: 2px; + flex: none; +} + +.pill { + display: inline-flex; + align-items: center; + height: 20px; + padding: 0 8px; + border: 1px solid transparent; + border-radius: 999px; + font-size: 11px; + line-height: 1; + white-space: nowrap; +} + +.pill--high { + background: var(--mcode-danger-soft); + border-color: var(--mcode-danger); + color: var(--mcode-danger); +} + +.pill--medium { + background: var(--mcode-warning-soft); + border-color: var(--mcode-warning); + color: var(--mcode-warning); +} + +.pill--low { + background: var(--mcode-surface-muted); + border-color: var(--mcode-border); + color: var(--mcode-text-muted); +} + +.pill--done { + background: var(--mcode-success-soft); + border-color: var(--mcode-success); + color: var(--mcode-success); +} + +/* ---------- 整周视图 ---------- */ + +.week-group { + border-top: 1px solid var(--mcode-border); +} + +.week-group:first-child { + border-top: none; +} + +.week-group__head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12px; + padding: 12px 2px 6px; +} + +.week-group__title { + font-size: 14px; + font-weight: 500; +} + +.week-group__meta { + color: var(--mcode-text-subtle); + font-size: 12px; + font-variant-numeric: tabular-nums; +} + +.week-group .task-list { + border-top: none; +} + +.week-group__empty { + padding: 2px 2px 12px; + color: var(--mcode-text-subtle); + font-size: 12px; +} + +/* ---------- 空状态与加载 ---------- */ + +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + padding: 40px 16px; + color: var(--mcode-text-muted); + text-align: center; +} + +.empty-state .icon { + color: var(--mcode-text-subtle); + margin-bottom: 2px; +} + +.empty-state__title { + font-size: 14px; + font-weight: 500; + color: var(--mcode-text); +} + +.empty-state__text { + font-size: 13px; +} + +.loading-state { + padding: 32px 2px; + color: var(--mcode-text-muted); + font-size: 13px; +} + +/* ---------- 提示条 ---------- */ + +.banner { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 10px 12px; + border: 1px solid transparent; + border-radius: 8px; + font-size: 13px; +} + +.banner--error { + background: var(--mcode-danger-soft); + border-color: var(--mcode-danger); + color: var(--mcode-danger); + margin-bottom: 16px; +} + +.banner--notice { + background: var(--mcode-warning-soft); + border-color: var(--mcode-warning); + color: var(--mcode-warning); + margin-bottom: 16px; +} + +/* ---------- 对话框 ---------- */ + +.dialog { + width: min(460px, calc(100vw - 32px)); + padding: 20px; + border: 1px solid var(--mcode-border); + border-radius: 12px; + background: var(--mcode-surface); + color: var(--mcode-text); + box-shadow: 0 0 20px rgb(10 10 10 / 8%); +} + +/* 模态与降级(文档不可见时)两种打开方式都保持居中、可读。 */ +.dialog[open] { + position: fixed; + inset: 0; + margin: auto; + max-height: calc(100vh - 40px); + overflow: auto; + z-index: 30; +} + +.dialog-scrim { + position: fixed; + inset: 0; + background: rgb(10 10 10 / 45%); + z-index: 29; +} + +.dialog::backdrop { + background: rgb(10 10 10 / 45%); +} + +.dialog__title { + font-size: 16px; + line-height: 24px; + font-weight: 600; +} + +.dialog__subtitle { + margin-top: 4px; + color: var(--mcode-text-muted); + font-size: 13px; +} + +.dialog__error { + margin-top: 12px; +} + +.dialog__actions { + display: flex; + justify-content: flex-end; + gap: 8px; + margin-top: 20px; +} + +.field { + display: flex; + flex-direction: column; + gap: 6px; + margin-top: 16px; + min-width: 0; +} + +.field__label { + font-size: 13px; + font-weight: 500; + color: var(--mcode-text); +} + +.field__hint { + color: var(--mcode-text-subtle); + font-size: 12px; + font-weight: 400; +} + +.field-row { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 16px; +} + +.field--date { + max-width: 220px; +} + +.input { + width: 100%; + height: 38px; + padding: 0 10px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface-muted); + color: var(--mcode-text); + font-family: inherit; + font-size: 14px; +} + +textarea.input { + height: auto; + padding: 8px 10px; + line-height: 1.5; + resize: vertical; +} + +.input::placeholder { + color: var(--mcode-text-subtle); +} + +.input:hover { + border-color: var(--mcode-border-strong); +} + +.radio-group { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 16px; + padding: 9px 12px; + background: var(--mcode-surface-muted); + border: 1px solid var(--mcode-border); + border-radius: 8px; + align-self: flex-start; +} + +.radio { + display: inline-flex; + align-items: center; + gap: 6px; + cursor: pointer; + font-size: 14px; + color: var(--mcode-text); +} + +.radio input { + width: 16px; + height: 16px; + margin: 0; + accent-color: var(--mcode-accent); + cursor: pointer; +} + +.radio input:checked + span { + font-weight: 500; +} + +.radio input:focus-visible { + outline: 2px solid var(--mcode-accent); + outline-offset: 2px; +} + +/* ---------- 轻提示 ---------- */ + +.toast { + position: fixed; + left: 50%; + bottom: 24px; + transform: translateX(-50%); + max-width: calc(100vw - 32px); + padding: 10px 16px; + border: 1px solid var(--mcode-border); + border-radius: 10px; + background: var(--mcode-surface); + color: var(--mcode-text); + font-size: 13px; + box-shadow: 0 0 20px rgb(10 10 10 / 8%); + z-index: 20; +} + +/* ---------- 响应式 ---------- */ + +@media (max-width: 768px) { + .app { + padding: 16px 16px 40px; + } + + .page-header { + flex-direction: column; + align-items: stretch; + } + + .page-header .btn-primary { + align-self: flex-start; + } + + .toolbar { + align-items: flex-start; + flex-direction: column; + gap: 10px; + } + + .toolbar__spacer { + display: none; + } + + .kpi-row { + gap: 12px; + } + + .day-distribution { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } + + .field-row { + grid-template-columns: minmax(0, 1fr); + } + + .task-item { + flex-wrap: wrap; + } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + transition-duration: 0.01ms !important; + animation-duration: 0.01ms !important; + } +} diff --git a/plugins/alanhean/weekly-planner/miniapp/miniapp.json b/plugins/alanhean/weekly-planner/miniapp/miniapp.json new file mode 100644 index 00000000..09e839d9 --- /dev/null +++ b/plugins/alanhean/weekly-planner/miniapp/miniapp.json @@ -0,0 +1,32 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/plan", + "window": { + "width": 1080, + "height": 760, + "minWidth": 480, + "minHeight": 360, + "resizable": true, + "frame": true, + "transparent": false, + "alwaysOnTop": false, + "skipTaskbar": false, + "clickThrough": false + } + }, + "mcpEndpoints": [] +} diff --git a/plugins/alanhean/weekly-planner/miniapp/node/miniapp-api.ts b/plugins/alanhean/weekly-planner/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..5276c6f8 --- /dev/null +++ b/plugins/alanhean/weekly-planner/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/alanhean/weekly-planner/miniapp/node/server.mjs b/plugins/alanhean/weekly-planner/miniapp/node/server.mjs new file mode 100644 index 00000000..696ec8dd --- /dev/null +++ b/plugins/alanhean/weekly-planner/miniapp/node/server.mjs @@ -0,0 +1,449 @@ +// @ts-check + +/** + * 周计划 Mini App — Node 运行时。 + * + * Node 是唯一的数据所有者:所有写操作都经过这里的一个领域服务, + * 先原子落盘到 dataDir,再把最新快照返回给页面。页面不保存任何业务数据。 + */ + +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { extname, join } from 'node:path'; +import { randomUUID } from 'node:crypto'; + +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ + +const PRIORITIES = ['high', 'medium', 'low']; +const PRIORITY_RANK = { high: 0, medium: 1, low: 2 }; +const MAX_TITLE = 200; +const MAX_NOTE = 500; +const MAX_BODY_BYTES = 64 * 1024; + +const CONTENT_TYPES = { + '.html': 'text/html; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.webp': 'image/webp', + '.ico': 'image/x-icon', +}; + +class HttpError extends Error { + /** + * @param {number} status + * @param {string} message + */ + constructor(status, message) { + super(message); + this.name = 'HttpError'; + this.status = status; + } +} + +/** + * @param {MiniAppContext} context + * @returns {Promise<{ dispose: () => Promise }>} + */ +export async function start(context) { + const clientDir = join(context.pluginRoot, 'miniapp/client'); + const dataDir = context.dataDir; + const dataFile = join(dataDir, 'tasks.json'); + + await mkdir(dataDir, { recursive: true }); + + /** @type {{ tasks: any[], warning: string | null }} */ + const state = { tasks: [], warning: null }; + await loadState(dataFile, state, context); + + const server = createServer((request, response) => { + handleRequest(request, response, { context, clientDir, dataFile, state }).catch((error) => { + const status = typeof error?.status === 'number' ? error.status : 500; + if (status >= 500) { + context.logger.error('miniapp.request.failed', { + message: String(error?.message ?? error), + }); + } + sendJson(response, status, { + error: status >= 500 ? 'internal_error' : 'invalid_request', + message: + status >= 500 + ? '服务暂时不可用,请稍后重试。' + : String(error?.message ?? '请求无法处理。'), + }); + }); + }); + + await new Promise((resolve, reject) => { + const onError = (error) => reject(error); + server.once('error', onError); + server.listen(context.listen.port, context.listen.host, () => { + server.off('error', onError); + resolve(undefined); + }); + }); + context.logger.info('miniapp.runtime.listening', { taskCount: state.tasks.length }); + + let disposal; + const dispose = () => { + if (disposal) return disposal; + context.signal.removeEventListener('abort', onAbort); + disposal = new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve(undefined))); + }); + return disposal; + }; + const onAbort = () => { + void dispose().catch(() => undefined); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} + +/** + * @param {import('node:http').IncomingMessage} request + * @param {import('node:http').ServerResponse} response + * @param {{ context: MiniAppContext, clientDir: string, dataFile: string, state: { tasks: any[], warning: string | null } }} deps + */ +async function handleRequest(request, response, deps) { + const { context, clientDir, dataFile, state } = deps; + const url = new URL(request.url ?? '/', 'http://miniapp.local'); + const pathname = url.pathname; + const method = request.method ?? 'GET'; + + if (pathname.startsWith('/api/')) { + if (method === 'GET' && pathname === '/api/state') { + sendJson(response, 200, snapshot(state)); + return; + } + + if (method === 'POST' && pathname === '/api/tasks') { + const body = await readJsonBody(request); + const task = createTask(body); + state.tasks.push(task); + await persist(dataFile, state); + sendJson(response, 201, snapshot(state)); + return; + } + + const taskMatch = /^\/api\/tasks\/([A-Za-z0-9_-]{1,64})$/.exec(pathname); + if (taskMatch) { + const id = taskMatch[1]; + if (method === 'PATCH' || method === 'PUT') { + const body = await readJsonBody(request); + const task = updateTask(state, id, body); + await persist(dataFile, state); + sendJson(response, 200, snapshot(state)); + return; + } + if (method === 'DELETE') { + const index = state.tasks.findIndex((item) => item.id === id); + if (index === -1) { + throw new HttpError(404, '任务不存在或已被删除。'); + } + state.tasks.splice(index, 1); + await persist(dataFile, state); + sendJson(response, 200, snapshot(state)); + return; + } + throw new HttpError(405, '不支持的请求方法。'); + } + + throw new HttpError(404, '接口不存在。'); + } + + if (method !== 'GET' && method !== 'HEAD') { + throw new HttpError(405, '不支持的请求方法。'); + } + + const asset = resolveAsset(pathname); + if (!asset) { + sendJson(response, 404, { error: 'not_found', message: '页面不存在。' }); + return; + } + try { + const body = await readFile(join(clientDir, asset)); + response.writeHead(200, { + 'content-type': CONTENT_TYPES[extname(asset).toLowerCase()] ?? 'application/octet-stream', + 'cache-control': 'no-store', + }); + response.end(method === 'HEAD' ? undefined : body); + } catch { + sendJson(response, 404, { error: 'not_found', message: '页面不存在。' }); + } +} + +/** + * 解析页面路径到 client 目录中的扁平文件名,拒绝任何越界路径。 + * @param {string} pathname + * @returns {string | null} + */ +function resolveAsset(pathname) { + let relative = pathname; + if (relative.startsWith('/plan')) relative = relative.slice('/plan'.length); + relative = relative.replace(/^\/+/, ''); + if (relative === '' || relative === '/') return 'index.html'; + if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(relative)) return null; + if (relative.includes('..')) return null; + return relative; +} + +/** + * @param {import('node:http').IncomingMessage} request + * @returns {Promise>} + */ +async function readJsonBody(request) { + const chunks = []; + let size = 0; + for await (const chunk of request) { + size += chunk.length; + if (size > MAX_BODY_BYTES) throw new HttpError(413, '提交的内容过大。'); + chunks.push(chunk); + } + if (!chunks.length) return {}; + const text = Buffer.concat(chunks).toString('utf8'); + let parsed; + try { + parsed = JSON.parse(text); + } catch { + throw new HttpError(400, '提交的内容格式不正确。'); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new HttpError(400, '提交的内容格式不正确。'); + } + return parsed; +} + +/** + * @param {Record} body + * @returns {any} + */ +function createTask(body) { + const title = readTitle(body.title, true); + const date = readDate(body.date, true); + const priority = readPriority(body.priority); + const note = readNote(body.note); + const now = Date.now(); + return { + id: `t_${randomUUID().replace(/-/g, '').slice(0, 16)}`, + title, + date, + priority, + note, + done: false, + createdAt: now, + updatedAt: now, + completedAt: null, + }; +} + +/** + * @param {{ tasks: any[] }} state + * @param {string} id + * @param {Record} body + * @returns {any} + */ +function updateTask(state, id, body) { + const task = state.tasks.find((item) => item.id === id); + if (!task) throw new HttpError(404, '任务不存在或已被删除。'); + + if (typeof body.title === 'string') task.title = readTitle(body.title, false); + if (typeof body.date === 'string') task.date = readDate(body.date, false); + if (body.priority !== undefined) task.priority = readPriority(body.priority); + if (typeof body.note === 'string') task.note = readNote(body.note); + if (typeof body.done === 'boolean') { + task.done = body.done; + task.completedAt = body.done ? Date.now() : null; + } + task.updatedAt = Date.now(); + return task; +} + +/** + * @param {unknown} value + * @param {boolean} required + * @returns {string} + */ +function readTitle(value, required) { + if (typeof value !== 'string') { + if (required) throw new HttpError(400, '请填写任务标题。'); + throw new HttpError(400, '任务标题格式不正确。'); + } + const title = value.trim(); + if (!title) throw new HttpError(400, '任务标题不能为空。'); + if (title.length > MAX_TITLE) throw new HttpError(400, `任务标题不能超过 ${MAX_TITLE} 个字符。`); + return title; +} + +/** + * @param {unknown} value + * @param {boolean} required + * @returns {string} + */ +function readDate(value, required) { + if (typeof value !== 'string' || !isDateKey(value)) { + if (required) throw new HttpError(400, '请选择有效日期。'); + throw new HttpError(400, '日期格式不正确。'); + } + return value; +} + +/** + * @param {unknown} value + * @returns {'high' | 'medium' | 'low'} + */ +function readPriority(value) { + if (value === undefined || value === null || value === '') return 'medium'; + if (typeof value !== 'string' || !PRIORITIES.includes(value)) { + throw new HttpError(400, '优先级取值无效。'); + } + return /** @type {'high' | 'medium' | 'low'} */ (value); +} + +/** + * @param {unknown} value + * @returns {string} + */ +function readNote(value) { + if (typeof value !== 'string') return ''; + return value.trim().slice(0, MAX_NOTE); +} + +/** + * @param {unknown} value + * @returns {boolean} + */ +function isDateKey(value) { + if (typeof value !== 'string') return false; + const matched = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); + if (!matched) return false; + const year = Number(matched[1]); + const month = Number(matched[2]); + const day = Number(matched[3]); + const date = new Date(year, month - 1, day); + return ( + date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day + ); +} + +/** + * @param {{ tasks: any[], warning: string | null }} state + */ +function snapshot(state) { + const tasks = [...state.tasks].sort( + (a, b) => + String(a.date).localeCompare(String(b.date)) || + PRIORITY_RANK[a.priority] - PRIORITY_RANK[b.priority] || + Number(a.createdAt) - Number(b.createdAt), + ); + return { + tasks, + warning: state.warning, + updatedAt: Date.now(), + }; +} + +/** + * @param {string} dataFile + * @param {{ tasks: any[], warning: string | null }} state + * @param {MiniAppContext} context + */ +async function loadState(dataFile, state, context) { + let raw; + try { + raw = await readFile(dataFile, 'utf8'); + } catch (error) { + const code = /** @type {any} */ (error)?.code; + if (code === 'ENOENT') return; + context.logger.warn('miniapp.state.read_failed', { code: String(code ?? 'unknown') }); + state.warning = '本机数据文件暂时无法读取,已按空计划开始。'; + return; + } + + let parsed; + try { + parsed = JSON.parse(raw); + } catch { + const backup = dataFile.replace(/\.json$/, `.corrupt-${Date.now()}.json`); + try { + await rename(dataFile, backup); + } catch { + /* 备份失败时仍继续,不覆盖原文件 */ + } + context.logger.warn('miniapp.state.corrupt', {}); + state.warning = '本机数据文件格式异常,已保留备份文件,计划从空列表开始。'; + return; + } + + const rawTasks = Array.isArray(parsed?.tasks) ? parsed.tasks : []; + const kept = []; + let skipped = 0; + for (const item of rawTasks) { + const normalized = normalizeTask(item); + if (normalized) kept.push(normalized); + else skipped += 1; + } + state.tasks = kept; + if (skipped > 0) { + context.logger.warn('miniapp.state.partial', { skipped }); + state.warning = `有 ${skipped} 条任务数据格式异常,已跳过其余任务。`; + } +} + +/** + * @param {unknown} item + * @returns {any | null} + */ +function normalizeTask(item) { + if (!item || typeof item !== 'object') return null; + const raw = /** @type {Record} */ (item); + if (typeof raw.title !== 'string' || !raw.title.trim()) return null; + if (typeof raw.date !== 'string' || !isDateKey(raw.date)) return null; + const now = Date.now(); + return { + id: typeof raw.id === 'string' && raw.id ? raw.id : `t_${randomUUID().replace(/-/g, '').slice(0, 16)}`, + title: raw.title.trim().slice(0, MAX_TITLE), + date: raw.date, + priority: PRIORITIES.includes(raw.priority) ? raw.priority : 'medium', + note: typeof raw.note === 'string' ? raw.note.slice(0, MAX_NOTE) : '', + done: raw.done === true, + createdAt: Number.isFinite(raw.createdAt) ? Number(raw.createdAt) : now, + updatedAt: Number.isFinite(raw.updatedAt) ? Number(raw.updatedAt) : now, + completedAt: Number.isFinite(raw.completedAt) ? Number(raw.completedAt) : null, + }; +} + +/** + * 原子写:先写同目录临时文件,再重命名覆盖目标文件。 + * @param {string} dataFile + * @param {{ tasks: any[], warning: string | null }} state + */ +async function persist(dataFile, state) { + const tempFile = `${dataFile}.${process.pid}.tmp`; + const payload = JSON.stringify( + { version: 1, updatedAt: Date.now(), tasks: state.tasks }, + null, + 2, + ); + await writeFile(tempFile, `${payload}\n`, 'utf8'); + await rename(tempFile, dataFile); +} + +/** + * @param {import('node:http').ServerResponse} response + * @param {number} status + * @param {unknown} payload + */ +function sendJson(response, status, payload) { + response.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + }); + response.end(JSON.stringify(payload)); +} diff --git a/plugins/alanhean/weekly-planner/package.json b/plugins/alanhean/weekly-planner/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/alanhean/weekly-planner/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +}