Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugin): 插件可请用户新建自动化(agent.schedule 加档) (#1715)
Chris Zhang656ef6ceac59
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.tsnew file mode 100644index 0000000000..4ddf7f4fb0--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts@@ -0,0 +1,399 @@+/**+ * scheduleSlot.test — 自动化草稿槽(agent.schedule 加档)的假 deps 单测。+ *+ * 最重要的一条在文件末尾:**这个槽只能开面板,不能建任务**。它没有任何触达调度+ * 存储的依赖 —— 那条约束是本能力的全部安全性所依,必须被测试钉住,不能只靠注释。+ */++import { describe, expect, it, vi } from 'vitest';++import {+ GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_SUGGESTION_MS,+ GHOST_SCHEDULE_DRAFT_NAME_MAX_CHARS,+ GHOST_SCHEDULE_DRAFT_PROMPT_MAX_CHARS,+ type GhostScheduleDraftPush,+ type InstalledGhost,+} from '../../../shared/ghost';+import { GhostScheduleSlot, isMainShellWindowUrl, type ScheduleSlotDeps } from '../scheduleSlot';++function scheduleGhost(+ options: {+ slots?: string[];+ schedule?: boolean;+ enabled?: boolean;+ background?: boolean;+ } = {},+): InstalledGhost {+ const slots = options.slots ?? ['agent', 'tool'];+ const agentNeeds = {+ ...(options.background === true ? { background: true } : {}),+ ...(options.schedule !== false ? { schedule: true } : {}),+ };+ return {+ manifest: {+ schemaVersion: 2,+ id: 'sched-ghost',+ name: '签字门看板',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots,+ ...(Object.keys(agentNeeds).length > 0 ? { agent: agentNeeds } : {}),+ },+ dir: '/fake/sched-ghost',+ enabled: options.enabled ?? true,+ iconDataUrl: 'data:image/png;base64,AAAA',+ } as InstalledGhost;+}++function makeSlot(overrides: Partial<ScheduleSlotDeps> = {}) {+ let clock = 0;+ const pushes: GhostScheduleDraftPush[] = [];+ let seq = 0;+ const deps: ScheduleSlotDeps = {+ getGhost: () => scheduleGhost(),+ sendToWindow: vi.fn((payload: GhostScheduleDraftPush) => {+ pushes.push(payload);+ return true;+ }),+ // 每次调用推进一小时,默认不撞限速;测限速的用例自己注入固定时钟。+ now: () => (clock += 3_600_000),+ newRequestId: () => `req-${++seq}`,+ ...overrides,+ };+ return { slot: new GhostScheduleSlot(deps), deps, pushes };+}++const validReq = {+ name: 'Codex 重置提醒',+ prompt: '检查本机 Codex 重置时间,快到了就调 update_status 写回去。',+};++describe('GhostScheduleSlot 资格审', () => {+ it('声明了 agent 槽 + schedule:true 才放行', () => {+ const { slot, pushes } = makeSlot();+ expect(slot.handleRequest('sched-ghost', validReq)).toEqual({ ok: true });+ expect(pushes).toHaveLength(1);+ });++ it('未装 → PERMISSION_DENIED', () => {+ const { slot } = makeSlot({ getGhost: () => null });+ expect(slot.handleRequest('nope', validReq)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });+ });++ it('已装但停用 → PERMISSION_DENIED', () => {+ const { slot } = makeSlot({ getGhost: () => scheduleGhost({ enabled: false }) });+ expect(slot.handleRequest('sched-ghost', validReq)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });+ });++ it('有 agent 槽但没有 schedule 加档 → PERMISSION_DENIED(仅 background 不够)', () => {+ const { slot } = makeSlot({+ getGhost: () => scheduleGhost({ schedule: false, background: true }),+ });+ expect(slot.handleRequest('sched-ghost', validReq)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });+ });++ it('写了 schedule 但 slots 没有 agent → PERMISSION_DENIED', () => {+ const { slot } = makeSlot({ getGhost: () => scheduleGhost({ slots: ['tool'] }) });+ expect(slot.handleRequest('sched-ghost', validReq)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });+ });+});++describe('GhostScheduleSlot 载荷校验', () => {+ it.each([+ ['非对象载荷', 'nope'],+ ['缺 name', { prompt: 'x' }],+ ['缺 prompt', { name: 'x' }],+ ['name 空白', { name: ' ', prompt: 'x' }],+ ['prompt 空白', { name: 'x', prompt: ' ' }],+ ['intervalMs 非数字', { ...validReq, intervalMs: 'soon' }],+ ['intervalMs 为 0', { ...validReq, intervalMs: 0 }],+ ['intervalMs 为负', { ...validReq, intervalMs: -5 }],+ ['intervalMs 非有限', { ...validReq, intervalMs: Number.POSITIVE_INFINITY }],+ ])('%s → INVALID_REQUEST', (_label, payload) => {+ const { slot, pushes } = makeSlot();+ expect(slot.handleRequest('sched-ghost', payload)).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ expect(pushes).toHaveLength(0);+ });++ it('控制字符被净化;净化后为空 → INVALID_REQUEST', () => {+ const { slot, pushes } = makeSlot();+ expect(+ // 字面控制字符会让整个源文件被 git 判成二进制,这里用转义写法:+ // 源码保持纯 ASCII,运行时才是真的 NUL / BEL。+ slot.handleRequest('sched-ghost', { name: '\u0000\u0007', prompt: 'x' }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });+ expect(pushes).toHaveLength(0);+ });++ it('超长 name / prompt 被截断而不是拒绝', () => {+ const { slot, pushes } = makeSlot();+ const res = slot.handleRequest('sched-ghost', {+ name: 'ん'.repeat(GHOST_SCHEDULE_DRAFT_NAME_MAX_CHARS + 50),+ prompt: 'p'.repeat(GHOST_SCHEDULE_DRAFT_PROMPT_MAX_CHARS + 500),+ });+ expect(res).toEqual({ ok: true });+ expect(pushes[0].name).toHaveLength(GHOST_SCHEDULE_DRAFT_NAME_MAX_CHARS);+ expect(pushes[0].prompt).toHaveLength(GHOST_SCHEDULE_DRAFT_PROMPT_MAX_CHARS);+ });+});++describe('GhostScheduleSlot 频率钳制', () => {+ it('低于 30 分钟的建议被上调,不是被拒', () => {+ const { slot, pushes } = makeSlot();+ expect(slot.handleRequest('sched-ghost', { ...validReq, intervalMs: 60_000 })).toEqual({+ ok: true,+ });+ expect(pushes[0].intervalMs).toBe(GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_SUGGESTION_MS);+ });++ it('高于下限的建议原样透传', () => {+ const { slot, pushes } = makeSlot();+ const twoHours = 2 * 3_600_000;+ slot.handleRequest('sched-ghost', { ...validReq, intervalMs: twoHours });+ expect(pushes[0].intervalMs).toBe(twoHours);+ });++ it('不给建议 → 推送里不带 intervalMs(面板用自己的默认频率)', () => {+ const { slot, pushes } = makeSlot();+ slot.handleRequest('sched-ghost', validReq);+ expect(pushes[0].intervalMs).toBeUndefined();+ });+});++describe('GhostScheduleSlot 骚扰钳制', () => {+ it('间隔内的第二次请求 → RATE_LIMITED', () => {+ const { slot, pushes } = makeSlot({ now: () => 1_000 });+ expect(slot.handleRequest('sched-ghost', validReq)).toEqual({ ok: true });+ expect(slot.handleRequest('sched-ghost', validReq)).toMatchObject({+ ok: false,+ errorCode: 'RATE_LIMITED',+ });+ expect(pushes).toHaveLength(1);+ });++ it('限速按尝试记账:被拒的那次也顺延窗口', () => {+ let now = 0;+ const { slot, pushes } = makeSlot({ now: () => now });+ expect(slot.handleRequest('sched-ghost', validReq)).toEqual({ ok: true });+ now = 10_000; // 仍在 15s 窗口内 → 拒,并把窗口顺延到此刻+ expect(slot.handleRequest('sched-ghost', validReq)).toMatchObject({ ok: false });+ now = 20_000; // 距首次 20s(>15s),但距上次尝试只有 10s → 仍拒+ expect(slot.handleRequest('sched-ghost', validReq)).toMatchObject({+ ok: false,+ errorCode: 'RATE_LIMITED',+ });+ expect(pushes).toHaveLength(1);+ });+});++describe('GhostScheduleSlot 推送内容', () => {+ it('身份由主机按已装清单填,沙箱伪装不了', () => {+ const { slot, pushes } = makeSlot();+ slot.handleRequest('sched-ghost', {+ ...validReq,+ // 沙箱试图自报身份 —— 这些字段一律不该进推送+ ghostId: 'someone-else',+ ghostName: '系统设置',+ iconDataUrl: 'data:image/png;base64,EVIL',+ });+ expect(pushes[0]).toMatchObject({+ ghostId: 'sched-ghost',+ ghostName: '签字门看板',+ iconDataUrl: 'data:image/png;base64,AAAA',+ });+ });++ it('每次请求带独立 requestId(renderer 据此去重,不叠开多个面板)', () => {+ // now 每次调用推进一小时,两次请求都不撞限速。+ const { slot, pushes } = makeSlot();+ slot.handleRequest('sched-ghost', validReq);+ slot.handleRequest('sched-ghost', validReq);+ expect(pushes.map((p) => p.requestId)).toEqual(['req-1', 'req-2']);+ });++ it('没有宿主窗口 → HOST_NOT_READY', () => {+ const { slot } = makeSlot({ sendToWindow: () => false });+ expect(slot.handleRequest('sched-ghost', validReq)).toMatchObject({+ ok: false,+ errorCode: 'HOST_NOT_READY',+ });+ });++ it('日志不留 prompt 正文(只记长度)', () => {+ const info = vi.fn();+ const { slot } = makeSlot({ log: { info, warn: vi.fn() } });+ slot.handleRequest('sched-ghost', { ...validReq, prompt: '这里是用户面前的业务内容' });+ const logged = JSON.stringify(info.mock.calls);+ expect(logged).not.toContain('这里是用户面前的业务内容');+ expect(logged).toContain('promptChars');+ });+});++describe('GhostScheduleSlot 硬约束:只能开面板,不能建任务', () => {+ /**+ * 这条不是"检查我们有没有调错 API",而是**结构性**保证:deps 的形状里就没有任何+ * 能写调度存储的东西。将来有人为了"省一步"给它注入 schedule storage,这个用例会+ * 立刻失败 —— 那一步会把「任务必须由用户亲手保存」这唯一的授权动作绕掉。+ */+ it('deps 里不存在任何创建/写调度的能力', () => {+ const { deps } = makeSlot();+ const keys = Object.keys(deps);+ expect(keys.sort()).toEqual(['getGhost', 'newRequestId', 'now', 'sendToWindow'].sort());+ for (const key of keys) {+ expect(key).not.toMatch(/creat|schedul|storage|insert|save|persist|write/i);+ }+ });++ it('放行时唯一的副作用就是投给一个窗口(不是广播)', () => {+ const sendToWindow = vi.fn(() => true);+ const { slot } = makeSlot({ sendToWindow });+ expect(slot.handleRequest('sched-ghost', validReq)).toEqual({ ok: true });+ // 恰好一次:打断式入口绝不能投多个窗口(#1715 review 同根因三条意见)。+ expect(sendToWindow).toHaveBeenCalledTimes(1);+ });++ /**+ * #1715 review 同根因三条意见(Greptile P1 / Codex P2 / Copilot)的回归:+ * 打断式入口**只能投一个窗口**。装配处的选窗逻辑在 index.ts,这里钉住槽这一侧的+ * 契约——它只调一次 sendToWindow,把"投给谁"整个交给装配处,自己不做任何扇出。+ * 如果将来有人把 deps 改回 broadcast 语义(在一次调用里投多个窗口),+ * 上面「deps 里不存在任何创建/写调度的能力」的键集合断言会先失败。+ */+ it('多窗口场景:一次请求只投递一次,不对窗口做扇出', () => {+ // 假装装配处后面挂着 3 个窗口:槽不该知道、也不该关心有几个。+ const delivered: GhostScheduleDraftPush[] = [];+ const { slot } = makeSlot({+ sendToWindow: (payload) => {+ delivered.push(payload);+ return true;+ },+ });+ expect(slot.handleRequest('sched-ghost', validReq)).toEqual({ ok: true });+ expect(delivered).toHaveLength(1);+ });++ it('没有可投窗口(全部销毁)→ HOST_NOT_READY,不静默丢弃', () => {+ const { slot } = makeSlot({ sendToWindow: () => false });+ expect(slot.handleRequest('sched-ghost', validReq)).toMatchObject({+ ok: false,+ errorCode: 'HOST_NOT_READY',+ });+ });++ /**+ * 钉住**本版**的返回形状:没有任何"任务已创建"的信息。+ * ⚠️ 这不是永久契约 —— 后续版本会引入「任务 ↔ 发起插件」的绑定,插件届时可以查询/+ * 管理**自己绑定的那条**任务(绑定关系即授权边界)。那时本用例需要随新契约调整,+ * 而不是把它当成"插件永远不能知道"的依据。+ */+ it('返回值不携带任何"任务已创建"的信息(拿不到 scheduleId)', () => {+ const { slot } = makeSlot();+ const res = slot.handleRequest('sched-ghost', validReq);+ expect(res).toEqual({ ok: true });+ expect(JSON.stringify(res)).not.toMatch(/scheduleId|created|saved/i);+ });+});++/**+ * 「插件面板聚焦 + 主窗口 + 会话副窗」的顺序不稳定场景(review 第二轮点名要覆盖)。+ *+ * 装配处的选窗规则是:candidates = 全部窗口按判据过滤 → focused 在 candidates 内则用它,+ * 否则取 candidates[0]。这里用判据函数复现那条规则,验证**无论窗口列表顺序如何**,+ * 回落都只会落到真正的主窗口 —— 副窗被判据挡在 candidates 之外,所以它排第几都不影响。+ */+describe('选窗回落:插件面板聚焦时只能落到主窗口', () => {+ const MAIN = 'file:///app/index.html#/cc-agent';+ const SECONDARY = 'file:///app/index.html?secondaryWindow=1&bootSession=s1#/cc-agent';+ const PANEL = 'file:///app/index.html?ghostPanelWindow=codex-reset-planner#/ghost-panel-window';++ /** 复刻 index.ts 装配处的选窗规则(那里拿的是 BrowserWindow,这里用 URL 代表窗口)。 */+ const pick = (all: string[], focused: string | null): string | undefined => {+ const candidates = all.filter((url) => isMainShellWindowUrl(url));+ return focused && candidates.includes(focused) ? focused : candidates[0];+ };++ it.each([+ ['主窗在前', [MAIN, SECONDARY, PANEL]],+ ['副窗在前', [SECONDARY, MAIN, PANEL]],+ ['面板窗在前', [PANEL, SECONDARY, MAIN]],+ ['副窗夹在中间', [PANEL, SECONDARY, MAIN, SECONDARY]],+ ])('%s:focused=插件面板窗 → 回落到主窗口而不是副窗', (_label, all) => {+ expect(pick(all, PANEL)).toBe(MAIN);+ });++ it('focused 本身是主窗口 → 就用它', () => {+ expect(pick([SECONDARY, MAIN, PANEL], MAIN)).toBe(MAIN);+ });++ it('只有副窗与面板窗(没有主窗)→ 无可投窗口,交由装配处回 HOST_NOT_READY', () => {+ expect(pick([SECONDARY, PANEL], PANEL)).toBeUndefined();+ });++ it('多个主窗:focused 不在候选内时取第一个主窗,不随副窗位置漂移', () => {+ const MAIN2 = 'file:///app/index.html#/settings';+ expect(pick([SECONDARY, MAIN, MAIN2], PANEL)).toBe(MAIN);+ expect(pick([SECONDARY, MAIN, MAIN2], MAIN2)).toBe(MAIN2);+ });+});++describe('isMainShellWindowUrl(投给哪个窗口的判据)', () => {+ it.each([+ ['主窗口', 'file:///app/index.html#/cc-agent'],+ ['主窗口带其它 query', 'file:///app/index.html?foo=1#/cc-agent/scheduled'],+ ['dev server', 'http://localhost:5173/#/cc-agent'],+ // 判据取 ==='1',不是 has():带 secondaryWindow=0 的主窗不该被误排除。+ ['主窗口 secondaryWindow=0', 'file:///app/index.html?secondaryWindow=0#/cc-agent'],+ ])('%s → 是主壳窗', (_label, url) => {+ expect(isMainShellWindowUrl(url)).toBe(true);+ });++ it.each([+ // 这两类窗口与 MainLayout 平级,没有草稿订阅、也去不了自动化页。+ ['插件面板独立窗(query)', 'file:///app/index.html?ghostPanelWindow=sign#/ghost-panel-window'],+ ['插件面板独立窗(仅 hash)', 'file:///app/index.html#/ghost-panel-window'],+ ['右侧栏独立窗(query)', 'file:///app/index.html?sidebarWindow=1#/sidebar-window'],+ ['右侧栏独立窗(仅 hash)', 'file:///app/index.html#/sidebar-window'],+ // utility 窗:统一带 ?view=<名字>,一律接不住草稿(review 第三轮)。+ ['语音浮窗', 'file:///app/index.html?view=voice-input-overlay'],+ ['词典 toast', 'file:///app/index.html?view=voice-input-dictionary-toast'],+ ['权限引导窗', 'file:///app/index.html?view=computer-permission-guide'],+ ['权限引导 backdrop', 'file:///app/index.html?view=computer-permission-backdrop'],+ // 按 key 排除而非枚举取值:将来任何新 utility 窗只要沿用 ?view= 约定就自动落在排除侧。+ ['将来某个未知的 utility 窗', 'file:///app/index.html?view=some-future-window'],+ // 插件沙箱窗用自定义 scheme 加载插件内容,被协议判据挡掉 —— 主机 UI 事件不该推给插件。+ ['插件沙箱窗(自定义协议)', 'cindy-ghost://codex-reset-planner/__boot__'],+ // 会话副窗:挂完整壳、技术上接得住,但不是用户建任务时看的窗口(review 第二轮)。+ ['会话副窗(secondaryWindow=1)', 'file:///app/index.html?secondaryWindow=1#/cc-agent'],+ ['会话副窗带 bootSession', 'file:///app/index.html?secondaryWindow=1&bootSession=abc#/cc-agent/x'],+ ['about:blank', 'about:blank'],+ ['空串', ''],+ ['非法 URL', 'not a url'],+ ])('%s → 不是主壳窗', (_label, url) => {+ expect(isMainShellWindowUrl(url)).toBe(false);+ });++ /**+ * 这条是本能力的主使用路径:编写手册 §4.11.2 第 1 步就是「用户在你的插件面板上+ * 点一下」,而面板可以被拉成独立窗口。那一刻 focused 是面板窗——若判据把它当成+ * 可投窗口,草稿就投给了一个接不住它的窗口,用户点了什么都不会发生。+ */+ it('插件面板独立窗绝不能被当作可投窗口(本能力的主使用路径)', () => {+ expect(isMainShellWindowUrl('file:///app/index.html?ghostPanelWindow=codex-reset-planner#/ghost-panel-window')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 24f4ce3a58..885271eba9 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1182,6 +1182,9 @@ Claude Code 与 Codex 都能发现,见 §4.16)、\`workspace\`(请主机为项要把任务交给 Agent 干并**取回结果**(而不是发进用户的会话),另写\`"agent": { "errand": true }\`(可与 background 并存),见 §4.11.1;同样是装入确认框单列的高风险档。+要请用户新建一条**自动化**(让插件里的内容定期自己刷新),另写+\`"agent": { "schedule": true }\`(可与前两项并存),见 §4.11.2。它只能打开预填好的+创建面板,任务由用户选好模型后亲手保存才存在;装入确认框单列一档。**node 工作进程详单**(声明 node 槽时必写,详见 §4.12):@@ -2627,6 +2630,79 @@ const q = await cindy.agent.queryErrand({ jobId: r.jobId });超时有 \`'TIMEOUT'\`(任务可能仍在会话里继续,提示用户打开会话查看)。- 这个能力必然产生模型费用且耗时分钟级:能用快问快答(§4.0.2)解决的,不要派活。+### 4.11.2 请用户新建一条自动化(agent.schedule 加档)++**这是"让插件里的内容自己保持新鲜"的正路。** 你的插件自己跑不了业务逻辑——沙箱只在+被唤起时活着,也没有定时器。要做出「每小时帮我看一眼,有事就点亮插件入口」这种效果,+正确的分工是:++ 插件不是执行者,而是**定时任务的目标**。执行者是 Cindy 的 AI。++完整回路(以「Codex 重置提醒」为例):++1. 用户在你的面板上点一个选项,比如「重置时间快到了提醒我」;+2. 你调 \`cindy.agent.requestSchedule(...)\`,请主机**打开预填好的新建自动化面板**;+3. 用户在面板上选个模型(或就用默认)→ **亲手点保存**。任务这才存在;+4. 到点了,Cindy 起一轮 AI 去干活:查本机重置时间、看 X 上的相关发帖、**判断**要不要+ 提醒——这些判断是 AI 做的,不是你做的;+5. 那一轮 AI **调用你申报的 tool**(§3)把结果交给你,你在 tool 里更新自己的数据;+6. 你顺手发一个未读角标(§4.9.1),用户的插件入口和图标上就亮起点;+7. 用户回来点开面板,看到刷新后的内容。++所以你需要的是三样东西的组合:\`agent.schedule\` 加档(第 2 步)+ 一个 \`tool\`(第 5 步)++ \`badge\` 槽(第 6 步)。三者缺一,回路就断在那里。++需声明 \`"slots": [..., "agent", "tool", "badge"]\` + \`"agent": { "schedule": true }\`+(装入确认里单列一档,文案会告诉用户"任务由你亲手保存、跑起来会产生模型费用")。++\`\`\`js+// 用户在面板上点了「提醒我」之后:+const r = await cindy.agent.requestSchedule({+ name: 'Codex 重置提醒', // 预填的自动化名称(≤60 字)+ prompt: [ // 到点了让 AI 干什么——用自然语言写清楚,+ '检查本机 Codex 的限额重置时间。', // 包含"什么情况下才值得提醒我"+ '再看一眼 X 上 @tobi 最近有没有相关发帖。',+ '如果重置时间在 2 小时内,调用 codex-reset-planner 插件的 update_status 工具',+ '把最新状态写回去;否则什么都不用做。',+ ].join('\\n'), // (≤2000 字)+ intervalMs: 60 * 60 * 1000, // 可选:建议每小时一次。**最小 30 分钟**,+ // 低于此值主机会自动上调+});+// { ok: true } = 请求已被接受并投递(**不保证面板真开了,更不代表用户存了**)+// { ok:false, errorCode:'PERMISSION_DENIED' | 'INVALID_REQUEST'+// | 'RATE_LIMITED' | 'HOST_NOT_READY' | 'INTERNAL', message }+\`\`\`++主机强制的边界(都不是建议):++- **你只能打开面板,不能创建任务。** 没有任何"直接建一条自动化"的接口——主机这一侧+ 压根没接调度存储,不是"忍着不用"。用户不点保存,什么都不会发生;+- **本版没有回执。** \`ok:true\` 只表示请求被接受并投递给了主壳窗口:用户当时可能正开着+ 另一个自动化表单在编辑,那种情况下本次草稿会被**丢弃**(保护他没保存的输入),他看到+ 一句提示、面板不换内容。即使面板正常打开,任务也要他亲手点保存才落库。所以你的 UI+ **不要**显示"已开启"这类完成态,写"已为你打开创建面板,请确认"才准确;+ 想确认用户是否照做了,当前唯一可信的信号是任务真的跑起来调了你的 tool。+ **后续版本会补上**:任务与发起插件的**绑定关系**,以及你查询 / 管理**自己绑定的那条+ 任务**(是否有效、下次运行时间、频率,以及改时间 / 暂停 / 关掉)。届时你就能在自己面板+ 上显示"已开启 · 每小时 · 下次 15:00"并让用户就地改。绑定本身即授权边界:你只能看和改+ 自己请求创建的那条,看不到用户的其它自动化;+- \`prompt\` 里要**自己说清楚该调你哪个工具**(见上面示例第 3 行)。AI 不会自动猜到+ "跑完要更新哪个插件";+- 预填内容会**净化 + 截断**(去控制字符,名称 60 字 / prompt 2000 字);净化后为空一律+ \`INVALID_REQUEST\`;+- \`intervalMs\` 低于 **30 分钟**会被自动上调。这不是权限闸门(用户自己在面板上改成+ 1 分钟是他的自由),是不让你预填出一个每分钟烧一次模型额度的任务;+- 同一插件两次请求至少隔 **15 秒**(\`RATE_LIMITED\`)。这个面板是打断式的——它会把+ 用户从当前页带到自动化页,别拿它刷屏;+- 面板上会显示**是你在请求**(插件名由主机填,你伪装不了),用户永远知道在替谁保存;+- **面板会开在主窗口**,不是你的面板窗。用户把你的面板拉成独立窗口后点这个入口时,+ 创建表单出现在主窗口里(独立面板窗挂的是轻壳,承载不了自动化页)——文案上别写+ "将在此处打开",写"去自动化页确认"之类更准;+- 一个都没有主窗口时(极端情况)→ \`HOST_NOT_READY\`。++什么时候**不该**用它:一次性的、当场就要结果的事,用快问快答(§4.0.2)或派活取件+(§4.11.1)。这个加档是给"长期定期刷新"用的,每条任务都会反复产生模型费用。+## 4.12 随包 Node 工作进程与 stdio MCP(node 槽)\`main.js\` 永远还是浏览器沙箱代码。声明 node 槽后,主机额外为**这一段意识**按需@@ -3257,7 +3333,7 @@ if (r.ok && r.confirmed) {- panel.systemButtons 格式错(不是对象、未知键、值非布尔,或 position:"tab" 时声明——插件页内面板没有标准头)- keywords(已废弃字段,旧包兼容保留,新意识别写)有单字词 · kind 写了但不是 "chip"(可省略) · schemaVersion 不是 2- cindy 详单格式错(未知类目/动作、空数组、有详单但 slots 没有 "cindy")-- agent 详单格式错(有详单但 slots 没有 "agent",或 background / errand 都不是 true;只需点击触发时应省略 agent 字段)+- agent 详单格式错(有详单但 slots 没有 "agent",或 background / errand / schedule 都不是 true;只需点击触发时应省略 agent 字段)- node 详单格式错(槽/详单不成对、entry 不是包内 CommonJS .js/.cjs、protocol 不在 json-rpc-stdio / mcp-stdio、写了 command/args/shell/env、resident 又写 idleTimeoutSeconds)- id 用了 \`cindy-\` / \`filo-\` / \`xd-\` 前缀(官方保留,正式版用户通道拒装;给自己的意识换个前缀)diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex c272691a6c..2666f8033a 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -168,6 +168,7 @@ import { GhostNodeRuntimeBroker } from './nodeRuntimeBroker.js';import { GhostPickSlot } from './pickSlot.js';import { recordGhostPickedDir } from './pickGrantsStore.js';import { GhostPreviewSlot } from './previewSlot.js';+import { GhostScheduleSlot, isMainShellWindowUrl } from './scheduleSlot.js';import { GhostWorkspaceSlot, type WorkspaceSessionService } from './workspaceSlot.js';import type { GhostTrustRegistry } from './ghostSignature.js';import { GhostNotifySlot, sanitizeGhostNoticeText } from './notifySlot.js';@@ -2293,6 +2294,58 @@ export function getGhostPreviewSlot(): GhostPreviewSlot {return previewSlotSingleton;}+let scheduleSlotSingleton: GhostScheduleSlot | null = null;++/** 插件自动化草稿通道(main → **单个**窗口;renderer 开自动化创建面板并预填)。 */+export const GHOST_SCHEDULE_DRAFT_CHANNEL = 'ghosts:schedule-draft';++/**+ * 自动化草稿槽单例(agent 槽的 schedule 加档):资格审/净化/频率钳制/限速在+ * GhostScheduleSlot,这里只组装"投给哪个窗口"。+ *+ * 只投**一个**窗口(focused ?? 第一个),与 confirm / pick 同纪律,**不像 notify /+ * preview 那样广播**:本操作是打断式的 —— renderer 收到会把该窗口导航到自动化页+ * 并弹出创建面板。"在新窗口打开"的会话副窗同样挂载完整 MainLayout、各自持有独立+ * 的 requestId 去重状态,所以广播会让主窗与每个副窗同时跳页弹表单:打断其它窗口+ * 里没保存的内容,还让同一份草稿被重复保存成多条自动化(#1715 review:Greptile P1 /+ * Codex P2 / Copilot 同根因)。状态同步类事件(notify / badge / preview 开标签)才+ * 适合广播,打断式的模态入口一律单投。+ *+ * 没有可投窗口(全部销毁 / 一个都没有)→ 返回 false → 槽回 HOST_NOT_READY,+ * 插件收到明确失败而不是静默丢弃。+ *+ * ⚠️ deps 里**刻意不注入任何建任务的能力** —— 本槽只能开面板,任务必须由用户+ * 在面板上选模型后亲手保存。别为了"省一步"给它接 schedule storage。+ */+export function getGhostScheduleSlot(): GhostScheduleSlot {+ if (!scheduleSlotSingleton) {+ scheduleSlotSingleton = new GhostScheduleSlot({+ getGhost: findAvailableGhost,+ sendToWindow: (payload) => {+ // 候选只取**挂了完整主壳**的窗口:独立的插件面板窗 / 右侧栏窗与 MainLayout+ // 平级,没有这个订阅也去不了自动化页(判据见 isMainShellWindowUrl)。+ // isDestroyed 两路都兜:getFocusedWindow 理论上不返回已销毁的窗,但窗口关闭+ // 与本次投递之间存在时序窗口。+ const candidates = BrowserWindow.getAllWindows().filter(+ (window) => !window.isDestroyed() && isMainShellWindowUrl(window.webContents.getURL()),+ );+ const focused = BrowserWindow.getFocusedWindow();+ // 用户正在插件面板独立窗里点「提醒我」时 focused 不在候选里 —— 回落到第一个+ // 主壳窗(通常就是主窗口),用户会在那里看到弹出的创建面板,而不是什么都没发生。+ const win =+ focused && !focused.isDestroyed() && candidates.includes(focused)+ ? focused+ : candidates[0];+ if (!win) return false;+ win.webContents.send(GHOST_SCHEDULE_DRAFT_CHANNEL, payload);+ return true;+ },+ log,+ });+ }+ return scheduleSlotSingleton;+}+/*** 模型槽单例:意识借主机 AI 出图的代办窗口。* 生成走主机统一图片通道(art 底层客户端,与聊天画图同一条付费链路);@@ -4263,6 +4316,12 @@ export function registerGhostIpc(): void {if (type === 'preview-request') {return getGhostPreviewSlot().handleRequest(id, payload);}+ // schedule-request = 打开自动化创建面板并预填(agent 槽的 schedule 加档):+ // 只开面板,任务由用户选模型后亲手保存才落库——本槽全程不碰 schedule storage。+ // 资格审/净化/频率钳制/限速在 scheduleSlot,落地在 renderer。+ if (type === 'schedule-request') {+ return getGhostScheduleSlot().handleRequest(id, payload);+ }if (type === 'card-update') {// 卡槽③供片:校验链(归属/卡槽/限速/净化)在 cardService,拒绝原因// 只进日志,恒回 { ok: true }(与 tool-result 同纪律,不给沙箱探测面)。diff --git a/apps/desktop/src/main/cindy-brain/scheduleSlot.ts b/apps/desktop/src/main/cindy-brain/scheduleSlot.tsnew file mode 100644index 0000000000..3e9626e07b--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/scheduleSlot.ts@@ -0,0 +1,222 @@+/**+ * scheduleSlot.ts — 自动化草稿槽(agent 槽的 schedule 加档,2026-08-04)。+ * ---------------------------------------------------------------------------+ * 插件经管子上行 `{type:'schedule-request', name, prompt, intervalMs?}`,请主机+ * **打开自动化创建面板并预填**。典型用法:插件在自己面板上给用户一个「提醒我+ * Codex 重置时间快到了」之类的选项,用户点了就跳到自动化面板,选个模型点保存。+ *+ * 安全模型 —— 一句话:**它只能开面板,不能建任务。**+ *+ * - 资格审:已装、启用、声明 'agent' 槽 **且** `agent.schedule === true`;+ * - 授权动作 = 用户在自动化面板上**亲手点保存**。本槽全程不碰 schedule storage+ * (deps 里压根没有建任务的能力,不是"忍着不调"——是给不了),所以不存在+ * "插件偷偷给自己排一条后台任务"的面。用户不保存,什么都不会发生;+ * - 本版**没有回执**:返回值只表示"请求已被接受并投递给主壳窗口"。它不保证面板真+ * 打开了(用户正开着另一个表单编辑时,本次草稿会被丢弃以保护他没保存的输入),+ * 更不表示任务已创建。插件 UI 因此不该显示"已开启"这类完成态。+ * 任务与发起插件的**绑定关系**、以及插件查询/管理自己绑定的那条任务(有效性、+ * 下次运行时间、频率、改时间/暂停/关掉)由后续版本提供 —— 绑定本身即授权边界:+ * 插件只能看和改它自己请求创建的那条;+ * - 身份不信自报:面板上显示的插件名/图标由主机按已装清单填;+ * - 文本净化 + 截断:name / prompt 都过 sanitizeGhostNoticeText(去控制字符),+ * 再按上限截断——预填内容会进用户的表单,不允许塞控制字符或超长正文;+ * - 频率钳制:插件建议的 intervalMs 一律不低于 30 分钟。这不是权限闸门(用户+ * 自己在面板上改成 1 分钟是他的自由),是防插件预填出一个每分钟烧一次模型+ * 额度的任务、而用户点保存时未必看清频率;+ * - 骚扰钳制:同一插件两次请求最小间隔 GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_MS+ * (按尝试记账,spam 顺延窗口)。比 preview 长一档 —— 这个面板是打断式的+ * (把用户从当前页带走),预览标签只是右侧栏多开一页。+ *+ * 纯逻辑 + 依赖注入(规则 14):选窗与投递在 cindy-brain/index.ts 组装时注入,+ * 单测喂假 deps 直测。+ */++import { randomUUID } from 'node:crypto';++import {+ GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_MS,+ GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_SUGGESTION_MS,+ GHOST_SCHEDULE_DRAFT_NAME_MAX_CHARS,+ GHOST_SCHEDULE_DRAFT_PROMPT_MAX_CHARS,+ type GhostPipeScheduleDraftResult,+ type GhostScheduleDraftPush,+ type InstalledGhost,+} from '../../shared/ghost.js';+import { sanitizeGhostNoticeText } from './notifySlot.js';++export interface ScheduleSlotDeps {+ getGhost(id: string): InstalledGhost | null;+ /**+ * 把"开面板并预填"投给**单个**宿主窗口;false = 没有可投窗口(HOST_NOT_READY)。+ *+ * 刻意叫 sendToWindow 而不是 broadcast(与 confirm 槽同名):本操作是打断式的,+ * 广播出去会让主窗与每个"在新窗口打开"的副窗同时跳页弹表单——那些副窗同样挂载+ * 完整 MainLayout、各自持有独立的 requestId 去重状态,于是同一份草稿会被重复+ * 保存成多条自动化。装配处负责选窗(focused ?? 第一个),本槽只管投一次。+ */+ sendToWindow(payload: GhostScheduleDraftPush): boolean;+ now?(): number;+ /** 仅测试注入;生产用 randomUUID。 */+ newRequestId?(): string;+ log?: {+ info: (msg: string, meta?: Record<string, unknown>) => void;+ warn: (msg: string, meta?: Record<string, unknown>) => void;+ };+}++function fail(+ errorCode: Extract<GhostPipeScheduleDraftResult, { ok: false }>['errorCode'],+ message: string,+): GhostPipeScheduleDraftResult {+ return { ok: false, errorCode, message };+}++/**+ * 该窗口是否是**能承载自动化页的主窗口**。投给别的窗口要么静默丢失,要么落错地方。+ *+ * ⚠️ 本判据被 review 连着推了三轮(面板窗 → 会话副窗 → utility 窗),所以这一版**按+ * 窗口约定收口,不再逐个枚举**:main 侧全部 `new BrowserWindow` 的位置只有 7 处+ * (secondary-windows / bootstrap / 插件沙箱 / ghost-panel-window /+ * right-sidebar-window / computer-permission-guide / voice-input),下面四条把它们+ * 全覆盖了,**只有 bootstrap 建的主窗口不带任何标识** —— 新增窗口类型只要沿用现有+ * 约定(utility 窗带 `?view=`),就自动落在排除侧,不需要再改这里。+ *+ * 1. **协议**只认 app 真实页面(file / http(s))。顺带挡住两类:`about:blank`(窗口刚建+ * 还没 load,它本身是合法 URL 且不带任何标识,不显式挡会被误判);以及**插件沙箱+ * 窗** —— 它用自定义 scheme 加载插件内容(runtime/electronSandboxAdapter.ts),+ * 往那边推主机 UI 事件本就不该发生。+ * 2. **utility 窗**统一带 `?view=<名字>`:语音浮窗 `voice-input-overlay`、词典 toast+ * `voice-input-dictionary-toast`、权限引导 `computer-permission-guide` 与它的+ * backdrop。这里按 **`view` 这个 key** 排除而不是枚举取值 —— 它是 app 的 utility+ * 窗约定,枚举取值就等着下一个新窗口再漏一次(review 第三轮)。+ * 3. **插件面板独立窗**(`?ghostPanelWindow=<id>`)与**右侧栏独立窗**(`?sidebarWindow=1`):+ * 与 MainLayout **平级**(router.tsx 两条根路由),只挂轻壳,**没有草稿订阅、也去不了+ * 自动化页** → 投过去静默丢失。而插件面板恰恰可以被用户拉成独立窗口,「在插件面板+ * 上点一下」正是本能力的主使用路径(编写手册 §4.11.2 第 1 步)——那一刻 focused 就是+ * 面板窗,若照 confirm 槽那样只写 `focused ?? all[0]` 就丢了。hash 两路也查,兜底。+ * 4. **「在新窗口打开」的会话副窗**(`?secondaryWindow=1`,main/secondary-windows.ts):+ * 它**挂的是完整 MainLayout**(有订阅、技术上接得住),但它是用户为某个会话单独开的+ * 窗口。回落时把创建面板弹进它 = 落错地方:用户以为在主窗口建任务,主窗口却什么也+ * 没发生,而某个会话副窗被劫持去开自动化页。**能接住 ≠ 该接住**。+ *+ * 纯函数(只收 URL 字符串,不碰 Electron),便于直测。+ */+export function isMainShellWindowUrl(rawUrl: string): boolean {+ if (!rawUrl.trim()) return false;+ let parsed: URL;+ try {+ parsed = new URL(rawUrl);+ } catch {+ // 尚未 load 完的空串 / 非法值:不当主壳窗,宁可回落到别的候选。+ return false;+ }+ // 只认 app 真实页面的协议。`about:blank`(窗口刚建还没 load)本身是合法 URL、+ // 也不带下面那些标识,不显式挡掉会被误判成主壳窗,草稿投过去即丢失。+ if (parsed.protocol !== 'file:' && parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ return false;+ }+ if (+ // utility 窗的统一约定:按 key 排除,不枚举取值(见上方第 2 条)。+ parsed.searchParams.has('view') ||+ parsed.searchParams.has('ghostPanelWindow') ||+ parsed.searchParams.has('sidebarWindow') ||+ // 会话副窗:挂完整壳、技术上接得住,但它不是用户建任务时看的那个窗口。+ // 取 === '1' 而不是 has():带 secondaryWindow=0 的主窗不该被误排除。+ parsed.searchParams.get('secondaryWindow') === '1'+ ) {+ return false;+ }+ const hash = parsed.hash;+ if (hash.includes('/ghost-panel-window') || hash.includes('/sidebar-window')) return false;+ return true;+}++/** 自动化草稿槽:资格审 → 载荷净化 → 频率钳制 → 限速 → 投给单个窗口开面板。 */+export class GhostScheduleSlot {+ /** 意识 id → 上次尝试时刻(按尝试记账;体量 = 已装意识数,无需清理)。 */+ private readonly lastAttemptAt = new Map<string, number>();++ constructor(private readonly deps: ScheduleSlotDeps) {}++ handleRequest(ghostId: string, payload: unknown): GhostPipeScheduleDraftResult {+ const ghost = this.deps.getGhost(ghostId);+ if (+ !ghost?.enabled ||+ !ghost.manifest.slots.includes('agent') ||+ ghost.manifest.agent?.schedule !== true+ ) {+ return fail(+ 'PERMISSION_DENIED',+ '插件未申请「可以请你新建自动化任务」权限(agent 槽的 schedule 加档),或当前未启用',+ );+ }+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {+ return fail('INVALID_REQUEST', 'schedule-request 载荷必须是对象');+ }+ const request = payload as Record<string, unknown>;+ if (typeof request.name !== 'string' || request.name.trim().length === 0) {+ return fail('INVALID_REQUEST', 'name 必填且必须是非空字符串(预填的任务名)');+ }+ if (typeof request.prompt !== 'string' || request.prompt.trim().length === 0) {+ return fail(+ 'INVALID_REQUEST',+ 'prompt 必填且必须是非空字符串(这条任务到点要干什么,用自然语言写)',+ );+ }+ if (request.intervalMs !== undefined) {+ if (typeof request.intervalMs !== 'number' || !Number.isFinite(request.intervalMs)) {+ return fail('INVALID_REQUEST', 'intervalMs 必须是有限数字(毫秒)');+ }+ if (request.intervalMs <= 0) {+ return fail('INVALID_REQUEST', 'intervalMs 必须大于 0');+ }+ }++ const name = sanitizeGhostNoticeText(request.name).slice(0, GHOST_SCHEDULE_DRAFT_NAME_MAX_CHARS);+ const prompt = sanitizeGhostNoticeText(request.prompt).slice(+ 0,+ GHOST_SCHEDULE_DRAFT_PROMPT_MAX_CHARS,+ );+ // 净化后可能只剩空白(全是控制字符/空格)——那等于没给,如实拒而不是推一个空面板。+ if (!name || !prompt) {+ return fail('INVALID_REQUEST', 'name / prompt 净化后为空');+ }++ // 限速按尝试记账:spam 会不断顺延窗口,对真实节奏(用户点一下)无感。+ const now = this.deps.now?.() ?? Date.now();+ const last = this.lastAttemptAt.get(ghostId);+ this.lastAttemptAt.set(ghostId, now);+ if (last !== undefined && now - last < GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_MS) {+ return fail('RATE_LIMITED', '打开自动化面板的请求太频繁,稍后再试');+ }++ // 频率建议只上调不下调(见文件头注释)。+ const intervalMs =+ typeof request.intervalMs === 'number'+ ? Math.max(+ Math.floor(request.intervalMs),+ GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_SUGGESTION_MS,+ )+ : undefined;++ const delivered = this.deps.sendToWindow({+ requestId: this.deps.newRequestId?.() ?? randomUUID(),+ ghostId,+ ghostName: ghost.manifest.name,+ ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),+ name,+ prompt,+ ...(intervalMs !== undefined ? { intervalMs } : {}),+ });+ if (!delivered) {+ return fail('HOST_NOT_READY', '当前没有可用的宿主窗口');+ }+ this.deps.log?.info('ghost schedule draft requested', {+ ghostId,+ intervalMs: intervalMs ?? null,+ // 只记长度不记正文:预填 prompt 是用户面前的业务内容,日志里没必要留副本。+ promptChars: prompt.length,+ });+ return { ok: true };+ }+}diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.tsindex 1b46212c4f..691196a572 100644--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@ -65,6 +65,13 @@ contextBridge.exposeInMainWorld('cindy', {ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'agent-errand-request', kind: 'run' }),queryErrand: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'agent-errand-request', kind: 'query' }),+ // 请用户新建一条自动化(agent.schedule 加档):只能**打开预填好的创建面板**,+ // 建不建由用户在面板上选好模型后亲手保存。{ ok:true } 只表示"请求已被接受并投递",+ // 既不保证面板真开了(用户正编辑另一个表单时本次草稿会被丢弃),也不表示任务已创建+ // ——本版没有回执通道,绑定与查改由后续版本提供(语义见 GhostPipeScheduleDraftResult)。+ // 资格审 / 净化 / 频率钳制 / 限速都在主机 scheduleSlot。+ requestSchedule: (req: Record<string, unknown>): Promise<unknown> =>+ ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'schedule-request' }),},node: {request: (req: Record<string, unknown>): Promise<unknown> =>diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex f14ef8d9fb..a5f7d309a7 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -499,6 +499,8 @@ const fanOutGhostUnreadSnapshot = createIpcFanOut('ghosts:unread-snapshot');const fanOutGhostConfirmRequest = createIpcFanOut('ghosts:confirm-request');// 插件预览开页(preview 槽:renderer 在右侧栏开 web-browser 标签)。const fanOutGhostPreviewOpen = createIpcFanOut('ghosts:preview-open');+// 插件自动化草稿(agent 槽 schedule 加档:renderer 开自动化创建面板并预填)。+const fanOutGhostScheduleDraft = createIpcFanOut('ghosts:schedule-draft');const fanOutVoiceInputModifierShortcutKeys = createIpcFanOut('voice-input:modifier-shortcut-keys');// 「待授权」快捷键在设置页之外自动恢复失败(helper 起不来)。设置页不在,它的 toast 也就// 不在,所以由常挂载的 MainLayout 接这条并提示。main 侧一次 App 运行只推一次。@@ -1068,6 +1070,7 @@ contextBridge.exposeInMainWorld('electronAPI', {resolveConfirm: (requestId: string, confirmed: boolean): Promise<{ handled: boolean }> =>ipcRenderer.invoke('ghosts:confirm:resolve', { requestId, confirmed }),onPreviewOpen: fanOutGhostPreviewOpen,+ onScheduleDraft: fanOutGhostScheduleDraft,getCard: (callId: string,): Promise<{diff --git a/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts b/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.tsindex 446cf0bc2d..2fc6ee453b 100644--- a/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts+++ b/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts@@ -11,8 +11,16 @@ import {systemTimeZone,usageLimitScheduleNavigationState,} from '@/features/scheduler/lib/usageLimitScheduleCreateIntent';+import { pluginScheduleNavigationState } from '@/features/scheduler/lib/pluginScheduleCreateIntent';const createSchedule = vi.fn();+const toastMocks = vi.hoisted(() => ({+ success: vi.fn(),+ warning: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+}));+vi.mock('@/lib/toast', () => ({ toast: toastMocks }));const localStorageData = new Map<string, string>();const routerMocks = vi.hoisted(() => ({location: {@@ -148,6 +156,15 @@ vi.mock('@/hooks/useAgentCapabilities', () => ({efforts: ['medium', 'high'],defaultEffort: 'medium',},+ // 第二个模型专供「所见即所存」那条用例:它需要一个**不等于 fallback**+ // (claude-sonnet-4-6)、又确实在可用目录里的模型 —— 否则要么测不出问题,+ // 要么被 isExplicitScheduleModelUnavailable 拦在提交前。+ {+ id: 'claude-opus-4-9',+ displayName: 'Claude Opus 4.9',+ efforts: ['medium', 'high'],+ defaultEffort: 'medium',+ },],hasFastMode: false,},@@ -303,4 +320,134 @@ describe('Scheduler template entry', () => {expect(screen.getByTestId('agent-kind').textContent).toBe('claude-code');expect(createSchedule).not.toHaveBeenCalled();});++ it('插件请求打开预填的创建表单,但不创建任务', async () => {+ routerMocks.location.state = pluginScheduleNavigationState({+ kind: 'plugin-schedule-draft',+ requestId: 'plugin-req-1',+ ghostId: 'codex-reset-planner',+ ghostName: 'Codex 重置管家',+ name: 'Codex 重置提醒',+ prompt: '检查本机 Codex 重置时间,快到了就提醒我。',+ intervalMs: 3_600_000,+ });++ render(createElement(SchedulerPage));++ await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy());+ expect(screen.getByDisplayValue('Codex 重置提醒')).toBeTruthy();+ expect(screen.getByDisplayValue('检查本机 Codex 重置时间,快到了就提醒我。')).toBeTruthy();+ // 插件永远不能直接建任务:落库只发生在用户点保存之后。+ expect(createSchedule).not.toHaveBeenCalled();+ // 一次性意图用完即清,重进自动化页不会再弹。+ expect(routerMocks.navigate).toHaveBeenCalledWith('/cc-agent/scheduled', {+ replace: true,+ state: null,+ });+ });++ /**+ * #1715 review Codex P2 的回归:表单已打开且用户改过内容时,新到的插件请求+ * **绝不能静默 reset 掉它**(ScheduleFormDialog 的 reset effect 依赖 initialValues,+ * 守卫只有 `if (!open) return`)。语义是"拒绝 + 提示",用户输入一个字都不能丢。+ */+ it('表单已打开且已修改时,新的插件请求不覆盖用户输入,只提示', async () => {+ routerMocks.location.state = pluginScheduleNavigationState({+ kind: 'plugin-schedule-draft',+ requestId: 'plugin-req-first',+ ghostId: 'sign-board',+ ghostName: '签字门看板',+ name: '插件预填的名字',+ prompt: '第一次请求的提示词。',+ });++ const view = render(createElement(SchedulerPage));+ await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy());++ // 用户在表单里改了名称 —— 这就是绝不能丢的内容。+ const nameInput = screen.getByDisplayValue('插件预填的名字');+ fireEvent.change(nameInput, { target: { value: '用户自己改的名字' } });+ expect(screen.getByDisplayValue('用户自己改的名字')).toBeTruthy();++ // 第二个插件请求到来(不同 requestId,否则会被去重挡掉)。+ routerMocks.location.state = pluginScheduleNavigationState({+ kind: 'plugin-schedule-draft',+ requestId: 'plugin-req-second',+ ghostId: 'codex-reset-planner',+ ghostName: 'Codex 重置管家',+ name: '第二次请求的名字',+ prompt: '第二次请求的提示词。',+ });+ view.rerender(createElement(SchedulerPage));++ // 用户输入原样保留,没有被第二次请求的预填顶掉。+ await waitFor(() =>+ expect(toastMocks.warning).toHaveBeenCalledWith(+ 'scheduler.toast.pluginDraftIgnoredFormOpen',+ ),+ );+ expect(screen.getByDisplayValue('用户自己改的名字')).toBeTruthy();+ expect(screen.queryByDisplayValue('第二次请求的名字')).toBeNull();+ expect(screen.queryByDisplayValue('第二次请求的提示词。')).toBeNull();+ expect(createSchedule).not.toHaveBeenCalled();+ });++ /**+ * review #1715 的回归:**所见即所存**。+ *+ * 插件请求的任务是「用户不改模型、直接点保存」的高频路径(插件把内容都预填好了,+ * 用户只是确认一下),所以模型默认值这条链路对它尤其值得钉死:一旦"显示的模型"与+ * "落库的模型"漂移,用户就会以为在用 A、实际每次跑 B(2026-06 真踩过)。+ *+ * 本用例钉的是**端到端结果**而非某条实现路径:当前由 ScheduleFormDialog 的+ * "form.model 为空时回填默认模型" effect 保证;将来若有人改成从 intent 直接给值,+ * 或反过来删掉那个 effect,只要最终"显示 === 落库"成立就仍然通过 —— 用户可见的+ * 正确性才是契约。+ *+ * 这里刻意把「记忆的模型」设成**不同于 fallback**(claude-sonnet-4-6)的值,+ * 否则两者恰好相等时这个 bug 根本测不出来。+ */+ it('插件请求:用户不碰模型 chip 直接保存,存下的模型与表单显示的一致', async () => {+ const REMEMBERED = 'claude-opus-4-9';+ expect(REMEMBERED).not.toBe('claude-sonnet-4-6'); // 必须区别于 fallback,否则测不出问题+ localStorageData.set(+ 'xdt:scheduleFormPrefs:v1',+ JSON.stringify({+ agentKind: 'claude-code',+ workspaceKind: 'dialogue',+ workingDir: '',+ useWorktree: false,+ lastByAgent: {+ 'claude-code': { model: REMEMBERED, providerId: '', effort: '', fastMode: false },+ },+ }),+ );++ routerMocks.location.state = pluginScheduleNavigationState({+ kind: 'plugin-schedule-draft',+ requestId: 'plugin-model-default',+ ghostId: 'codex-reset-planner',+ ghostName: 'Codex 重置管家',+ name: 'Codex 重置提醒',+ prompt: '检查重置时间,快到了提醒我。',+ intervalMs: 3_600_000,+ });++ render(createElement(SchedulerPage));+ await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy());++ // 表单显示的就是记忆值(不是空、也不是 fallback)。+ expect(screen.getByTestId('model-value').textContent).toBe(REMEMBERED);++ // 用户什么都不改,直接保存。+ fireEvent.click(+ screen.getByRole('button', { name: 'scheduler.editor.promptDialog.createAria' }),+ );++ // 存下去的模型 === 表单上显示的那个,不省略、不回退。+ await waitFor(() => expect(createSchedule).toHaveBeenCalled());+ expect(createSchedule).toHaveBeenCalledWith(+ expect.objectContaining({ model: REMEMBERED, agentKind: 'claude-code' }),+ );+ });});diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex 00713e4660..c0e514262a 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -29,6 +29,7 @@ import { GlobalDropImportListener } from '@/components/layout/GlobalDropImportLiimport { SessionShareImportWizard } from '@/components/settings/SessionShareImportWizard';import { ControlledBanner } from '@/features/remote-device/ControlledBanner';import { useDeviceLinkRemoteProjects } from '@/features/device-link/useDeviceLinkRemoteProjects';+import { pluginScheduleNavigationState } from '@/features/scheduler/lib/pluginScheduleCreateIntent';import { FeatureSidebarSlotProvider } from '@/features/feature-context';import { useAppShortcut } from '@/hooks/useAppShortcut';import { useCloseShortcutShellOwner } from '@/hooks/useCloseWindowShortcut';@@ -528,6 +529,49 @@ export function MainLayout() {return unsubscribe;}, [navigateToSession]);+ // 插件请求新建自动化(agent 槽的 schedule 加档):main 的 scheduleSlot 已做资格审 /+ // 净化截断 / 频率钳制 / 限速,这里只负责把用户带到自动化页并把预填内容交过去。+ // 挂在 MainLayout 的理由同上面那条:它在 ProtectedRoute + LocalDbGate 之内,用户+ // 必然已登录、可以安全 navigate;而插件请求可能在任何路由下到达(用户当时正在+ // 插件面板里),SchedulerPage 那时还没挂载,接不到这条推送。+ //+ // main 侧**只投一个主壳窗**(见 cindy-brain 的 isMainShellWindowUrl):独立的插件+ // 面板窗 / 右侧栏窗与 MainLayout 平级、没有本订阅,所以别在那两个轻壳里再加一份+ // 处理——它们收不到,加了也是死代码。同一窗口内仍需去重(下游 SchedulerPage 的+ // handledScheduleCreateRequestRef):navigate 带的 state 可能被 effect 重复消费。+ //+ // ⚠️ 这里**只导航**。任务落库只发生在用户于面板上点保存之后 —— 插件全程没有+ // 直接建任务的通道(scheduleSlot 的 deps 里压根没有 schedule storage)。+ useEffect(() => {+ const unsubscribe = window.electronAPI.ghosts?.onScheduleDraft?.((payload) => {+ if (!payload || typeof payload !== 'object') return;+ const { requestId, ghostId, ghostName, name, prompt, intervalMs } = payload;+ if (+ typeof requestId !== 'string' || !requestId ||+ typeof ghostId !== 'string' || !ghostId ||+ typeof ghostName !== 'string' || !ghostName ||+ typeof name !== 'string' || !name ||+ typeof prompt !== 'string' || !prompt+ ) {+ return;+ }+ navigate('/cc-agent/scheduled', {+ state: pluginScheduleNavigationState({+ kind: 'plugin-schedule-draft',+ requestId,+ ghostId,+ ghostName,+ name,+ prompt,+ ...(typeof intervalMs === 'number' && Number.isFinite(intervalMs) && intervalMs > 0+ ? { intervalMs }+ : {}),+ }),+ });+ });+ return unsubscribe;+ }, [navigate]);+// cindy://(+ 历史 xdt-maker://)深度链接 + --open-folder 右键菜单订阅 —— main 端解析后推 payload,// 这里按 type 分发。// session: canonicalize 后 navigate 到对应路由(与 onNotificationFocusSession 同语义)diff --git a/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx b/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsxindex 5eebfeee07..d5456000f8 100644--- a/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx+++ b/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx@@ -64,6 +64,10 @@ import {buildUsageLimitScheduleFormOverrides,readUsageLimitScheduleCreateIntent,} from './lib/usageLimitScheduleCreateIntent';+import {+ buildPluginScheduleFormOverrides,+ readPluginScheduleCreateIntent,+} from './lib/pluginScheduleCreateIntent';function scheduleToUserCreateInput(schedule: Schedule,@@ -154,6 +158,13 @@ export function SchedulerPage() {// 项目分组"+"按钮的预填 workingDir:用户级 schedule,仅省去选项目目录这一步,// 不强制写 schedules.json(要"提升为项目自动化"走右键菜单 promoteToProject)。const [createPrefillWorkingDir, setCreatePrefillWorkingDir] = useState<string | null>(null);+ // 本次创建面板是由哪个插件请求打开的(agent 槽 schedule 加档)。只做面板上的+ // 来源标注 —— 让用户看清是谁请求建这条任务;不落库(见 pluginScheduleCreateIntent+ // 里 ghostId 的注释:落库要新增 DB 列 + 不可回退的 migration)。+ const [pluginScheduleOrigin, setPluginScheduleOrigin] = useState<{+ ghostId: string;+ ghostName: string;+ } | null>(null);const [selectedId, setSelectedId] = useState<string | null>(null);// Status 筛选默认 'all'(默认展示全部任务,含 paused);用户在 popover 主动// 切换后持久化,重进页面恢复上次选择(issue #75)。@@ -213,6 +224,7 @@ export function SchedulerPage() {setCreatePrefillWorkingDir(null);setCreateInitialTemplate(null);setCreateInitialValues(null);+ setPluginScheduleOrigin(null);setEditing(focused);setFormOpen(true);}, [editToken, focusId, schedules]);@@ -237,6 +249,48 @@ export function SchedulerPage() {navigate(path, { replace: true, state: null });}, [location.pathname, location.search, location.state, navigate, t]);+ // 插件请求新建自动化(agent 槽 schedule 加档):形态与上面 usage-limit 那条+ // 完全一致 —— 一次性导航意图 → 预填打开面板 → 用完立刻清掉 state。+ // 与它共用 handledScheduleCreateRequestRef:两种意图不该叠开两个面板。+ // ⚠️ 这里只 setCreateInitialValues + 打开面板,**不创建任务**。落库仍然只发生在+ // 用户点保存后走 handleSubmit —— 插件全程没有直接建任务的通道。+ useEffect(() => {+ const intent = readPluginScheduleCreateIntent(location.state);+ if (!intent || handledScheduleCreateRequestRef.current === intent.requestId) return;+ handledScheduleCreateRequestRef.current = intent.requestId;+ const consumeState = () => {+ const path = `${location.pathname || '/cc-agent/scheduled'}${location.search}`;+ navigate(path, { replace: true, state: null });+ };+ // 表单已经开着 → **不覆盖**,提示后把这次请求丢掉(review #1715 的 Codex P2)。+ // ⚠️ PR 号写成 `review` 紧跟编号的语序不是随手排版:scheduler-ci-guard 的+ // 色值白名单规则会把「井号 + 4 位数字」当成 RGBA 简写色值,它只豁免紧跟+ // `PR ` / `review ` 的写法(见 scripts/scheduler-ci-guard.mjs)。+ //+ // 为什么不能直接往下走:ScheduleFormDialog 的 reset effect 依赖 initialValues 且+ // 守卫只有 `if (!open) return`(components/ScheduleFormDialog.tsx 的那个 effect),+ // 所以在表单已 open 时换一份 initialValues 会**静默 reset 掉用户正在填的内容**。+ // 插件请求可以在任何时刻到达,这条路径是本 PR 打开的,必须由本 PR 兜住。+ //+ // 语义选"拒绝 + 提示"而不是"延后"或"弹确认":延后要引入待处理队列与过期判定,+ // 弹确认会在用户填表中途再插一层模态——两者都比"让用户存完再点一次"更重。用户+ // 输入绝不丢是硬要求,一次插件请求丢掉只需再点一次,代价不对称。+ //+ // 只可能在用户正停在自动化页时命中:formOpen 是本页 state,离开页面即卸载归 false。+ if (formOpen) {+ toast.warning(t('scheduler.toast.pluginDraftIgnoredFormOpen', { name: intent.ghostName }));+ consumeState();+ return;+ }+ setCreatePrefillWorkingDir(null);+ setCreateInitialTemplate(null);+ setEditing(null);+ setCreateInitialValues(buildPluginScheduleFormOverrides(intent));+ setPluginScheduleOrigin({ ghostId: intent.ghostId, ghostName: intent.ghostName });+ setFormOpen(true);+ consumeState();+ }, [formOpen, location.pathname, location.search, location.state, navigate, t]);+// workingDir filter(URL ?workingDir=...)const scopedByDir = useMemo(() => {if (!filterWorkingDir) return schedules;@@ -299,6 +353,7 @@ export function SchedulerPage() {setCreatePrefillWorkingDir(null);setCreateInitialTemplate(null);setCreateInitialValues(null);+ setPluginScheduleOrigin(null);setEditing(null);setFormOpen(true);}, []);@@ -307,6 +362,7 @@ export function SchedulerPage() {setCreatePrefillWorkingDir(null);setCreateInitialTemplate(template);setCreateInitialValues(null);+ setPluginScheduleOrigin(null);setEditing(null);setFormOpen(true);}, []);@@ -315,6 +371,7 @@ export function SchedulerPage() {setCreatePrefillWorkingDir(null);setCreateInitialTemplate(null);setCreateInitialValues(null);+ setPluginScheduleOrigin(null);setEditing(s);setFormOpen(true);}, []);@@ -323,6 +380,7 @@ export function SchedulerPage() {setEditing(null);setCreateInitialTemplate(null);setCreateInitialValues(null);+ setPluginScheduleOrigin(null);setCreatePrefillWorkingDir(workingDir);setFormOpen(true);}, []);@@ -469,6 +527,7 @@ export function SchedulerPage() {const handleEditProjectSchedule = useCallback((s: Schedule) => {setCreatePrefillWorkingDir(null);setCreateInitialTemplate(null);+ setPluginScheduleOrigin(null);setEditing(s);setFormOpen(true);}, []);@@ -638,12 +697,14 @@ export function SchedulerPage() {setCreatePrefillWorkingDir(null);setCreateInitialTemplate(null);setCreateInitialValues(null);+ setPluginScheduleOrigin(null);}}}initial={editing}initialTemplate={createInitialTemplate}initialValues={createInitialValues}initialWorkingDir={createPrefillWorkingDir}+ requestedByGhostName={pluginScheduleOrigin?.ghostName ?? null}editProjectSchedule={editing?.source === 'project'}onSubmit={handleSubmit}/>diff --git a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsxindex df7f1ad4bb..e2be5998c4 100644--- a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx+++ b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx@@ -106,6 +106,12 @@ interface Props {initialWorkingDir?: string | null;/** 编辑 project schedule 时为 true,保存走 schedules.json upsert。 */editProjectSchedule?: boolean;+ /**+ * 本次新建面板是由哪个插件请求打开的(agent 槽 schedule 加档)。非空时在标题下+ * 显示来源标注,让用户看清是谁请求建这条任务 —— 预填内容来自插件,用户必须知道+ * 自己在替谁保存。仅展示,不影响提交内容。+ */+ requestedByGhostName?: string | null;}export function ScheduleFormDialog({@@ -117,6 +123,7 @@ export function ScheduleFormDialog({onSubmit,initialWorkingDir = null,editProjectSchedule = false,+ requestedByGhostName = null,}: Props) {const { t } = useTranslation();const formApi = useScheduleForm(initial);@@ -556,7 +563,11 @@ export function ScheduleFormDialog({: t('scheduler.editor.promptDialog.titleCreate')}</Dialog.Title><p className="text-sm leading-[1.43] text-[var(--cmd-palette-item-meta)]">- {t('scheduler.editor.promptDialog.subtitle')}+ {requestedByGhostName+ ? t('scheduler.editor.promptDialog.subtitleFromGhost', {+ name: requestedByGhostName,+ })+ : t('scheduler.editor.promptDialog.subtitle')}</p></div>{!isEdit && !isProjectAutomationMode && (diff --git a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/pluginScheduleCreateIntent.test.ts b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/pluginScheduleCreateIntent.test.tsnew file mode 100644index 0000000000..626b40299f--- /dev/null+++ b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/pluginScheduleCreateIntent.test.ts@@ -0,0 +1,101 @@+/**+ * @vitest-environment node+ *+ * pluginScheduleCreateIntent.test — 插件请求新建自动化的意图/预填纯函数层。+ */++import { describe, expect, it } from 'vitest';++import {+ buildPluginScheduleFormOverrides,+ pluginScheduleNavigationState,+ readPluginScheduleCreateIntent,+ type PluginScheduleCreateIntent,+} from '../pluginScheduleCreateIntent';++const intent: PluginScheduleCreateIntent = {+ kind: 'plugin-schedule-draft',+ requestId: 'req-1',+ ghostId: 'codex-reset-planner',+ ghostName: 'Codex 重置管家',+ name: 'Codex 重置提醒',+ prompt: '检查本机 Codex 重置时间,快到了就调 update_status 写回去。',+ intervalMs: 3_600_000,+};++describe('readPluginScheduleCreateIntent', () => {+ it('往返:navigationState → read 得回原 intent', () => {+ expect(readPluginScheduleCreateIntent(pluginScheduleNavigationState(intent))).toEqual(intent);+ });++ it('不带 intervalMs 也合法(面板用自己的默认频率)', () => {+ const noInterval: PluginScheduleCreateIntent = { ...intent };+ delete noInterval.intervalMs;+ expect(readPluginScheduleCreateIntent(pluginScheduleNavigationState(noInterval))).toEqual(+ noInterval,+ );+ });++ it.each([+ ['null', null],+ ['非对象', 'nope'],+ ['空对象', {}],+ ['kind 不对', { pluginScheduleDraft: { ...intent, kind: 'other' } }],+ ['缺 requestId', { pluginScheduleDraft: { ...intent, requestId: '' } }],+ ['缺 ghostId', { pluginScheduleDraft: { ...intent, ghostId: '' } }],+ ['缺 ghostName', { pluginScheduleDraft: { ...intent, ghostName: '' } }],+ ['缺 name', { pluginScheduleDraft: { ...intent, name: '' } }],+ ['缺 prompt', { pluginScheduleDraft: { ...intent, prompt: '' } }],+ ['intervalMs 非数字', { pluginScheduleDraft: { ...intent, intervalMs: 'soon' } }],+ ['intervalMs 为 0', { pluginScheduleDraft: { ...intent, intervalMs: 0 } }],+ ['intervalMs 为负', { pluginScheduleDraft: { ...intent, intervalMs: -1 } }],+ ['intervalMs 非有限', { pluginScheduleDraft: { ...intent, intervalMs: Number.NaN } }],+ ])('形状不对就当没有:%s → null', (_label, state) => {+ expect(readPluginScheduleCreateIntent(state)).toBeNull();+ });+});++describe('buildPluginScheduleFormOverrides', () => {+ it('落成普通 agent 自动化 —— 不带任何插件专属执行配置', () => {+ const overrides = buildPluginScheduleFormOverrides(intent);+ expect(overrides.executionMode).toBe('agent');+ // 插件不是执行者,所以不该出现 script/plugin 那类执行配置字段。+ expect(overrides).not.toHaveProperty('scriptCommand');+ expect(overrides).not.toHaveProperty('pluginConfig');+ });++ it('模型/来源/思考强度一律留空 = 用默认模型,由用户在面板上自己选', () => {+ const overrides = buildPluginScheduleFormOverrides(intent);+ expect(overrides.model).toBe('');+ expect(overrides.providerId).toBe('');+ expect(overrides.effort).toBe('');+ expect(overrides.fastMode).toBe(false);+ });++ it('预填 name / prompt 原样透传(净化与截断已在 main 侧做完)', () => {+ const overrides = buildPluginScheduleFormOverrides(intent);+ expect(overrides.name).toBe(intent.name);+ expect(overrides.prompt).toBe(intent.prompt);+ });++ it('带建议频率 → 写进 intervalMs;不带 → 不带该 key(沿用面板默认)', () => {+ expect(buildPluginScheduleFormOverrides(intent).intervalMs).toBe(3_600_000);+ const noInterval: PluginScheduleCreateIntent = { ...intent };+ delete noInterval.intervalMs;+ expect(buildPluginScheduleFormOverrides(noInterval)).not.toHaveProperty('intervalMs');+ });++ it('不绑会话、不占工作目录、不开隔离工作区', () => {+ const overrides = buildPluginScheduleFormOverrides(intent);+ expect(overrides.targetSessionId).toBe('');+ expect(overrides.persistentSession).toBe(false);+ expect(overrides.workspaceKind).toBe('dialogue');+ expect(overrides.workingDir).toBe('');+ expect(overrides.useWorktree).toBe(false);+ });++ it('不落库发起插件 id(避免为一个展示字段欠下不可回退的 schema 债)', () => {+ // ghostId 只用于面板上的来源标注,不进表单提交内容。+ expect(buildPluginScheduleFormOverrides(intent)).not.toHaveProperty('originGhostId');+ });+});diff --git a/apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts b/apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.tsnew file mode 100644index 0000000000..438a091142--- /dev/null+++ b/apps/desktop/src/renderer/features/scheduler/lib/pluginScheduleCreateIntent.ts@@ -0,0 +1,130 @@+/**+ * pluginScheduleCreateIntent — 插件请求「新建自动化」的意图与预填构造(纯函数层)。+ * ---------------------------------------------------------------------------+ * 链路:插件面板上用户点「提醒我 XXXX」→ 管子 schedule-request → main 的+ * scheduleSlot(资格审/净化/钳制/限速)→ 广播 → 订阅点导航到自动化页并带上本+ * intent → SchedulerPage 读出来转成表单预填 → 面板打开,用户选模型后**亲手保存**。+ *+ * 形态与 usageLimitScheduleCreateIntent 逐条同构(同一套 navigation state 通道 ++ * Partial<ScheduleFormState> 预填),不另发明一条路。+ *+ * 落成的任务是一条**普通 agent 自动化**:执行者是 AI 会话,插件只是这条任务到点+ * 去调用的目标(靠已有的 tool 槽 + ghost_call)。所以这里不碰 executionMode,也+ * 没有任何插件专属的执行配置。+ */++import type { ScheduleFormState } from './scheduleFormLogic';++export interface PluginScheduleCreateIntent {+ kind: 'plugin-schedule-draft';+ /** main 铸的请求 id;renderer 用它去重(同一次请求重复推送不叠开面板)。 */+ requestId: string;+ /**+ * 发起插件。目前只用于面板上的来源标注(让用户看清是谁请求建这条任务),+ * **不落库** —— 把它写进 schedule 需要新增 DB 列 + migration,而 migration+ * 一旦进 main 就拆不掉(仓规红线)。等"插件详情页列出自己建的任务"这个需求+ * 真的要做时再一并加,不为一个展示字段先欠一笔不可回退的 schema 债。+ */+ ghostId: string;+ /** 插件展示名(main 按已装清单填,不信沙箱自报)。 */+ ghostName: string;+ /** 预填任务名(main 已净化截断)。 */+ name: string;+ /** 预填提示词:这条任务到点要干什么(插件用自然语言写)。 */+ prompt: string;+ /** 建议触发间隔 ms(main 已钳到 30 分钟之上);缺省 = 用面板默认频率。 */+ intervalMs?: number;+}++export function pluginScheduleNavigationState(intent: PluginScheduleCreateIntent): {+ pluginScheduleDraft: PluginScheduleCreateIntent;+} {+ return { pluginScheduleDraft: intent };+}++/**+ * 从导航 state 读回 intent。**所有字段逐个校验** —— 这条 state 的源头是插件沙箱+ * 提供的内容(main 已净化,但 renderer 不假设上游一定干净),形状不对就当没有。+ */+export function readPluginScheduleCreateIntent(+ state: unknown,+): PluginScheduleCreateIntent | null {+ if (!state || typeof state !== 'object') return null;+ const candidate = (state as { pluginScheduleDraft?: unknown }).pluginScheduleDraft;+ if (!candidate || typeof candidate !== 'object') return null;+ const value = candidate as Partial<PluginScheduleCreateIntent>;+ if (+ value.kind !== 'plugin-schedule-draft' ||+ typeof value.requestId !== 'string' ||+ !value.requestId ||+ typeof value.ghostId !== 'string' ||+ !value.ghostId ||+ typeof value.ghostName !== 'string' ||+ !value.ghostName ||+ typeof value.name !== 'string' ||+ !value.name ||+ typeof value.prompt !== 'string' ||+ !value.prompt ||+ (value.intervalMs !== undefined &&+ (typeof value.intervalMs !== 'number' ||+ !Number.isFinite(value.intervalMs) ||+ value.intervalMs <= 0))+ ) {+ return null;+ }+ return value as PluginScheduleCreateIntent;+}++/** 本机时区(与 usageLimit 那条同实现,失败兜底 UTC)。 */+function systemTimeZone(): string {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';+ } catch {+ return 'UTC';+ }+}++/**+ * intent → 表单预填。+ *+ * 刻意留空的两项:+ * - `model` / `providerId` / `effort` 全空 = **用默认模型**。插件不该替用户选模型,+ * 用户在面板上想改就改(Chris 定案:"用户选模型或者默认模型")。+ *+ * ⚠️ 留空**不会**让"显示的模型"与"实际执行的模型"漂移(review #1715 曾按此判为+ * 缺陷,实测不成立):ScheduleFormDialog 有一个专门的 effect —— `form.model` 为空+ * 且非 heartbeat 形态时,立即回填 `getScheduleDefaultModel(agentKind)` 的三级回退+ * 显式值(见该文件"form.model 为空时回填默认模型"那段,它正是为 2026-06 那次+ * "看着选了 Opus 4.8、实际每次跑 4.7"加的)。本 intent 的 `targetSessionId: ''`+ * 满足回填条件,所以表单打开那一刻 model 就已是显式值,保存时不会被省略。+ * 端到端行为由 schedulerTemplateEntry 的「所见即所存」用例钉住。+ * `providerId` / `effort` / `fastMode` 留空则本就是**合法语义**(跟随原生默认来源 /+ * 用模型默认思考强度 / 不开 Fast),不是缺失值。+ * - `cronExpr` 保留表单默认值:intervalMs 有值时引擎按 interval 语义走,cronExpr+ * 只是占位(见 Schedule.intervalMs 注释);没给建议频率时就用面板默认。+ *+ * `workspaceKind: 'dialogue'` —— 这类任务是"去查点东西再更新插件",不属于任何+ * 项目目录,落 app 管理的对话工作区(与 usageLimit 那条同口径)。+ */+export function buildPluginScheduleFormOverrides(+ intent: PluginScheduleCreateIntent,+): Partial<ScheduleFormState> {+ return {+ name: intent.name,+ prompt: intent.prompt,+ executionMode: 'agent',+ ...(intent.intervalMs !== undefined ? { intervalMs: intent.intervalMs } : {}),+ timezone: systemTimeZone(),+ recurring: true,+ manual: false,+ model: '',+ providerId: '',+ effort: '',+ fastMode: false,+ workspaceKind: 'dialogue',+ workingDir: '',+ useWorktree: false,+ targetSessionId: '',+ persistentSession: false,+ };+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 0bb5d74af6..cbb08ca323 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3389,6 +3389,8 @@"agentBackgroundDetail": "Does not require a click each time, but can only use sessions you previously connected to this plugin. Model charges may apply.","agentErrand": "Can hand tasks to the Cindy Agent and collect the result","agentErrandDetail": "Tasks run in this plugin's dedicated session, always visible in the sidebar and stoppable at any time. Read-only by default; raising the level requires your change in the plugin settings. Model charges may apply.",+ "agentSchedule": "Can ask you to create an automation",+ "agentScheduleDetail": "It can only open the new-automation panel with the fields filled in; whether it is created is up to you — pick a model and save it yourself. Once created, Cindy runs it on the schedule you set. Model charges may apply.","nodeRuntime": "Can run a bundled Node program on this computer","nodeMcp": "Can run a bundled stdio MCP on this computer","nodeRuntimeDetail": "High risk: it has the same local access as your user account, including files, network, and starting other programs. Cindy cannot contain it in the browser sandbox.",@@ -7054,6 +7056,7 @@"titleProjectCreate": "New project automation","titleProjectEdit": "Edit project automation","subtitle": "Run a prompt on a schedule with Claude or Codex.",+ "subtitleFromGhost": "\"{{name}}\" is asking you to create an automation. Pick a model and save to enable it.","save": "Save","create": "Create","saveAria": "Save automation",@@ -7274,7 +7277,8 @@"actionFailed": "Action failed: {{error}}","renameFailed": "Rename failed: {{error}}","deleteFailed": "Failed to delete: {{error}}",- "restartFailed": "Failed to restart: {{error}}"+ "restartFailed": "Failed to restart: {{error}}",+ "pluginDraftIgnoredFormOpen": "\"{{name}}\" asked to create an automation, but a form is already open. Your edits were kept — save or close it, then trigger the request again."},"deleteDialog": {"title": "Delete automation \"{{name}}\"?",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex e848796065..09f5e7f66f 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3388,6 +3388,8 @@"agentBackgroundDetail": "毎回のクリックは不要ですが、以前このプラグインに関連付けたセッションでのみ使用できます。モデル料金が発生する場合があります。","agentErrand": "Cindy Agent にタスクを任せて結果を受け取れます","agentErrandDetail": "タスクはこのプラグイン専用のセッションで実行され、サイドバーから常に確認・停止できます。既定では読み取り専用で、権限の引き上げはプラグイン設定であなた自身が行う必要があります。モデル料金が発生する場合があります。",+ "agentSchedule": "自動化の新規作成をあなたに依頼できます",+ "agentScheduleDetail": "できるのは内容が入力済みの新規自動化パネルを開くことだけで、作成するかどうかはあなたがモデルを選んで自分で保存して決めます。作成後は Cindy があなたの設定した時間に実行します。モデル料金が発生する場合があります。","nodeRuntime": "同梱された Node プログラムをこのコンピューターで実行できます","nodeMcp": "同梱された stdio MCP をこのコンピューターで実行できます","nodeRuntimeDetail": "高リスク:あなたのユーザーアカウントと同じ権限で、ローカルファイルの読み書き、ネットワークアクセス、他のプログラムの起動ができます。Cindy のブラウザーサンドボックスでは隔離できません。",@@ -7043,6 +7045,7 @@"titleProjectCreate": "新しいプロジェクト自動化","titleProjectEdit": "プロジェクト自動化を編集","subtitle": "Claude または Codex でプロンプトをスケジュール実行します。",+ "subtitleFromGhost": "「{{name}}」が自動化の作成を求めています。モデルを選んで保存すると有効になります。","save": "保存","create": "作成","saveAria": "自動化を保存",@@ -7263,7 +7266,8 @@"actionFailed": "操作に失敗しました: {{error}}","renameFailed": "名前の変更に失敗しました: {{error}}","deleteFailed": "削除に失敗しました: {{error}}",- "restartFailed": "再開に失敗しました: {{error}}"+ "restartFailed": "再開に失敗しました: {{error}}",+ "pluginDraftIgnoredFormOpen": "「{{name}}」が自動化の作成を求めましたが、編集中のフォームが開いています。入力内容はそのまま保持しました。保存または閉じたあと、もう一度実行してください。"},"deleteDialog": {"title": "自動化「{{name}}」を削除しますか?",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 83748a3a08..663886cc33 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3388,6 +3388,8 @@"agentBackgroundDetail": "매번 클릭할 필요는 없지만, 이전에 이 플러그인과 연결한 세션에서만 사용할 수 있습니다. 모델 비용이 발생할 수 있습니다.","agentErrand": "Cindy Agent에게 작업을 맡기고 결과를 받아올 수 있음","agentErrandDetail": "작업은 이 플러그인 전용 세션에서 실행되며, 사이드바에서 언제든 확인하고 중단할 수 있습니다. 기본은 읽기 전용이며, 권한 상향은 플러그인 설정에서 직접 해야 합니다. 모델 비용이 발생할 수 있습니다.",+ "agentSchedule": "자동화 새로 만들기를 요청할 수 있음",+ "agentScheduleDetail": "내용이 미리 채워진 자동화 만들기 패널을 여는 것만 할 수 있으며, 실제로 만들지는 사용자가 모델을 고르고 직접 저장해 결정합니다. 만든 뒤에는 Cindy가 설정한 시간에 실행합니다. 모델 비용이 발생할 수 있습니다.","nodeRuntime": "함께 제공된 Node 프로그램을 이 컴퓨터에서 실행할 수 있음","nodeMcp": "함께 제공된 stdio MCP를 이 컴퓨터에서 실행할 수 있음","nodeRuntimeDetail": "고위험:사용자 계정과 같은 권한으로 로컬 파일을 읽거나 수정하고, 네트워크에 접근하며, 다른 프로그램을 시작할 수 있습니다. Cindy의 브라우저 샌드박스로 격리할 수 없습니다.",@@ -7043,6 +7045,7 @@"titleProjectCreate": "새 프로젝트 자동화","titleProjectEdit": "프로젝트 자동화 편집","subtitle": "Claude 또는 Codex로 프롬프트를 일정에 따라 실행합니다.",+ "subtitleFromGhost": "\"{{name}}\"에서 자동화 만들기를 요청했습니다. 모델을 고르고 저장하면 적용됩니다.","save": "저장","create": "만들기","saveAria": "자동화 저장",@@ -7263,7 +7266,8 @@"actionFailed": "작업 실패: {{error}}","renameFailed": "이름 변경 실패: {{error}}","deleteFailed": "삭제 실패: {{error}}",- "restartFailed": "재시작 실패: {{error}}"+ "restartFailed": "재시작 실패: {{error}}",+ "pluginDraftIgnoredFormOpen": "\"{{name}}\"에서 자동화 만들기를 요청했지만 편집 중인 양식이 열려 있습니다. 입력한 내용은 그대로 유지했습니다. 저장하거나 닫은 뒤 다시 요청하세요."},"deleteDialog": {"title": "자동화 \"{{name}}\"을(를) 삭제하시겠습니까?",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex e2a64079ed..73ee944f43 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3388,6 +3388,8 @@"agentBackgroundDetail": "不需要当次点击,但只能使用你曾为这个插件建立过关联的任务,可能产生模型费用。","agentErrand": "可把任务交给 Cindy Agent 代办并取回结果","agentErrandDetail": "这些代办会在这个插件的专属任务里进行,你随时可以在侧边栏看到并叫停;默认只能读不能改,要放开需你在插件配置里亲手调整,可能产生模型费用。",+ "agentSchedule": "可以请你新建自动化",+ "agentScheduleDetail": "它只能为你打开新建自动化的面板并把内容填好,是否创建由你在面板上选好模型后亲手保存决定。创建后由 Cindy 按你设定的时间运行,可能产生模型费用。","nodeRuntime": "可在本机运行随插件附带的 Node 程序","nodeMcp": "可在本机运行随插件附带的 stdio MCP","nodeRuntimeDetail": "高风险:它和你本人一样,可以读取或修改你账号能访问的本机文件、访问网络并启动其它程序。Cindy 不能用浏览器沙箱限制它。",@@ -7043,6 +7045,7 @@"titleProjectCreate": "新建项目自动化","titleProjectEdit": "编辑项目自动化","subtitle": "用 Claude 或 Codex 按计划运行 Prompt。",+ "subtitleFromGhost": "「{{name}}」请你新建一个自动化。选好模型后保存即可生效。","save": "保存","create": "创建","saveAria": "保存自动化",@@ -7263,7 +7266,8 @@"actionFailed": "操作失败:{{error}}","renameFailed": "重命名失败:{{error}}","deleteFailed": "删除失败:{{error}}",- "restartFailed": "重启失败:{{error}}"+ "restartFailed": "重启失败:{{error}}",+ "pluginDraftIgnoredFormOpen": "「{{name}}」请你新建自动化,但当前有正在编辑的自动化表单。已保留你填写的内容;保存或关闭后请再点一次。"},"deleteDialog": {"title": "删除自动化「{{name}}」?",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex cbd098bae8..af67ee6b40 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1407,6 +1407,25 @@ interface ElectronAPI {url: string;}) => void,) => () => void;+ /**+ * agent 槽 schedule 加档:插件请求打开自动化创建面板并预填。+ * main 已做资格审 / 文本净化截断 / 频率钳制 / 限速;身份三件套由 main 按+ * 已装清单填(不信沙箱自报)。**只开面板** —— 任务由用户选模型后亲手保存。+ *+ * 投递是**单窗口**的:main 只投一个挂了完整主壳的窗口(打断式操作广播出去会让+ * 每个窗口都跳页弹表单)。独立的插件面板窗 / 右侧栏窗收不到本推送。+ */+ onScheduleDraft: (+ callback: (payload: {+ requestId: string;+ ghostId: string;+ ghostName: string;+ iconDataUrl?: string;+ name: string;+ prompt: string;+ intervalMs?: number;+ }) => void,+ ) => () => void;/** 运行时状态快照(错误接管态首帧数据源)。 */runtimeStates: () => Promise<{ states: Record<string, string> }>;/** 面板错误态「重载意识」:清熔断记账 + 重新拉起沙箱。 */diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex bf6ea05a7f..3318d27b00 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -744,7 +744,83 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {expect(diff.removed).toHaveLength(0);});- it('agent 详单必须与槽成对,且只接受 background / errand 两项加档', () => {+ it('agent.schedule 加档:单列一档权限,可与 background / errand 并存(2026-08-04)', () => {+ const sched = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'agent'],+ agent: { schedule: true },+ });+ expect(sched.ok).toBe(true);+ if (!sched.ok) return;+ expect(sched.manifest.agent).toEqual({ schedule: true });+ expect(ghostPermissionItems(sched.manifest)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ key: 'agent:schedule',+ kind: 'agent',+ labelKey: 'agentSchedule',+ detailKey: 'agentScheduleDetail',+ }),+ ]),+ );++ const all = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'agent'],+ agent: { background: true, errand: true, schedule: true },+ });+ expect(all.ok).toBe(true);+ if (!all.ok) return;+ expect(all.manifest.agent).toEqual({ background: true, errand: true, schedule: true });++ // 扩权复核必须看得见它:只加 schedule 的更新,added 恰好是这一项。+ const userActionOnly = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'agent'],+ });+ expect(userActionOnly.ok).toBe(true);+ if (!userActionOnly.ok) return;+ const diff = diffGhostPermissionItems(userActionOnly.manifest, sched.manifest);+ expect(diff.added.map((item) => item.key)).toEqual(['agent:schedule']);+ expect(diff.removed).toHaveLength(0);++ // schedule: false 且其余非 true = 详单没意义,拒(应省略字段)。+ expect(+ validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'agent'],+ agent: { schedule: false },+ }).ok,+ ).toBe(false);+ // schedule 非布尔 → 拒。+ expect(+ validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'agent'],+ agent: { schedule: 'yes' },+ }).ok,+ ).toBe(false);+ });++ it('存量兼容红线:不声明 agent.schedule 的清单,权限项与内容键逐字不变', () => {+ // 这条钉的是仓规红线(plugin-security-and-authoring.md §5):用户升级客户端后+ // 什么都不做,已装插件必须照旧可用 —— 不能因为新增了 schedule 加档,就让任何+ // 老清单多出/少掉一项权限或内容键(那会触发扩权复核、要求用户重新确认)。+ for (const agentNeeds of [undefined, { background: true }, { errand: true }]) {+ const result = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'agent'],+ ...(agentNeeds ? { agent: agentNeeds } : {}),+ });+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ const keys = ghostPermissionItems(result.manifest).map((item) => item.key);+ expect(keys).not.toContain('agent:schedule');+ expect(ghostContentKeys(result.manifest)).not.toContain('slotSchedule');+ }+ });++ it('agent 详单必须与槽成对,且只接受 background / errand / schedule 三项加档', () => {expect(validateGhostManifest({...goodChipManifest(),diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 1db625652f..e7c9f4deae 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -162,6 +162,27 @@ export interface GhostCardNeeds {export interface GhostAgentNeeds {background?: boolean;errand?: boolean;+ /**+ * schedule = 「可以请你新建自动化任务」(2026-08-04)。+ *+ * 用途:插件在自己面板上给用户一个「提醒我 XXXX」之类的选项,用户点了以后由+ * 插件请主机**打开自动化创建面板并预填**(名称 / 要干什么 / 建议频率)。+ *+ * 它能做什么、不能做什么(权限文案与实现必须一致):+ * - 只能**打开面板**。任务由用户在面板上选模型、亲手点保存才落库 —— 插件+ * 没有任何直接建任务的通道(scheduleSlot 只广播,不碰 storage;有测试钉住)。+ * - 落成的任务是一条**普通 agent 自动化**:执行者是 AI 会话,不是插件。插件在+ * 其中的角色是「被这条任务调用的目标」,靠已有的 tool 槽 + ghost_call 被叫到。+ * - 因此它**会消耗用户的模型额度** —— 装入确认必须说出口。+ *+ * 为什么挂在 agent 详单而不是新开一个 slot:+ * 语义上它就是「让 agent 定期替我干活」,属 agent 槽;而判据的可证明性与新 slot+ * 等同 —— agent 详单是**严格字段白名单**(见 parse 处 unknownAgentField 分支),+ * 未登记的子字段一律拒装,所以任何已经装在用户机器上的老包都不可能带+ * `agent.schedule`。不存在"老包恰好写过同名字段而白拿这份能力"的模糊地带+ * (与 badge / timer 那套判例同一理由,但少改一处基座白名单)。+ */+ schedule?: boolean;}/** 插件随包本地 Node 工作进程使用的 stdio 协议。 */@@ -831,6 +852,25 @@ export const GHOST_PREVIEW_URL_MAX_CHARS = 2048;/** preview 槽:同一插件两次打开预览的最小间隔 ms(防标签页刷屏)。 */export const GHOST_PREVIEW_OPEN_MIN_INTERVAL_MS = 5000;+/**+ * agent.schedule:同一插件两次请求打开自动化面板的最小间隔 ms。+ * 比 preview 长一档 —— 这个面板是**打断式**的(会把用户从当前页带走),+ * 而预览标签只是在右侧栏多开一页。按尝试记账,spam 顺延窗口。+ */+export const GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_MS = 15_000;+/** agent.schedule:预填任务名长度上限(字符;超出截断)。 */+export const GHOST_SCHEDULE_DRAFT_NAME_MAX_CHARS = 60;+/** agent.schedule:预填 prompt 长度上限(字符;超出截断)。 */+export const GHOST_SCHEDULE_DRAFT_PROMPT_MAX_CHARS = 2000;+/**+ * agent.schedule:插件能建议的最小触发间隔 ms(30 分钟)。+ *+ * 这不是权限闸门(任务由用户在面板上亲手保存,他改成 1 分钟是他的自由),而是+ * **对插件建议值的钳制** —— 不让插件预填出一个每分钟叫醒一次 AI 会话的任务,+ * 用户点保存时未必看清频率就把额度烧了。低于此值一律上调到此值。+ */+export const GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_SUGGESTION_MS = 30 * 60_000;+/*** preview 槽详单(与 slots 含 'preview' 严格成对——有槽必有详单:范围是* 本能力的全部知情面,不允许"先装后说")。hosts 语法与 network 域名白名单@@ -1582,6 +1622,19 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItdetailKey: 'agentErrandDetail',});}+ // 「可以请你新建自动化任务」:独立 key 单列一档。理由同 badge/errand ——+ // diffGhostPermissionItems 按 key + detail 比对,若并进任何既有 key,已装插件+ // 在更新里新增 schedule 时 added 为空,plugin-market 的扩权复核不会拦,用户会+ // 在毫不知情的情况下多给出一份"能反复弹自动化面板、且任务会烧模型额度"的能力。+ // 排在 background/errand 之下:它必须经用户在面板上亲手保存才生效,风险低半档。+ if (manifest.agent?.schedule === true) {+ items.push({+ key: 'agent:schedule',+ kind: 'agent',+ labelKey: 'agentSchedule',+ detailKey: 'agentScheduleDetail',+ });+ }}// Node 是本机用户级执行权,不与浏览器沙箱的 `code` 混称。基础执行与// 常驻分别列出,用户能看懂“能运行”与“会一直运行”是两件事。@@ -2987,7 +3040,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {}const agentRaw = raw.agent as Record<string, unknown>;const unknownAgentField = Object.keys(agentRaw).find(- (key) => key !== 'background' && key !== 'errand',+ (key) => key !== 'background' && key !== 'errand' && key !== 'schedule',);if (unknownAgentField) {return {@@ -3001,16 +3054,20 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (agentRaw.errand !== undefined && typeof agentRaw.errand !== 'boolean') {return { ok: false, reason: 'agent.errand 必须是布尔值' };}- if (agentRaw.background !== true && agentRaw.errand !== true) {+ if (agentRaw.schedule !== undefined && typeof agentRaw.schedule !== 'boolean') {+ return { ok: false, reason: 'agent.schedule 必须是布尔值' };+ }+ if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true) {return {ok: false,reason:- 'agent 能力详单只有 background: true / errand: true 两项加档;仅需用户点击触发时请省略 agent 字段',+ 'agent 能力详单只有 background: true / errand: true / schedule: true 三项加档;仅需用户点击触发时请省略 agent 字段',};}agent = {...(agentRaw.background === true ? { background: true } : {}),...(agentRaw.errand === true ? { errand: true } : {}),+ ...(agentRaw.schedule === true ? { schedule: true } : {}),};}@@ -4331,6 +4388,10 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {* - pick-request:pick 槽——请主机弹系统级选文件夹窗口(用户亲选即授权)。* - preview-request:preview 槽——请主机在右侧栏内置浏览器开预览标签页* (URL 必须命中身份卡 preview.hosts 白名单)。+ * - schedule-request:agent 槽 schedule 加档——请主机**打开自动化创建面板并预填**+ * (名称 / 提示词 / 建议频率)。只能开面板:任务由用户选模型后亲手保存才落库,+ * 插件没有任何直接建任务的通道。本版也没有"建成了没有"的回执(语义见+ * GhostPipeScheduleDraftResult);绑定与查改由后续版本提供。** 身份永远由主机按 webContents 反查(不信自报),这里的类型只描述载荷形状。*/@@ -4799,6 +4860,81 @@ export type GhostPipePreviewResult =message: string;};+/**+ * schedule-request(agent.schedule 加档)的上行载荷。+ *+ * 与本文件里其它上行请求(PickRequest / PreviewRequest / WorkspaceRequest …)同规格:+ * 只描述**形状**,不代表已通过校验 —— 资格审、文本净化截断、频率钳制与限速都在主机侧+ * scheduleSlot 完成,沙箱给什么都要重新过一遍。+ */+export interface GhostPipeScheduleDraftRequest {+ type: 'schedule-request';+ /** 预填的自动化名称(净化后按 GHOST_SCHEDULE_DRAFT_NAME_MAX_CHARS 截断)。 */+ name: string;+ /** 预填提示词:这条自动化到点要干什么(净化后按 …PROMPT_MAX_CHARS 截断)。 */+ prompt: string;+ /**+ * 建议触发间隔(毫秒)。低于 GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_SUGGESTION_MS+ * 会被主机上调;缺省 = 不建议频率,面板用自己的默认值。+ */+ intervalMs?: number;+}++/**+ * schedule-request(agent.schedule 加档)的返回形态。+ *+ * ⚠️ ok:true 的语义严格是「**请求已被主机接受并投递给主壳窗口**」。它**不保证**+ * 面板真的打开了,更不表示任务已创建:+ * - 用户当时可能正开着另一个自动化表单在编辑 —— 那种情况下本次草稿会被**丢弃**+ * (保护用户没保存的输入),用户看到一句提示,面板不换内容;+ * - 即使面板正常打开,任务也要用户选完模型**亲手点保存**才落库。+ *+ * 因此插件 UI **不要**据此显示「已开启」之类的完成态,应显示「已为你打开创建面板,+ * 请确认」。判据不是保守 —— 是这一版本来就没有任何"用户存没存"的回执通道。+ *+ * 后续会补上:任务与发起插件的**绑定关系**,以及插件查询 / 管理**自己绑定的那条+ * 任务**(是否有效、下次运行时间、频率,以及改时间 / 暂停 / 关掉)。届时插件才能在+ * 自己面板上显示「已开启 · 每小时 · 下次 15:00」并让用户就地改。绑定关系本身即是+ * 授权边界:插件只能看和改它自己请求创建的那条,看不到用户的其它自动化。+ */+export type GhostPipeScheduleDraftResult =+ | { ok: true }+ | {+ ok: false;+ errorCode:+ | 'PERMISSION_DENIED'+ | 'INVALID_REQUEST'+ | 'RATE_LIMITED'+ | 'HOST_NOT_READY'+ | 'INTERNAL';+ message: string;+ };++/**+ * 主机 → renderer 的「打开自动化创建面板并预填」推送载荷。+ *+ * 身份三件套(ghostId / name / iconDataUrl)由主机按已装清单填,**不信沙箱自报**+ * (同 GhostPreviewOpenPush 纪律):面板上要让用户看清是哪个插件在请求。+ * 文本字段已由主机净化 + 截断;频率建议已钳到最小间隔之上。+ */+export interface GhostScheduleDraftPush {+ /** 本次请求 id(renderer 去重用:重复推送不叠开多个面板)。 */+ requestId: string;+ ghostId: string;+ /** 插件展示名(主机填,用于面板上的来源标注)。 */+ ghostName: string;+ iconDataUrl?: string;+ /** 预填任务名(已净化截断)。 */+ name: string;+ /** 预填提示词 —— 「这条任务到点要干什么」,由插件自己用自然语言写。 */+ prompt: string;+ /**+ * 建议触发间隔 ms。已钳到 GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_SUGGESTION_MS 之上。+ * 缺省 = 不建议频率,面板用它自己的默认值。+ */+ intervalMs?: number;+}+/** host-request 与 settings 页面 `/app-context` 共用的只读返回形态。 */export interface GhostAppContextResult {ok: true;