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MRy%ipDKxc+#k7En7+RrklI~Sdmo1bg6`PiN0n#CTy2vIV@izrM+Ju?Ht
m|NpbhtN4MXJsYT)XJ&Z(ZtAoneFio_5e83JKbLh*2~7YK=FPVN
literal 0
HcmV?d00001
diff --git a/plugins/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 @@
+
+
+
+
+
+ 周计划
+
+
+
+
+
+
+
+
+
+
+
本周进度
+ 正在统计…
+
+
+
+
+
+
+
+ 加载失败。
+ 重试
+
+
+
+
+
+
+
+
+
+
+
+
+
这一天还没有任务
+
点击右上角“新建任务”,把要做的事情添加进来。
+
+ 正在加载本机计划…
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 删除任务
+ 删除后无法恢复,确认删除这条任务吗?
+
+ 取消
+ 确认删除
+
+
+
+
+
+
+
+
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"
+ }
+}