cc-viewer 1.9.22 → 1.9.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/LICENSE.md +28 -0
  2. package/README.md +2 -2
  3. package/cli.js +25 -1
  4. package/dist/assets/App-BwRRqrP5.css +1 -0
  5. package/dist/assets/App-Cfmm41z0.js +2 -0
  6. package/dist/assets/ArchivePreview-BKXTsPsN.css +1 -0
  7. package/dist/assets/ArchivePreview-dKWXN9Zp.js +1 -0
  8. package/dist/assets/{MdxEditorPanel-CmHF9Mz1.js → MdxEditorPanel-CT6w8hjl.js} +1 -1
  9. package/dist/assets/Mobile-noWViQpL.js +1 -0
  10. package/dist/assets/{ProxyStatsModal-Ogrx3mxS.js → ProxyStatsModal-BeCRPqaC.js} +1 -1
  11. package/dist/assets/{_baseUniq-CsF04anE.js → _baseUniq-BGBEhBne.js} +1 -1
  12. package/dist/assets/{arc-BOacYe6N.js → arc-4pbWOEmh.js} +1 -1
  13. package/dist/assets/{architectureDiagram-Q4EWVU46-BSUEfjC_.js → architectureDiagram-Q4EWVU46-BHZPDnby.js} +1 -1
  14. package/dist/assets/{blockDiagram-DXYQGD6D-CC37UGtW.js → blockDiagram-DXYQGD6D-DszLU7Pg.js} +1 -1
  15. package/dist/assets/{c4Diagram-AHTNJAMY-IzgRD4uO.js → c4Diagram-AHTNJAMY-DbDJNYxl.js} +1 -1
  16. package/dist/assets/{channel-C6PxyQUn.js → channel-BpIsxDHj.js} +1 -1
  17. package/dist/assets/{chunk-4BX2VUAB-cdQt_dcU.js → chunk-4BX2VUAB-ChcBwBh2.js} +1 -1
  18. package/dist/assets/{chunk-4TB4RGXK-BpTDA_Pb.js → chunk-4TB4RGXK-DzBEAck_.js} +1 -1
  19. package/dist/assets/{chunk-55IACEB6-CcitNo0P.js → chunk-55IACEB6-9UDvmw07.js} +1 -1
  20. package/dist/assets/{chunk-EDXVE4YY-BjKwZ9I7.js → chunk-EDXVE4YY-DHEU2DKg.js} +1 -1
  21. package/dist/assets/{chunk-FMBD7UC4-vZDVX3tI.js → chunk-FMBD7UC4-sysT0Sy2.js} +1 -1
  22. package/dist/assets/{chunk-OYMX7WX6-DGkYahGo.js → chunk-OYMX7WX6-DLXt2vYo.js} +1 -1
  23. package/dist/assets/{chunk-QZHKN3VN-C9065hSE.js → chunk-QZHKN3VN-CDIkC7QK.js} +1 -1
  24. package/dist/assets/{chunk-YZCP3GAM-D_pcTg6_.js → chunk-YZCP3GAM-D9b_INz7.js} +1 -1
  25. package/dist/assets/classDiagram-6PBFFD2Q-4Lh0SB4X.js +1 -0
  26. package/dist/assets/classDiagram-v2-HSJHXN6E-4Lh0SB4X.js +1 -0
  27. package/dist/assets/clone-cWiXtXrO.js +1 -0
  28. package/dist/assets/{cose-bilkent-S5V4N54A-BPPFMIGv.js → cose-bilkent-S5V4N54A-DJQwV_Dp.js} +1 -1
  29. package/dist/assets/{dagre-KV5264BT-fjzhKO5o.js → dagre-KV5264BT-bl9Pq21t.js} +1 -1
  30. package/dist/assets/{diagram-5BDNPKRD-5L6FzTry.js → diagram-5BDNPKRD-BA8CJxzI.js} +1 -1
  31. package/dist/assets/{diagram-G4DWMVQ6-GOwcGpff.js → diagram-G4DWMVQ6-DzSQULuz.js} +1 -1
  32. package/dist/assets/{diagram-MMDJMWI5-BDsFE25W.js → diagram-MMDJMWI5-DhfHWnT4.js} +1 -1
  33. package/dist/assets/{diagram-TYMM5635-BqjpbSGH.js → diagram-TYMM5635-BbAoFfGS.js} +1 -1
  34. package/dist/assets/{erDiagram-SMLLAGMA-DWO3Dk1v.js → erDiagram-SMLLAGMA-CMjA2eBk.js} +1 -1
  35. package/dist/assets/{flowDiagram-DWJPFMVM-Br4nNBVd.js → flowDiagram-DWJPFMVM-bOubqgJ6.js} +1 -1
  36. package/dist/assets/{ganttDiagram-T4ZO3ILL-9sN-VOhw.js → ganttDiagram-T4ZO3ILL-BUIu7WwI.js} +1 -1
  37. package/dist/assets/{gitGraphDiagram-UUTBAWPF-BsPcTAKr.js → gitGraphDiagram-UUTBAWPF-B_vrztDU.js} +1 -1
  38. package/dist/assets/{graph-o31GzaB6.js → graph-BR3YGx52.js} +1 -1
  39. package/dist/assets/{index-DAjx9lT3.js → index-B88yR2TU.js} +1 -1
  40. package/dist/assets/{index-PDvAAbti.js → index-BMpUfdYI.js} +1 -1
  41. package/dist/assets/{index-DyV81jSF.js → index-BQx5MOpr.js} +1 -1
  42. package/dist/assets/index-Ca3a2tOc.js +2 -0
  43. package/dist/assets/{index-CuvDJTY7.js → index-ClTuiPoz.js} +1 -1
  44. package/dist/assets/{index-tZqiJJGq.js → index-DtZAmvwJ.js} +1 -1
  45. package/dist/assets/{index-B3b0lRUB.js → index-DwMyfQJq.js} +1 -1
  46. package/dist/assets/{index-CXMr3tiK.js → index-mvm_Pxcf.js} +1 -1
  47. package/dist/assets/{infoDiagram-42DDH7IO-VUMzEo4o.js → infoDiagram-42DDH7IO-Co9Db2ir.js} +1 -1
  48. package/dist/assets/{ishikawaDiagram-UXIWVN3A-BuzrU3sx.js → ishikawaDiagram-UXIWVN3A-4z7EydCd.js} +1 -1
  49. package/dist/assets/{journeyDiagram-VCZTEJTY-BZtR5BAF.js → journeyDiagram-VCZTEJTY-CtLfbhYE.js} +1 -1
  50. package/dist/assets/{jszip.min-CtodH5MV.js → jszip.min-DtbrAiWv.js} +1 -1
  51. package/dist/assets/{kanban-definition-6JOO6SKY-Cj_97xXb.js → kanban-definition-6JOO6SKY-9ZrhOvdX.js} +1 -1
  52. package/dist/assets/{layout-Du0I-tlh.js → layout-Ddo06NJO.js} +1 -1
  53. package/dist/assets/{linear-BJtxCASI.js → linear-BZUsBSwS.js} +1 -1
  54. package/dist/assets/{mermaid.core-QlorX0Yw.js → mermaid.core-O-x0KuTp.js} +2 -2
  55. package/dist/assets/{min-BVnQfunZ.js → min-PzJh19JL.js} +1 -1
  56. package/dist/assets/{mindmap-definition-QFDTVHPH-Bh_KL4qU.js → mindmap-definition-QFDTVHPH-C3MVo-7p.js} +1 -1
  57. package/dist/assets/{pieDiagram-DEJITSTG-Bvv0rC_q.js → pieDiagram-DEJITSTG-CMn9-kQc.js} +1 -1
  58. package/dist/assets/{quadrantDiagram-34T5L4WZ-Bw8cGCRU.js → quadrantDiagram-34T5L4WZ-9eyqTdkj.js} +1 -1
  59. package/dist/assets/{requirementDiagram-MS252O5E-Cg9jQ71h.js → requirementDiagram-MS252O5E-BJbuDOpR.js} +1 -1
  60. package/dist/assets/{sankeyDiagram-XADWPNL6-BXJo6-CD.js → sankeyDiagram-XADWPNL6-CzQ1KxD3.js} +1 -1
  61. package/dist/assets/seqResourceLoaders-DH-Nl0yh.css +41 -0
  62. package/dist/assets/seqResourceLoaders-DeqzMajS.js +2 -0
  63. package/dist/assets/{sequenceDiagram-FGHM5R23-D7zpGxwq.js → sequenceDiagram-FGHM5R23-CfmSEAYp.js} +1 -1
  64. package/dist/assets/{stateDiagram-FHFEXIEX-Der2CqR1.js → stateDiagram-FHFEXIEX-Brw2ZXQC.js} +1 -1
  65. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-DetvG_Lc.js → stateDiagram-v2-QKLJ7IA2-Dnyo23Rp.js} +1 -1
  66. package/dist/assets/{timeline-definition-GMOUNBTQ-0UenzEZ6.js → timeline-definition-GMOUNBTQ-DNi7GnlG.js} +1 -1
  67. package/dist/assets/{vendor-antd-I6I2F7Rv.js → vendor-antd-DWLgSkPo.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-Zkm6UHQg.js → vendor-codemirror-CKsm_iG4.js} +1 -1
  69. package/dist/assets/{vendor-mdxeditor-CC09MDyZ.js → vendor-mdxeditor-Dah6NK0y.js} +2 -2
  70. package/dist/assets/{vendor-qrcode-gZpmSeeh.js → vendor-qrcode-CDcb8weP.js} +1 -1
  71. package/dist/assets/{vendor-virtuoso-BGwznQ5y.js → vendor-virtuoso-DKUobZpA.js} +1 -1
  72. package/dist/assets/{vennDiagram-DHZGUBPP-COzYyZ5h.js → vennDiagram-DHZGUBPP-Cdkdx7gB.js} +1 -1
  73. package/dist/assets/{wardley-RL74JXVD-VZdOtN8t.js → wardley-RL74JXVD-YKzsVN4U.js} +1 -1
  74. package/dist/assets/{wardleyDiagram-NUSXRM2D-CVkL75Qy.js → wardleyDiagram-NUSXRM2D-gBsb6aut.js} +1 -1
  75. package/dist/assets/{xychartDiagram-5P7HB3ND-6CHBAYyF.js → xychartDiagram-5P7HB3ND-Bh63NWof.js} +1 -1
  76. package/dist/index.html +4 -4
  77. package/findcc.js +4 -4
  78. package/node_modules/@ccv/core/src/ask-auto-answer.js +122 -0
  79. package/node_modules/@ccv/core/src/contentFilter.js +4 -1
  80. package/node_modules/@ccv/core/src/ultraplanTemplates.js +199 -0
  81. package/package.json +1 -1
  82. package/server/i18n.js +4 -20
  83. package/server/lib/ask/ask-bridge.js +4 -1
  84. package/server/lib/ask/ask-reaper.js +1 -0
  85. package/server/lib/ask-auto-answer.js +153 -0
  86. package/server/lib/auto-approve.js +3 -1
  87. package/server/lib/binary-sniff.js +35 -0
  88. package/server/lib/ensure-hooks.js +134 -2
  89. package/server/lib/im/im-bridge-core.js +16 -0
  90. package/server/lib/scheduled-task-executor.js +14 -2
  91. package/server/lib/scheduled-task-store.js +129 -18
  92. package/server/lib/sdk-manager.js +178 -30
  93. package/server/pty-manager.js +103 -4
  94. package/server/routes/ask-perm.js +87 -6
  95. package/server/routes/files-content.js +46 -8
  96. package/server/routes/scheduled-tasks.js +13 -0
  97. package/server/server.js +100 -0
  98. package/server/system-prompt-templates/presets/kimi-k3.md +8 -0
  99. package/dist/assets/App-BN3viVRq.js +0 -2
  100. package/dist/assets/App-BvVdj099.css +0 -1
  101. package/dist/assets/Mobile-nbI6IeX_.js +0 -1
  102. package/dist/assets/classDiagram-6PBFFD2Q-BUmU_G-i.js +0 -1
  103. package/dist/assets/classDiagram-v2-HSJHXN6E-BUmU_G-i.js +0 -1
  104. package/dist/assets/clone-CvoOne2K.js +0 -1
  105. package/dist/assets/index-DoFyHmPM.js +0 -2
  106. package/dist/assets/seqResourceLoaders-DbccWwKz.css +0 -41
  107. package/dist/assets/seqResourceLoaders-n9iXZRHx.js +0 -2
@@ -2,8 +2,9 @@
2
2
  * Register AskUserQuestion and permission approval hooks into ~/.claude/settings.json.
3
3
  * Shared between cli.js and electron/tab-worker.js.
4
4
  */
5
- import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from 'node:fs';
6
- import { resolve } from 'node:path';
5
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, statSync, chmodSync } from 'node:fs';
6
+ import { resolve, join } from 'node:path';
7
+ import { homedir } from 'node:os';
7
8
  import { randomBytes } from 'node:crypto';
8
9
  import { getClaudeConfigDir } from '../../findcc.js';
9
10
  import { SERVER_LIB } from '../_paths.js';
@@ -385,3 +386,134 @@ export function ensureHooks() {
385
386
  console.warn('[CC Viewer] Failed to ensure hooks:', err.message);
386
387
  }
387
388
  }
389
+
390
+ // ─── .claude.json path resolution + onboarding/trust initialization ───
391
+ // Claude Code's global config file lives at a location that depends on whether
392
+ // CLAUDE_CONFIG_DIR is set and whether a `.config.json` override exists:
393
+ // 1. `<configDir>/.config.json` — highest precedence when it exists
394
+ // 2. `<configDir>/.claude.json` — custom config dir (e.g. CodeFuse engine cc dir)
395
+ // 3. `~/.claude.json` — default (home dir, NOT ~/.claude/.claude.json)
396
+ // Getting this wrong means the trust/onboarding write lands in a file Claude
397
+ // never reads, and the process stays blocked on the "Yes, I trust this folder" page.
398
+ export function resolveClaudeJsonPath(configDir) {
399
+ const expand = (d) => (typeof d === 'string' && d.startsWith('~/')) ? join(homedir(), d.slice(2)) : d;
400
+ const defaultDir = resolve(getClaudeConfigDir());
401
+ const dir = resolve(expand(configDir) || defaultDir);
402
+ const dotConfig = join(dir, '.config.json');
403
+ if (existsSync(dotConfig)) return dotConfig;
404
+ const explicitCustomDir = !!configDir && dir !== defaultDir;
405
+ const parentEnvSet = !!(process.env.CLAUDE_CONFIG_DIR && process.env.CLAUDE_CONFIG_DIR.trim() !== '');
406
+ if (explicitCustomDir || parentEnvSet) return join(dir, '.claude.json');
407
+ return resolve(defaultDir, '..', '.claude.json');
408
+ }
409
+
410
+ /**
411
+ * Ensure Claude Code's onboarding and trust state are pre-seeded in .claude.json
412
+ * so the process never blocks on interactive confirmation dialogs ("Yes, I accept"
413
+ * / "Yes, I trust this folder"). This is critical for headless IM workers where
414
+ * no human is present to press Enter.
415
+ *
416
+ * Fields written (idempotent, never overwrites user data):
417
+ * - `hasCompletedOnboarding: true` — skips the first-run onboarding flow
418
+ * - `trustedFolders[workspacePath] = true` — skips the directory trust dialog
419
+ * - `projects[workspacePath].hasTrustDialogAccepted = true` — newer Claude builds
420
+ * may key trust off this per-project field instead of (or in addition to)
421
+ * `trustedFolders`
422
+ *
423
+ * Safety invariant: if the target file exists but is unreadable/corrupt, we
424
+ * NEVER write back — a blind overwrite would destroy the user's projects,
425
+ * mcpServers, oauthAccount, etc. (same rule as ensureApiKeyApproved).
426
+ *
427
+ * Writes are atomic (tmp file + rename) and preserve the original file mode.
428
+ */
429
+ export function ensureOnboardingAndTrust({ configDir, workspacePath } = {}) {
430
+ try {
431
+ const claudeJsonPath = resolveClaudeJsonPath(configDir || getClaudeConfigDir());
432
+ let claudeJson = null;
433
+ if (existsSync(claudeJsonPath)) {
434
+ try {
435
+ claudeJson = JSON.parse(readFileSync(claudeJsonPath, 'utf-8'));
436
+ if (!claudeJson || typeof claudeJson !== 'object' || Array.isArray(claudeJson)) {
437
+ console.warn(`[cc-viewer] ${claudeJsonPath} is not a JSON object, skipping onboarding/trust write`);
438
+ return;
439
+ }
440
+ } catch (err) {
441
+ // P0 safety rule: unreadable/corrupt file → never overwrite.
442
+ console.warn(`[cc-viewer] ${claudeJsonPath} is unreadable/unparseable (${err.message}), skipping onboarding/trust write to avoid overwriting user config`);
443
+ return;
444
+ }
445
+ } else {
446
+ claudeJson = {}; // first run: safe to start from empty object
447
+ }
448
+
449
+ let dirty = false;
450
+ // 1) hasCompletedOnboarding: skip the "Yes, I accept" first-run dialog.
451
+ if (claudeJson.hasCompletedOnboarding !== true) {
452
+ claudeJson.hasCompletedOnboarding = true;
453
+ dirty = true;
454
+ }
455
+ // 2) bypassPermissionsModeAccepted: skip the "Bypass Permissions mode" warning
456
+ // that appears when --dangerously-skip-permissions is used on a fresh config.
457
+ // IM workers always launch with this flag, so this is required to prevent
458
+ // the hang from moving from the trust page to the bypass page.
459
+ if (claudeJson.bypassPermissionsModeAccepted !== true) {
460
+ claudeJson.bypassPermissionsModeAccepted = true;
461
+ dirty = true;
462
+ }
463
+ // 3) trustedFolders: skip the "Do you trust this folder" dialog.
464
+ // NOTE: Claude Code 2.1.199 does not actually read this field (verified
465
+ // against the binary); it is written for forward compatibility only.
466
+ // Normalize the key the same way Claude does: path.normalize + forward
467
+ // slashes on Windows, NFC on all platforms.
468
+ if (workspacePath) {
469
+ const normPath = resolve(workspacePath).replace(/\\/g, '/').normalize('NFC');
470
+ const trusted = claudeJson.trustedFolders && typeof claudeJson.trustedFolders === 'object' && !Array.isArray(claudeJson.trustedFolders)
471
+ ? claudeJson.trustedFolders
472
+ : {};
473
+ if (!trusted[normPath]) {
474
+ trusted[normPath] = true;
475
+ claudeJson.trustedFolders = trusted;
476
+ dirty = true;
477
+ }
478
+ }
479
+ // 4) projects[workspacePath].hasTrustDialogAccepted: the field Claude Code
480
+ // 2.1.199 actually checks (verified against the binary). This is the
481
+ // operative trust mechanism. Same normalization as above.
482
+ if (workspacePath) {
483
+ const normPath = resolve(workspacePath).replace(/\\/g, '/').normalize('NFC');
484
+ if (!claudeJson.projects || typeof claudeJson.projects !== 'object' || Array.isArray(claudeJson.projects)) {
485
+ claudeJson.projects = {};
486
+ }
487
+ const proj = claudeJson.projects[normPath];
488
+ if (!proj || typeof proj !== 'object' || Array.isArray(proj)) {
489
+ claudeJson.projects[normPath] = { hasTrustDialogAccepted: true };
490
+ dirty = true;
491
+ } else if (proj.hasTrustDialogAccepted !== true) {
492
+ proj.hasTrustDialogAccepted = true;
493
+ dirty = true;
494
+ }
495
+ }
496
+
497
+ if (dirty) {
498
+ // Atomic write: tmp file + rename, preserving original file mode.
499
+ // Create the tmp file with the target permissions from the start (0o600 for
500
+ // a new file — .claude.json may contain credentials), so the content is
501
+ // never briefly world-readable between write and chmod.
502
+ const tmpPath = `${claudeJsonPath}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`;
503
+ try {
504
+ let targetMode = 0o600; // safe default for a new file holding credentials
505
+ try {
506
+ targetMode = statSync(claudeJsonPath).mode & 0o777;
507
+ } catch { /* file doesn't exist yet — use safe default */ }
508
+ writeFileSync(tmpPath, JSON.stringify(claudeJson, null, 2), { encoding: 'utf-8', mode: targetMode });
509
+ renameSyncWithRetry(tmpPath, claudeJsonPath);
510
+ } catch (err) {
511
+ try { if (existsSync(tmpPath)) unlinkSync(tmpPath); } catch { /* ignore */ }
512
+ throw err;
513
+ }
514
+ }
515
+ } catch (err) {
516
+ console.warn('[cc-viewer] Failed to ensure onboarding/trust in .claude.json:', err.message);
517
+ }
518
+ }
519
+
@@ -606,6 +606,22 @@ function drainQueue(inst) {
606
606
  void sendReply(inst, item, tr(inst, 'noSession'));
607
607
  continue;
608
608
  }
609
+ // Boot-state gate: when the Claude PTY is blocked on an interactive dialog
610
+ // (trust confirmation, onboarding), fail fast with a clear error instead of
611
+ // letting the message sit until the 120s timeout. This turns a silent hang
612
+ // into an actionable diagnostic.
613
+ // NOTE: 'exited' is NOT handled here — the !st.running check above already
614
+ // catches exited PTYs and replies 'noSession'. This gate only covers the
615
+ // "running but blocked on a dialog" case.
616
+ if (typeof d.getPtyBootState === 'function') {
617
+ const bootState = d.getPtyBootState();
618
+ if (bootState === 'blocked-on-trust' || bootState === 'blocked-on-onboarding') {
619
+ inst.queue.shift();
620
+ audit(inst, 'startup-blocked', { conversationId: item.conversationId, bootState });
621
+ void sendReply(inst, item, tr(inst, 'startupError'));
622
+ continue;
623
+ }
624
+ }
609
625
  inst.queue.shift();
610
626
  const cfg = d.getConfig();
611
627
  const skipPerm = d.getPtySkipPermissions();
@@ -11,6 +11,13 @@
11
11
  // Result contract:
12
12
  // inject → { status:'dispatched' } | { status:'failed', reason }
13
13
  // spawn → { status:'completed', sessionId, durationMs } | { status:'error', reason, error? }
14
+ //
15
+ // The stored task.prompt is the RAW user text; the UltraPlan template wrapper and the
16
+ // quoted attachment paths are assembled HERE at fire time (assembleScheduledPrompt,
17
+ // shared with the web hosts via @ccv/core) so the stored prompt stays editable and
18
+ // summaries/toasts stay human-readable.
19
+
20
+ import { assembleScheduledPrompt } from '@ccv/core/ultraplanTemplates';
14
21
 
15
22
  /**
16
23
  * @param {object} task the claimed task (has .mode/.prompt/.cwd/.project/.schedule)
@@ -25,8 +32,13 @@
25
32
  * }
26
33
  */
27
34
  export async function executeScheduledTask(task, claim, io) {
28
- if (task.mode === 'spawn') return _spawn(task, claim, io);
29
- return io.isSdkMode ? _injectSdk(task, io) : _injectPty(task, io);
35
+ // Assemble once: template wrapper + quoted attachment paths + raw prompt text.
36
+ // An empty assembly (no text, no attachments) means there is nothing to dispatch.
37
+ const prompt = assembleScheduledPrompt(task);
38
+ if (!prompt) return { status: 'failed', reason: 'invalid_prompt' };
39
+ const resolved = { ...task, prompt };
40
+ if (task.mode === 'spawn') return _spawn(resolved, claim, io);
41
+ return io.isSdkMode ? _injectSdk(resolved, io) : _injectPty(resolved, io);
30
42
  }
31
43
 
32
44
  async function _injectSdk(task, io) {
@@ -31,7 +31,7 @@
31
31
  // Boundary: L1-lib. Imports L1 (cron/schedule-model/json-store/scheduled-task-runs-store)
32
32
  // + L0-leaf (pid-alive) + node builtins. Must NOT import L2 (pty-manager/sdk-manager/…).
33
33
 
34
- import { join } from 'node:path';
34
+ import { join, isAbsolute } from 'node:path';
35
35
  import { randomBytes } from 'node:crypto';
36
36
  import { existsSync, readFileSync } from 'node:fs';
37
37
  import { mutateJson, readJsonStrict } from './json-store.js';
@@ -39,6 +39,7 @@ import { isPidAlive } from './pid-alive.js';
39
39
  import { normalizeSchedule, nextBaseFor, occurrencesAtOrBefore, jitterForTaskId } from './schedule-model.js';
40
40
  import { appendRuns, appendRun, deleteRunsForTask, findRunByClaimId } from './scheduled-task-runs-store.js';
41
41
  import { reportSwallowed } from './error-report.js';
42
+ import { assembleScheduledPrompt } from '@ccv/core/ultraplanTemplates';
42
43
 
43
44
  const LEGACY_FILE_NAME = 'scheduled-tasks.json';
44
45
  const PREFS_FILE_NAME = 'preferences.json';
@@ -46,6 +47,11 @@ const VERSION = 1;
46
47
  const MAX_TASKS_PER_PROJECT = 50;
47
48
  const MAX_RUNS = 20;
48
49
  const MAX_PROMPT_LEN = 20_000;
50
+ // Attachments ride the task so the executor can prefix quoted paths at fire time
51
+ // (the stored prompt stays the raw user text). Bounded: prefs is pretty-printed and
52
+ // rewritten on every claim/finalize, so strings must not be unbounded.
53
+ const MAX_ATTACHMENTS = 20;
54
+ const MAX_ATTACHMENT_STR = 1024;
49
55
  const SUMMARY_LEN = 200;
50
56
  const CATCH_UP_WINDOW_MS = 7 * 24 * 3600 * 1000; // 7 days
51
57
  // A claim whose owner pid is unreadable is reclaimed after this age (pid-reuse
@@ -152,13 +158,79 @@ export function mutateScheduledTasks(root, mutator) {
152
158
  }
153
159
 
154
160
  function _newId(prefix) { return `${prefix}_${randomBytes(8).toString('hex')}`; }
161
+
162
+ // A stored path becomes a quoted prefix in the fire-time prompt, so it must be a
163
+ // plain absolute path: no quotes, no control chars (LF/CR/ESC would break the
164
+ // single-line structure and could smuggle hidden instructions into the prompt).
165
+ function _isValidAttachmentPath(p) {
166
+ if (typeof p !== 'string' || !p || p.length > MAX_ATTACHMENT_STR) return false;
167
+ if (!isAbsolute(p)) return false;
168
+ // eslint-disable-next-line no-control-regex
169
+ if (/[\x00-\x1f\x7f"\\]/.test(p)) return false;
170
+ return true;
171
+ }
172
+
173
+ // Validate + normalize a task's UltraPlan fields. Absent fields → {} (no change /
174
+ // not set), so old clients and partial updates (pause/resume) are unaffected.
175
+ // Returns { ok:true, fields } | { ok:false, reason }.
176
+ function _normalizeUltraplanFields(draft) {
177
+ const fields = {};
178
+ if (draft.template !== undefined) {
179
+ if (typeof draft.template !== 'string' || !draft.template || draft.template.length > 200) {
180
+ return { ok: false, reason: 'invalid_template' };
181
+ }
182
+ fields.template = draft.template;
183
+ }
184
+ if (draft.templateContent !== undefined) {
185
+ if (typeof draft.templateContent !== 'string' || draft.templateContent.length > MAX_PROMPT_LEN) {
186
+ return { ok: false, reason: 'invalid_template' };
187
+ }
188
+ fields.templateContent = draft.templateContent;
189
+ }
190
+ if (draft.attachments !== undefined) {
191
+ const list = draft.attachments;
192
+ if (!Array.isArray(list) || list.length > MAX_ATTACHMENTS) return { ok: false, reason: 'invalid_attachments' };
193
+ for (const a of list) {
194
+ if (!a || typeof a !== 'object'
195
+ || typeof a.name !== 'string' || !a.name || a.name.length > MAX_ATTACHMENT_STR
196
+ || !_isValidAttachmentPath(a.path)) {
197
+ return { ok: false, reason: 'invalid_attachments' };
198
+ }
199
+ }
200
+ fields.attachments = list.map(a => ({ name: a.name, path: a.path }));
201
+ }
202
+ return { ok: true, fields };
203
+ }
204
+
205
+ // Final bound on what actually gets dispatched. The per-field caps above allow a
206
+ // combined ~60KB prompt (20k text + 20k template + 20×1KB paths); cap the assembled
207
+ // result so the injected prompt stays within the documented maximum.
208
+ function _assembledWithinLimit(fields, task) {
209
+ const probe = {
210
+ prompt: fields.prompt !== undefined ? fields.prompt : task?.prompt,
211
+ template: fields.template !== undefined ? fields.template : task?.template,
212
+ templateContent: fields.templateContent !== undefined ? fields.templateContent : task?.templateContent,
213
+ attachments: fields.attachments !== undefined ? fields.attachments : task?.attachments,
214
+ };
215
+ return assembleScheduledPrompt(probe).length <= MAX_PROMPT_LEN;
216
+ }
217
+
155
218
  function _summarize(prompt) {
156
219
  const s = String(prompt == null ? '' : prompt).replace(/\s+/g, ' ').trim();
157
220
  return s.length > SUMMARY_LEN ? `${s.slice(0, SUMMARY_LEN - 1)}…` : s;
158
221
  }
159
222
 
223
+ // Attachments-only tasks have an empty prompt — fall back to the attachment names so
224
+ // run history and completion toasts never render a blank summary.
225
+ function _summarizeTask(task) {
226
+ const s = _summarize(task.prompt);
227
+ if (s) return s;
228
+ const names = (Array.isArray(task.attachments) ? task.attachments : []).map(a => a.name).filter(Boolean);
229
+ return names.length ? `[${names.join(', ')}]` : s;
230
+ }
231
+
160
232
  function _makeRun(task, fields) {
161
- return { id: _newId('run'), summary: _summarize(task.prompt), ...fields };
233
+ return { id: _newId('run'), summary: _summarizeTask(task), ...fields };
162
234
  }
163
235
 
164
236
  // History is best-effort: a flush failure is reported but never fails the state change
@@ -207,16 +279,23 @@ export function getTask(root, id) {
207
279
  }
208
280
 
209
281
  /**
210
- * Create a task. draft = { project, cwd, prompt, mode, schedule, enabled }.
282
+ * Create a task. draft = { project, cwd, prompt, mode, schedule, enabled,
283
+ * template?, templateContent?, attachments? }. prompt is the RAW user text; the
284
+ * UltraPlan wrapper + attachment paths are assembled at fire time (executor).
211
285
  * The ONLY writer allowed to create the `scheduledTasks` prefs key (legacy tombstone).
212
286
  */
213
287
  export async function createTask(root, draft, now = Date.now()) {
214
288
  const norm = normalizeSchedule(draft.schedule, now);
215
289
  if (!norm.ok) return { ok: false, reason: norm.error, detail: norm.detail };
216
290
  const prompt = String(draft.prompt == null ? '' : draft.prompt).trim();
217
- if (!prompt) return { ok: false, reason: 'invalid_prompt' };
218
- if (prompt.length > MAX_PROMPT_LEN) return { ok: false, reason: 'invalid_prompt', detail: 'too long' };
219
291
  if (draft.mode !== 'inject' && draft.mode !== 'spawn') return { ok: false, reason: 'invalid_mode' };
292
+ const ultra = _normalizeUltraplanFields(draft);
293
+ if (!ultra.ok) return { ok: false, reason: ultra.reason };
294
+ // An empty prompt is fine when attachments carry the task (they become the fire-time
295
+ // prompt prefix); "both empty" is rejected.
296
+ if (!prompt && (ultra.fields.attachments || []).length === 0) return { ok: false, reason: 'invalid_prompt' };
297
+ if (prompt.length > MAX_PROMPT_LEN) return { ok: false, reason: 'invalid_prompt', detail: 'too long' };
298
+ if (!_assembledWithinLimit(ultra.fields, { prompt })) return { ok: false, reason: 'invalid_prompt', detail: 'assembled too long' };
220
299
 
221
300
  return mutateScheduledTasks(root, (reg) => {
222
301
  const sameProject = reg.tasks.filter(t => t.project === draft.project);
@@ -229,6 +308,10 @@ export async function createTask(root, draft, now = Date.now()) {
229
308
  mode: draft.mode,
230
309
  schedule: norm.schedule,
231
310
  permissionMode: draft.mode === 'spawn' ? (draft.permissionMode === 'inherit' ? 'inherit' : 'default') : undefined,
311
+ // UltraPlan fields are omitted (not null) when absent so old tasks keep their shape.
312
+ ...(ultra.fields.template !== undefined ? { template: ultra.fields.template } : {}),
313
+ ...(ultra.fields.templateContent !== undefined ? { templateContent: ultra.fields.templateContent } : {}),
314
+ ...(ultra.fields.attachments !== undefined ? { attachments: ultra.fields.attachments } : {}),
232
315
  enabled: draft.enabled !== false,
233
316
  jitterMs: undefined,
234
317
  nextBaseAt: null,
@@ -249,12 +332,33 @@ export async function createTask(root, draft, now = Date.now()) {
249
332
  }
250
333
 
251
334
  /**
252
- * Update prompt / mode / schedule / enabled. Recomputes next ONLY when schedule or
253
- * enabled changed. Never clobbers an active claim. Resume does NOT catch up; it records
254
- * a skipped/paused run (flushed to the runs file after the prefs write).
335
+ * Update prompt / mode / schedule / enabled and the UltraPlan fields (template,
336
+ * templateContent, attachments — absent = no change). Recomputes next ONLY when
337
+ * schedule or enabled changed. Never clobbers an active claim. Resume does NOT catch
338
+ * up; it records a skipped/paused run (flushed to the runs file after the prefs write).
339
+ *
340
+ * Validation is fully staged BEFORE any mutation: mutateJson writes the file even when
341
+ * the mutator reports failure, so validating after mutating would persist a
342
+ * half-applied patch on a rejected update.
255
343
  */
256
344
  export async function updateTask(root, id, patch, now = Date.now()) {
257
345
  if (_isLegacy(root)) return { ok: false, reason: 'task_not_found' };
346
+ // Field-shape validation first (cheap, no lock).
347
+ const ultra = _normalizeUltraplanFields(patch);
348
+ if (!ultra.ok) return { ok: false, reason: ultra.reason };
349
+ if (patch.prompt !== undefined) {
350
+ const p = String(patch.prompt).trim();
351
+ if (p.length > MAX_PROMPT_LEN) return { ok: false, reason: 'invalid_prompt' };
352
+ }
353
+ if (patch.mode !== undefined && patch.mode !== 'inject' && patch.mode !== 'spawn') {
354
+ return { ok: false, reason: 'invalid_mode' };
355
+ }
356
+ // Schedule validation before the lock too (it only depends on the patch + now).
357
+ let stagedNorm;
358
+ if (patch.schedule !== undefined) {
359
+ const norm = normalizeSchedule(patch.schedule, now);
360
+ stagedNorm = norm; // once_in_past may still be forgiven inside the lock (at unchanged)
361
+ }
258
362
  const pendingRuns = [];
259
363
  const out = await mutateScheduledTasks(root, (reg) => {
260
364
  const task = reg.tasks.find(t => t.id === id);
@@ -262,15 +366,6 @@ export async function updateTask(root, id, patch, now = Date.now()) {
262
366
  let scheduleChanged = false;
263
367
  let enabledChanged = false;
264
368
 
265
- if (patch.prompt !== undefined) {
266
- const prompt = String(patch.prompt).trim();
267
- if (!prompt || prompt.length > MAX_PROMPT_LEN) return { ok: false, reason: 'invalid_prompt' };
268
- task.prompt = prompt;
269
- }
270
- if (patch.mode !== undefined) {
271
- if (patch.mode !== 'inject' && patch.mode !== 'spawn') return { ok: false, reason: 'invalid_mode' };
272
- task.mode = patch.mode;
273
- }
274
369
  if (patch.schedule !== undefined) {
275
370
  // once.at>=now+60s is only enforced when `at` itself changes: the UI always sends the
276
371
  // full schedule back on save, so a prompt edit on an expired once task would otherwise
@@ -278,7 +373,7 @@ export async function updateTask(root, id, patch, now = Date.now()) {
278
373
  const atUnchanged = patch.schedule && patch.schedule.kind === 'once'
279
374
  && task.schedule && task.schedule.kind === 'once'
280
375
  && Number(patch.schedule.at) === Number(task.schedule.at);
281
- const norm = normalizeSchedule(patch.schedule, now);
376
+ const norm = stagedNorm;
282
377
  if (!norm.ok) {
283
378
  if (!(atUnchanged && norm.error === 'once_in_past')) {
284
379
  return { ok: false, reason: norm.error, detail: norm.detail };
@@ -288,6 +383,22 @@ export async function updateTask(root, id, patch, now = Date.now()) {
288
383
  if (!atUnchanged) delete task.jitterMs;
289
384
  scheduleChanged = true;
290
385
  }
386
+ if (patch.mode !== undefined) task.mode = patch.mode;
387
+ // Cross-field invariant on the MERGED result, computed BEFORE any mutation:
388
+ // mutateJson persists even when the mutator reports failure, so a both-empty
389
+ // rejection must not leave attachments/prompt half-cleared on disk.
390
+ const mergedPrompt = patch.prompt !== undefined ? String(patch.prompt).trim() : task.prompt;
391
+ const mergedAttachments = ultra.fields.attachments !== undefined ? ultra.fields.attachments : (task.attachments || []);
392
+ if (!String(mergedPrompt || '').trim() && mergedAttachments.length === 0) {
393
+ return { ok: false, reason: 'invalid_prompt' };
394
+ }
395
+ if (!_assembledWithinLimit({ ...ultra.fields, prompt: mergedPrompt }, task)) {
396
+ return { ok: false, reason: 'invalid_prompt', detail: 'assembled too long' };
397
+ }
398
+ if (ultra.fields.template !== undefined) task.template = ultra.fields.template;
399
+ if (ultra.fields.templateContent !== undefined) task.templateContent = ultra.fields.templateContent;
400
+ if (ultra.fields.attachments !== undefined) task.attachments = ultra.fields.attachments;
401
+ if (patch.prompt !== undefined) task.prompt = mergedPrompt;
291
402
  if (patch.enabled !== undefined && patch.enabled !== task.enabled) {
292
403
  task.enabled = !!patch.enabled;
293
404
  enabledChanged = true;