cc-viewer 1.9.22 → 1.9.23

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.
package/findcc.js CHANGED
@@ -201,7 +201,7 @@ export function resolveExplicitClaudePath(value, platform = process.platform) {
201
201
  } catch { return null; }
202
202
  let real = expanded;
203
203
  try { real = realpathSync(expanded); } catch { }
204
- const isJs = real.toLowerCase().endsWith('.js');
204
+ const isJs = real.toLowerCase().endsWith('.js') || real.toLowerCase().endsWith('.cjs');
205
205
  try {
206
206
  if (isJs) {
207
207
  accessSync(real, fsConstants.R_OK);
@@ -571,7 +571,7 @@ export function resolveClaudeFromPath() {
571
571
 
572
572
  let real = result;
573
573
  try { real = realpathSync(result); } catch { }
574
- if (real.endsWith('.js')) return { path: real, isNpmVersion: true };
574
+ if (real.endsWith('.js') || real.endsWith('.cjs')) return { path: real, isNpmVersion: true };
575
575
  return { path: result, isNpmVersion: false };
576
576
  } catch {
577
577
  // Try the next lookup command.
@@ -630,12 +630,12 @@ export function resolveNativePath() {
630
630
  // win32 过滤掉 sh shim / .cmd / .ps1,只取 .exe(否则 ConPTY spawn 报 error 193)
631
631
  const result = pickSpawnableLookupResult(rawOut);
632
632
  if (result && existsSync(result)) {
633
- // 只排除 .js 文件(老版本 npm 分发的 cli.js,需要 node 运行,
633
+ // 只排除 .js/.cjs 文件(npm 分发的 Node 入口,需要 node 运行,
634
634
  // 由 resolveNpmClaudePath 处理)。Claude Code 2.x+ 的 npm 包内
635
635
  // 直接打包了原生二进制(bin/claude.exe),应当作 native 处理。
636
636
  let real = result;
637
637
  try { real = realpathSync(result); } catch { }
638
- if (real.endsWith('.js')) continue;
638
+ if (real.endsWith('.js') || real.endsWith('.cjs')) continue;
639
639
  return result;
640
640
  }
641
641
  } catch {
@@ -610,7 +610,10 @@ let _registryScanned = new WeakSet();
610
610
  // Identify the session by the first request's timestamp; auto-reset on switch
611
611
  let _registrySessionKey = null;
612
612
 
613
- const PROMPT_PREFIX_LEN = 60;
613
+ export const PROMPT_PREFIX_LEN = 60;
614
+ // Shared cap on the retained prompt snippet for agent tasks — the web tracker and
615
+ // the server replay table must truncate identically for prompt-prefix joins.
616
+ export const AGENT_PROMPT_SNIPPET_LEN = 1024;
614
617
  const TM_TAG_RE = /<teammate-message[^>]*>/;
615
618
 
616
619
  /**
@@ -0,0 +1,199 @@
1
+ // Ultraplan prompt templates for local Claude Code execution.
2
+ // Shared isomorphic module (@ccv/core): the web hosts (TerminalPanel / ChatView) assemble
3
+ // at send time, and the scheduled-task executor (packages/app) assembles at fire time —
4
+ // one source of truth so the wrapper can never drift between the two.
5
+ //
6
+ // Two expert roles:
7
+ // - codeExpert: Multi-agent code planning & implementation (from subagents template)
8
+ // - researchExpert: Multi-agent research & analysis
9
+ // Plus the 'none' variant: no template wrapper, the user input is sent as-is.
10
+ //
11
+ // Assembly logic mirrors ~/claude-code/commands/ultraplan.tsx:63-73
12
+ // buildUltraplanPrompt(blurb, seedPlan?)
13
+
14
+ export const ULTRAPLAN_VARIANTS = {
15
+
16
+ codeExpert: `<system-reminder>
17
+ [SCOPED INSTRUCTION] The following instructions apply only to the next 1–3 interactions. Once the task is complete, these instructions should gradually decrease in priority and no longer affect subsequent interactions. You should be adept at utilizing tools such as \`AskUserQuestion\` and \`EnterPlanMode\`, rather than relying solely on plain text processing. Before execution, you must ensure that the \`EnterPlanMode\`, \`ExitPlanMode\`, \`SendMessage\`, \`TaskCreate\`, \`TaskUpdate\`, \`TaskStop\`, \`TaskGet\`, \`TaskOutput\` and \`TaskList\` tools are loaded.
18
+
19
+ Pre-requisite: Use \`AskUserQuestion\` to clarify user intent whenever the request is ambiguous (target element, interaction style, scope of platforms, etc.). Skip only if the intent is unambiguous.
20
+
21
+ Leverage a multi-agent exploration mechanism to formulate a highly detailed implementation plan.
22
+
23
+ Instructions:
24
+ 1. Use the \`Agent\` tool to spawn parallel agents that simultaneously explore different aspects of the codebase:
25
+ - If necessary, assign a preliminary researcher to use the \`webSearch\` tool to first investigate cutting-edge solutions in the relevant industry domain;
26
+ - One agent responsible for understanding the relevant existing code and architecture;
27
+ - One agent responsible for identifying all files that need to be modified;
28
+ - One agent responsible for identifying potential risks, edge cases, and dependencies;
29
+ - You may add other roles or deploy additional agents beyond the three listed above; the maximum number of concurrently dispatched agents is 5.
30
+
31
+ 2. Synthesize the findings from all agents into a detailed, step-by-step implementation plan.
32
+
33
+ 3. Use the \`Agent\` tool to spawn 2-3 review agents that examine the plan from different perspectives, checking for missing steps, potential risks, or corresponding mitigation strategies.
34
+
35
+ 4. Integrate the feedback gathered during the review process, then call \`ExitPlanMode\` to submit your final plan.
36
+
37
+ 5. Once \`ExitPlanMode\` returns a result:
38
+ - If approved: proceed to execute the plan within this session.
39
+ - If rejected: revise the plan based on the feedback provided and call \`ExitPlanMode\` again.
40
+ - If an error occurs (including receiving a "Not in Plan Mode" message): do **not** follow the suggestions provided in the error message; instead, prompt the user for further instructions.
41
+
42
+ Your final plan must include the following elements:
43
+ - A clear summary of the implementation strategy;
44
+ - An ordered list of files to be created or modified, with precise details of the required changes for each file;
45
+ - A step-by-step execution sequence;
46
+ - Testing and validation procedures;
47
+ - Potential risks and their corresponding mitigation strategies;
48
+
49
+ 6. After the final plan has been successfully executed:
50
+ First run \`git diff --quiet && git diff --cached --quiet\` (or equivalent) to detect whether the working tree actually has non-trivial changes; if there are no real changes (or only whitespace/comment-only edits), skip the UltraReview step.
51
+ Otherwise, if the project is managed with Git:
52
+ Use the \`Agent\` tool to build a team, dynamically allocating the number of teammates based on task complexity (5+ recommended);
53
+ Note: spawn teammates (which have a \`name\`), not plain subagents (which have no name);
54
+ Task: Conduct a Code Review of the current git changes from multiple roles and perspectives;
55
+ Pre-requisites:
56
+ - The git repository may be located in a subdirectory of the current directory; recursively locate the \`.git\` directory first before proceeding;
57
+ - In the case of multiple repositories, review tasks may be executed separately per repository;
58
+ Review dimensions (a reference framework — each role covers them as its perspective requires, aiming to be as comprehensive as possible):
59
+ - Whether requirements/objectives have been met and functionality is complete;
60
+ - Whether newly added code introduces side effects, breaks existing functionality, or poses potential risks;
61
+ - Code quality: naming, readability, complexity, technical debt, maintainability;
62
+ - Testing and documentation: whether there is adequate test coverage, and whether critical logic has necessary comments or documentation;
63
+ - Dependencies and compatibility: whether new dependencies or version compatibility issues have been introduced;
64
+ - Any other dimensions you see fit;
65
+ Workflow:
66
+ - Each teammate, according to their own role, covers the review dimensions one by one and independently outputs a report;
67
+ - After consolidating the reports, perform a cross-review to identify conflicts or shared concerns;
68
+ - Distill specific, actionable modification suggestions and annotate them with priority levels (P0/P1/P2/P3);
69
+ - Upon completion, fix all P0 and P1 items; evaluate P2 items dialectically (use \`AskUserQuestion\` to consult the user when any item needs a special decision);
70
+ - After execution is complete, close the team: notify each teammate to exit individually;
71
+ </system-reminder>`,
72
+
73
+ researchExpert: `<system-reminder>
74
+ [SCOPED INSTRUCTION] The following instructions are intended for the next 1–3 interactions. Once the task is complete, these instructions should be gradually deprioritized and no longer influence subsequent interactions.You should be adept at utilizing tools such as \`AskUserQuestion\`, \`EnterPlanMode\` and \`WebSearch\`, rather than relying solely on plain text processing. Before execution, you must ensure that the \`EnterPlanMode\`, \`ExitPlanMode\`, \`TaskCreate\`, \`TaskUpdate\`, \`TaskStop\`, \`TaskGet\`, \`TaskOutput\` and \`TaskList\` tools are loaded.
75
+
76
+ Pre-requisite: Use \`AskUserQuestion\` to clarify the research scope, target audience, and deliverable format whenever the user's intent is ambiguous. Skip only if the intent is unambiguous.
77
+
78
+ Leverage a multi-agent exploration mechanism to formulate an exceptionally detailed implementation plan.
79
+
80
+ Instructions:
81
+ 1. Utilize the Agent tool to spawn parallel agents that simultaneously explore various facets of the requirements:
82
+ - If necessary, deploy a preliminary investigator to conduct an initial survey of industry-specific solutions using \`webSearch\`;
83
+ - If necessary, deploy a specialized investigator to research authoritative sources—such as academic papers, news articles, and research reports—using \`webSearch\`;
84
+ - Assign an agent to synthesize the target solution, while simultaneously verifying the rigor and credibility of the gathered papers, news, and research reports;
85
+ - If necessary, assign an agent to analyze competitor data to provide supplementary analytical perspectives;
86
+ - If necessary, assign an agent to handle the implementation of a product demo (generating outputs such as HTML, Markdown, etc.);
87
+ - If the task is sufficiently complex, you may assign additional teammates to the roles defined above, or introduce other specialized roles; you are permitted to schedule up to 5 teammates concurrently.
88
+
89
+ 2. Synthesize the findings from the aforementioned agents into a comprehensive, step-by-step implementation plan.
90
+
91
+ 3. Utilize the Agent tool to spawn a set of parallel review agents; these agents shall scrutinize the plan from multiple roles and perspectives to identify any omitted steps and to propose reasonable additions or optimizations.
92
+
93
+ 4. Consolidate the feedback received from the review agents, then invoke \`ExitPlanMode\` to submit your final plan.
94
+
95
+ 5. Upon receiving the result from \`ExitPlanMode\`:
96
+ - If Approved: Proceed to execute the plan within this current session.
97
+ - If Rejected: Revise the plan based on the provided feedback, and then invoke \`ExitPlanMode\` once again.
98
+ - If an Error Occurs (including the message "Not in Plan Mode"): Do *not* follow the suggestions provided by the error message; instead, prompt the user for further instructions.
99
+
100
+ Your final plan must include the following elements:
101
+ - A clear summary of the proposed implementation strategy;
102
+ - An ordered list of files to be created or modified, specifying the exact changes required for each;
103
+ - A step-by-step sequence for executing the implementation;
104
+ - Identification of potential risks and corresponding mitigation strategies;
105
+ - Creative ideation and suggestions for advanced enhancements;
106
+ - If a product demo was generated, place the corresponding demo output in an appropriate location and notify the user.
107
+ </system-reminder>`,
108
+
109
+ };
110
+
111
+ /**
112
+ * Wrap user-authored custom instruction body with the same scoped-instruction
113
+ * preamble used by the built-in variants. Produces a full <system-reminder>
114
+ * block ready to be inlined into a Claude Code prompt.
115
+ */
116
+ export function buildCustomTemplate(content) {
117
+ const body = (content || '').trim();
118
+ if (!body) return '';
119
+ // A body that already carries the wrapper shell (the prefilled skeleton or a
120
+ // hand-written one) must not be wrapped again; startsWith (not includes) so a
121
+ // body that merely *mentions* the tag in prose still gets the scope preamble.
122
+ if (body.startsWith('<system-reminder>')) return body;
123
+ return `<system-reminder>
124
+ [SCOPED INSTRUCTION] The following instructions apply only to the next 1–3 interactions. Once the task is complete, these instructions should gradually decrease in priority and no longer affect subsequent interactions. You should be adept at utilizing tools such as \`AskUserQuestion\` and \`EnterPlanMode\`, rather than relying solely on plain text processing.
125
+
126
+ ${body}
127
+ </system-reminder>`;
128
+ }
129
+
130
+ /**
131
+ * Assemble a local ultraplan prompt.
132
+ * Mirrors ~/claude-code/commands/ultraplan.tsx:63-73 buildUltraplanPrompt()
133
+ *
134
+ * @param {string} userPrompt - User's task description
135
+ * @param {'none'|'codeExpert'|'researchExpert'|'custom'} variant - Template variant;
136
+ * 'none' returns the user prompt as-is (no wrapper).
137
+ * @param {string} [seedPlan] - Optional draft plan to refine
138
+ * @param {string} [customContent] - Required when variant === 'custom': the user-authored body
139
+ * @returns {string} Assembled prompt ready to send to Claude Code
140
+ */
141
+ export function buildLocalUltraplan(userPrompt, variant = 'codeExpert', seedPlan, customContent) {
142
+ // 'none' is the empty template: send the user input verbatim. seedPlan only
143
+ // makes sense together with a wrapper, so it is ignored here.
144
+ if (variant === 'none') return userPrompt || '';
145
+ let template;
146
+ if (variant === 'custom') {
147
+ template = buildCustomTemplate(customContent);
148
+ if (!template) return '';
149
+ } else {
150
+ template = ULTRAPLAN_VARIANTS[variant] || ULTRAPLAN_VARIANTS.codeExpert;
151
+ }
152
+ const parts = [];
153
+ if (seedPlan) {
154
+ parts.push('Here is a draft plan to refine:', '', seedPlan, '');
155
+ }
156
+ parts.push(template);
157
+ if (userPrompt) {
158
+ parts.push('', userPrompt);
159
+ }
160
+ return parts.join('\n');
161
+ }
162
+
163
+ /**
164
+ * Assemble the text a scheduled task actually dispatches (executor-side).
165
+ * The task stores the RAW user input (task.prompt) plus the template selection
166
+ * and attachment paths; the wrapper and the quoted-path prefix are injected here
167
+ * at fire time so the stored prompt stays editable and summaries stay human-readable.
168
+ *
169
+ * @param {object} task
170
+ * @param {string} task.prompt raw user text (never pre-wrapped)
171
+ * @param {string} [task.template] 'none' | builtin key | 'custom:<id>'; absent → 'none'
172
+ * @param {string} [task.templateContent] snapshot of the custom expert body (custom:* only)
173
+ * @param {Array<{name:string, path:string}>} [task.attachments]
174
+ * @returns {string} the prompt to dispatch (empty string when there is nothing to send)
175
+ */
176
+ export function assembleScheduledPrompt(task) {
177
+ const raw = (task && task.prompt != null) ? String(task.prompt).trim() : '';
178
+ const attachments = Array.isArray(task?.attachments) ? task.attachments : [];
179
+ const filePaths = attachments
180
+ .map(f => (f && typeof f.path === 'string') ? `"${f.path.replace(/"/g, '')}"` : '')
181
+ .filter(Boolean)
182
+ .join(' ');
183
+ const userInput = filePaths ? (raw ? `${filePaths} ${raw}` : filePaths) : raw;
184
+
185
+ const template = typeof task?.template === 'string' ? task.template : 'none';
186
+ if (template.startsWith('custom:')) {
187
+ // The snapshot rides with the task so later edits/deletions of the custom
188
+ // expert do not change what fires. A missing/empty snapshot degrades to the
189
+ // raw input rather than silently dropping the task.
190
+ const wrapped = buildCustomTemplate(task.templateContent);
191
+ if (!wrapped) return userInput;
192
+ return `${wrapped}\n\n${userInput}`.trim();
193
+ }
194
+ if (template === 'codeExpert' || template === 'researchExpert') {
195
+ return buildLocalUltraplan(userInput, template);
196
+ }
197
+ // 'none' or anything unknown: verbatim.
198
+ return userInput;
199
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-viewer",
3
- "version": "1.9.22",
3
+ "version": "1.9.23",
4
4
  "description": "Claude Code logging, visualization, and management toolkit — launch a web viewer alongside Claude Code with full request/response tracing, proxy, and mobile support",
5
5
  "license": "MIT",
6
6
  "main": "server.js",
package/server/i18n.js CHANGED
@@ -841,6 +841,7 @@ const i18nData = {
841
841
  "server.dingtalk.queueFull": { "zh": "消息队列已满({max}),已丢弃该消息,请稍后再发。", "en": "Message queue is full ({max}); this message was dropped. Try again later." },
842
842
  "server.dingtalk.ackProcessing": { "zh": "收到,正在思考…", "en": "Got it, thinking…" },
843
843
  "server.dingtalk.ackTimeout": { "zh": "处理超时,请重试。", "en": "Processing timed out, please try again." },
844
+ "server.dingtalk.startupError": { "zh": "Claude 启动未完成(目录信任待处理),请检查配置后重试。", "en": "Claude startup incomplete (directory trust pending) — check configuration and retry." },
844
845
  "server.feishu.replyChunkTitle": { "zh": "Claude", "en": "Claude" },
845
846
  "server.feishu.truncated": { "zh": "(回复过长已截断,完整内容请见 Web 界面)", "en": "(reply truncated — see the web UI for the full content)" },
846
847
  "server.feishu.noTextReply": { "zh": "(本轮无文本回复)", "en": "(no text reply this turn)" },
@@ -855,6 +856,7 @@ const i18nData = {
855
856
  "server.feishu.queueFull": { "zh": "消息队列已满({max}),已丢弃该消息,请稍后再发。", "en": "Message queue is full ({max}); this message was dropped. Try again later." },
856
857
  "server.feishu.ackProcessing": { "zh": "收到,正在思考…", "en": "Got it, thinking…" },
857
858
  "server.feishu.ackTimeout": { "zh": "处理超时,请重试。", "en": "Processing timed out, please try again." },
859
+ "server.feishu.startupError": { "zh": "Claude 启动未完成(目录信任待处理),请检查配置后重试。", "en": "Claude startup incomplete (directory trust pending) — check configuration and retry." },
858
860
  "server.wecom.replyChunkTitle": { "zh": "Claude", "en": "Claude" },
859
861
  "server.wecom.truncated": { "zh": "(回复过长已截断,完整内容请见 Web 界面)", "en": "(reply truncated — see the web UI for the full content)" },
860
862
  "server.wecom.noTextReply": { "zh": "(本轮无文本回复)", "en": "(no text reply this turn)" },
@@ -869,6 +871,7 @@ const i18nData = {
869
871
  "server.wecom.queueFull": { "zh": "消息队列已满({max}),已丢弃该消息,请稍后再发。", "en": "Message queue is full ({max}); this message was dropped. Try again later." },
870
872
  "server.wecom.ackProcessing": { "zh": "收到,正在思考…", "en": "Got it, thinking…" },
871
873
  "server.wecom.ackTimeout": { "zh": "处理超时,请重试。", "en": "Processing timed out, please try again." },
874
+ "server.wecom.startupError": { "zh": "Claude 启动未完成(目录信任待处理),请检查配置后重试。", "en": "Claude startup incomplete (directory trust pending) — check configuration and retry." },
872
875
  "server.discord.replyChunkTitle": { "zh": "Claude", "en": "Claude" },
873
876
  "server.discord.truncated": { "zh": "(回复过长已截断,完整内容请见 Web 界面)", "en": "(reply truncated — see the web UI for the full content)" },
874
877
  "server.discord.noTextReply": { "zh": "(本轮无文本回复)", "en": "(no text reply this turn)" },
@@ -883,6 +886,7 @@ const i18nData = {
883
886
  "server.discord.queueFull": { "zh": "消息队列已满({max}),已丢弃该消息,请稍后再发。", "en": "Message queue is full ({max}); this message was dropped. Try again later." },
884
887
  "server.discord.ackProcessing": { "zh": "收到,正在思考…", "en": "Got it, thinking…" },
885
888
  "server.discord.ackTimeout": { "zh": "处理超时,请重试。", "en": "Processing timed out, please try again." },
889
+ "server.discord.startupError": { "zh": "Claude 启动未完成(目录信任待处理),请检查配置后重试。", "en": "Claude startup incomplete (directory trust pending) — check configuration and retry." },
886
890
  "update.updating": {
887
891
  "zh": "正在更新到 v{version}...",
888
892
  "en": "Updating to v{version}...",
@@ -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) {