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.
@@ -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;
@@ -36,6 +36,7 @@ import { createHash, randomBytes } from 'node:crypto';
36
36
  import { registerSdkSessionLister } from './sdk-session-index.js';
37
37
  import { readPrefsRaw } from './prefs-store.js';
38
38
  import { projectKeyForCwd } from './system-prompt-snapshots.js';
39
+ import { AGENT_PROMPT_SNIPPET_LEN } from '@ccv/core/contentFilter';
39
40
  import {
40
41
  computeAutoApprove,
41
42
  createAutoApproveState,
@@ -328,18 +329,17 @@ function _isBareClearCommand(text) {
328
329
  * delta for the client to apply, and `skip_transcript` is forwarded as
329
330
  * `skipTranscript` so the UI stage can decide whether to hide ambient tasks.
330
331
  *
331
- * Two constraints the UI stage MUST respect (server-side, this round is pure relay):
332
+ * Two constraints the UI stage MUST respect:
332
333
  * - TWO status vocabularies share the wire: `task_notification.status` is
333
334
  * `completed|failed|stopped`, while `task_updated.patch.status` is
334
335
  * `pending|running|completed|failed|killed` — adjacent but disjoint domains.
335
336
  * A client that naively merges `{...task, ...frame}` then `{...frame.patch}`
336
337
  * will mis-render; discriminate by `subtype` before reading `status`.
337
- * - NO server-side task table → NOT reconnect-replayed (unlike sdk-init's
338
- * `_lastInitSnapshot`). A frame missed during a WS gap (page refresh / 2s
339
- * reconnect) is NOT recoverable; an in-flight task is invisible to a late
340
- * client. Accept-as-ephemeral vs add a bounded last-state map is a UI-stage
341
- * decision (see sdk-mode-todo-list; if replay is wanted, reuse task-state.js's
342
- * reducer semantics rather than growing a second table here).
338
+ * - The live relay is delta-only, but every frame is ALSO folded into a bounded
339
+ * per-session table (taskId → latest folded state, cap 64, reset on session
340
+ * boundaries) and replayed as an authoritative `sdk-task-snapshot` on WS
341
+ * reconnect — a frame missed during a gap is recoverable, and an empty table
342
+ * replays as `tasks: []` so the client reconciles to "no tasks".
343
343
  *
344
344
  * Note: the 4 subtypes relayed here are the PUBLIC contract (sdk.d.ts SDKMessage
345
345
  * union). The SDK additionally emits @internal `task_summary` / `post_turn_summary`
@@ -386,6 +386,41 @@ function _normalizeSdkTask(msg) {
386
386
  return out;
387
387
  }
388
388
 
389
+ /**
390
+ * Fold one normalized sdk-task frame into a server-side table entry (the latest
391
+ * known state per taskId). task_started seeds; task_progress/updated merge fields
392
+ * (patch.status is authoritative for updated); task_notification marks terminal.
393
+ * Kept deliberately small — the full prompt is retained only as a bounded snippet,
394
+ * shared via @ccv/core's AGENT_PROMPT_SNIPPET_LEN so the client tracker truncates
395
+ * identically.
396
+ */
397
+ const _SDK_TASK_TERMINAL = new Set(['completed', 'failed', 'stopped', 'killed']);
398
+ function _foldSdkTask(prev, frame) {
399
+ const next = { ...(prev || {}), taskId: frame.taskId };
400
+ if (frame.sessionId != null) next.sessionId = frame.sessionId;
401
+ if (frame.toolUseId != null) next.toolUseId = frame.toolUseId;
402
+ if (frame.taskType != null) next.taskType = frame.taskType;
403
+ if (frame.description != null) next.description = frame.description;
404
+ if (frame.patch && frame.patch.description != null) next.description = frame.patch.description; // task_updated delta
405
+ if (frame.summary != null) next.summary = frame.summary;
406
+ if (frame.prompt != null) next.promptSnippet = String(frame.prompt).slice(0, AGENT_PROMPT_SNIPPET_LEN);
407
+ // Retained so getSdkTaskSnapshot can hide ambient tasks from the replay while the
408
+ // entry still participates in session-boundary detection (a skipTranscript first
409
+ // frame may be the only task frame carrying the new sessionId).
410
+ if (frame.skipTranscript != null) next.skipTranscript = frame.skipTranscript === true;
411
+ if (frame.workflowName != null) next.workflowName = frame.workflowName;
412
+ if (frame.lastToolName != null) next.lastToolName = frame.lastToolName;
413
+ if (frame.usage != null) next.usage = frame.usage;
414
+ // Status: notification carries the terminal word; updated carries it in patch.
415
+ if (frame.subtype === 'task_notification' && frame.status != null) next.status = frame.status;
416
+ else if (frame.patch && frame.patch.status != null) next.status = frame.patch.status;
417
+ else if (frame.status != null) next.status = frame.status;
418
+ else if (!next.status) next.status = frame.subtype === 'task_started' ? 'running' : 'pending';
419
+ next.terminal = _SDK_TASK_TERMINAL.has(next.status);
420
+ next.updatedAt = Date.now();
421
+ return next;
422
+ }
423
+
389
424
  // ── Per-session factory ──────────────────────────────────────────────────────
390
425
  // ONE closure = ONE workspace's resident SDK session. Every variable the current
391
426
  // (single-session) module held in module-level `let` lives here EXCEPT the ones
@@ -491,6 +526,15 @@ function _createSession(key, cwd) {
491
526
  // turn-correlated, so it gets no turn-end/compact trigger and none of the in-flight gate
492
527
  // (fetching/queued/seq) machinery above. It reuses the same CTX_USAGE_TIMEOUT_MS bound.
493
528
  let _lastMcpStatus = null;
529
+ // Bounded server-side sdk-task table (review: stale active-agents strip). Until now
530
+ // the relay was stateless — a frame missed during a WS gap was unrecoverable, so a
531
+ // late/refreshed client never learned an in-flight agent, and a client whose
532
+ // terminal frame was lost kept the agent "active" forever. This bounded map (one
533
+ // entry per taskId, per sessionId) lets a reconnecting client reconcile to the
534
+ // server's authoritative view. Cleared on session boundaries like _lastInitSnapshot.
535
+ let _sdkTaskTable = new Map(); // taskId -> normalized sdk-task frame (latest)
536
+ let _sdkTaskTableSessionId = null; // sessionId the table belongs to
537
+ const _SDK_TASK_TABLE_CAP = 64; // bounded: oldest evicted beyond this
494
538
  // Pending canUseTool promises: id → { kind, resolve, replay, startedAt, timeoutMs }
495
539
  // replay is the exact broadcast payload that announced this approval — retained so a
496
540
  // fresh WS connection can re-announce it (server.js connection replay), otherwise a
@@ -1556,6 +1600,14 @@ function _createSession(key, cwd) {
1556
1600
  // /clear may reinitialize instead of returning a normal result. The new session is
1557
1601
  // now authoritative, so context reads may resume (without resuming the old session).
1558
1602
  if (_ctxUsageClearPending && msg.session_id) _ctxUsageClearPending = false;
1603
+ // Session boundary for the task table: /clear re-inits with a new session_id but
1604
+ // may emit no task frame until the next task starts (the task-frame boundary in
1605
+ // the task branch only fires once one arrives), and a task that was in flight
1606
+ // gets no terminal frame — without this reset a reconnect would resurrect it.
1607
+ if (msg.session_id && msg.session_id !== _sdkTaskTableSessionId) {
1608
+ _sdkTaskTable = new Map();
1609
+ _sdkTaskTableSessionId = msg.session_id;
1610
+ }
1559
1611
  if (_broadcastWs && Array.isArray(msg.slash_commands) && msg.slash_commands.length > 0
1560
1612
  && msg.session_id !== _initAnnouncedSid) {
1561
1613
  _initAnnouncedSid = msg.session_id;
@@ -1602,10 +1654,26 @@ function _createSession(key, cwd) {
1602
1654
  // SDK background-task / subagent progress (SDK 0.2.x system subtypes). The TODO
1603
1655
  // HUD (TaskProgressHud) is hook-fed and never fires in SDK mode; this is a
1604
1656
  // separate, lossless relay so clients can observe task lifecycle (incl.
1605
- // failed/stopped/killed terminal states the TODO HUD vocabulary lacks). The
1606
- // server keeps no task table here — pure forward, merge semantics left to the
1607
- // client (task_updated.patch is a wire-safe delta, not a full snapshot).
1608
- _broadcastWs({ type: 'sdk-task', cwd: _cwd, instanceKey, ..._normalizeSdkTask(msg) });
1657
+ // failed/stopped/killed terminal states the TODO HUD vocabulary lacks). Folded
1658
+ // into a bounded server-side table for reconnect replay (a frame lost in a WS
1659
+ // gap is no longer unrecoverable); merge semantics stay client-side.
1660
+ const sdkTaskFrame = { type: 'sdk-task', cwd: _cwd, instanceKey, ..._normalizeSdkTask(msg) };
1661
+ // Maintain the authoritative table (sessionId-scoped, bounded). A new sessionId
1662
+ // resets the table so a /clear or in-place resume never leaks the prior session's
1663
+ // tasks into a reconnecting client's view.
1664
+ if (sdkTaskFrame.taskId) {
1665
+ if (sdkTaskFrame.sessionId && sdkTaskFrame.sessionId !== _sdkTaskTableSessionId) {
1666
+ _sdkTaskTable = new Map();
1667
+ _sdkTaskTableSessionId = sdkTaskFrame.sessionId;
1668
+ }
1669
+ _sdkTaskTable.delete(sdkTaskFrame.taskId); // re-insert for LRU order
1670
+ _sdkTaskTable.set(sdkTaskFrame.taskId, _foldSdkTask(_sdkTaskTable.get(sdkTaskFrame.taskId), sdkTaskFrame));
1671
+ while (_sdkTaskTable.size > _SDK_TASK_TABLE_CAP) {
1672
+ const oldest = _sdkTaskTable.keys().next().value;
1673
+ _sdkTaskTable.delete(oldest);
1674
+ }
1675
+ }
1676
+ _broadcastWs(sdkTaskFrame);
1609
1677
  }
1610
1678
  break;
1611
1679
 
@@ -2627,6 +2695,8 @@ function _createSession(key, cwd) {
2627
2695
  _lastInitSnapshot = null; // don't replay the OLD session's sdk-init to the new one
2628
2696
  _lastSkillsSnapshot = null; // same for the skill surface
2629
2697
  _lastSessionState = null; // same for the session-state snapshot — new session starts idle
2698
+ _sdkTaskTable = new Map(); // drop the outgoing session's task table
2699
+ _sdkTaskTableSessionId = null;
2630
2700
  _clearStateHeartbeat();
2631
2701
  _suspectGeneration = false;
2632
2702
  _lastFailedTurn = null; // the failure belongs to the outgoing session — never retry it into this one
@@ -2651,6 +2721,8 @@ function _createSession(key, cwd) {
2651
2721
  _initAnnouncedSid = '';
2652
2722
  _lastInitSnapshot = null;
2653
2723
  _lastSkillsSnapshot = null;
2724
+ _sdkTaskTable = new Map(); // full reset: drop the task table too
2725
+ _sdkTaskTableSessionId = null;
2654
2726
  // Tell clients BEFORE nulling the snapshot: a re-init/launch mid-turn would
2655
2727
  // otherwise leave the spinner lit with no frame ever clearing it (the new
2656
2728
  // session starts idle and the state-change guard would swallow the first
@@ -2725,6 +2797,19 @@ function _createSession(key, cwd) {
2725
2797
  getContextUsageSnapshot: () => _lastContextUsage,
2726
2798
  getMcpStatusSnapshot: () => _lastMcpStatus,
2727
2799
  getSkillsSnapshot: () => _lastSkillsSnapshot,
2800
+ // Authoritative sdk-task table for WS reconnect replay: a refreshed/reconnected
2801
+ // client reconciles its delta-only tracker to this snapshot (sessionId-scoped).
2802
+ // ALWAYS returns a frame — an empty `tasks: []` is authoritative ("no tasks"),
2803
+ // otherwise a client that missed the session boundary keeps its stale agents.
2804
+ // skipTranscript entries are tracked (they carry the session boundary) but hidden
2805
+ // from the replay, matching the live path that never shows ambient tasks.
2806
+ getSdkTaskSnapshot: () => ({
2807
+ type: 'sdk-task-snapshot',
2808
+ cwd: _cwd,
2809
+ instanceKey,
2810
+ sessionId: _sdkTaskTableSessionId,
2811
+ tasks: [..._sdkTaskTable.values()].filter((t) => t.skipTranscript !== true),
2812
+ }),
2728
2813
  fetchContextUsage: async () => {
2729
2814
  // On-demand fetch for the HTTP route: refresh the snapshot, broadcast to all clients,
2730
2815
  // then reply. Unlike _refreshContextUsage this bypasses the in-flight gate (an explicit
@@ -3236,6 +3321,23 @@ export function getMcpStatusSnapshot(anchor) {
3236
3321
  return sess ? sess.getMcpStatusSnapshot() : null;
3237
3322
  }
3238
3323
 
3324
+ /**
3325
+ * WS reconnect replay getter for the authoritative sdk-task table.
3326
+ *
3327
+ * `anchor` (optional, skills-snapshot parity — resolved by _sessionForAnchor):
3328
+ * - { instanceKey } exact registered instance
3329
+ * - { cwd } exact normalized cwd
3330
+ * - { project } sanitized/raw basename; ambiguous → null
3331
+ * No anchor → the ACTIVE session. Returns the always-present `sdk-task-snapshot`
3332
+ * frame ({ type, cwd, instanceKey, sessionId, tasks }) — tasks may be empty — or
3333
+ * null only when the anchor resolves to no registered session (the caller sends
3334
+ * nothing; an anchor failure must not replay a foreign workspace's table).
3335
+ */
3336
+ export function getSdkTaskSnapshot(anchor) {
3337
+ const sess = anchor ? _sessionForAnchor(anchor) : _active();
3338
+ return sess ? sess.getSdkTaskSnapshot() : null;
3339
+ }
3340
+
3239
3341
  /**
3240
3342
  * On-demand context-usage fetch for the HTTP route (see the Session factory's
3241
3343
  * fetchContextUsage). No anchor → the active session. Returns
@@ -1,13 +1,14 @@
1
1
  import { resolveNativePath, LOG_DIR } from '../findcc.js';
2
2
  import { normalizeSessionCwd } from './lib/v2/layout.js';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { join, dirname, sep } from 'node:path';
5
- import { chmodSync, statSync } from 'node:fs';
4
+ import { join, dirname, sep, resolve } from 'node:path';
5
+ import { chmodSync, statSync, existsSync } from 'node:fs';
6
6
  import { platform, arch, homedir } from 'node:os';
7
7
  import { createRequire } from 'node:module';
8
8
  import { prepareEmbeddedShellSpawn, stripClaudeNoFlickerUnlessOptedIn, applyClaudeAltScreenPref } from './lib/terminal-env.js';
9
9
  import { killPtyTree } from './lib/term-signals.js';
10
10
  import { findSafeSliceStart, splitTrailingIncomplete } from './lib/ansi-safe-slice.js';
11
+ import { imDir } from './lib/im/im-lock.js';
11
12
  import { resolveSpawnModel } from './lib/spawn-model-resolver.js';
12
13
  import { mergeSettingsIntoArgs } from './lib/settings-merge.js';
13
14
  import { projectKeyForCwd } from './lib/system-prompt-snapshots.js';
@@ -18,6 +19,7 @@ import { randomBytes } from 'node:crypto';
18
19
  import { withDefaultThinkingDisplay, resolveLaunchSystemPrompt, insertBeforeDashDash } from './lib/launch-config.js';
19
20
  export { withDefaultThinkingDisplay } from './lib/launch-config.js';
20
21
  import { reportSwallowed } from './lib/error-report.js';
22
+ import { ensureOnboardingAndTrust } from './lib/ensure-hooks.js';
21
23
  import { t, tFor } from './i18n.js';
22
24
 
23
25
  const __filename = fileURLToPath(import.meta.url);
@@ -389,6 +391,21 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
389
391
  env.CCV_PROXY_MODE = '1'; // tell interceptor.js not to start a server again
390
392
  env.CCV_LOG_DIR = LOG_DIR; // let the forked Claude Code process find the same
391
393
  // profile.json etc. resources
394
+ // IM worker CodeFuse config-dir fallback is handled in cli.js runImMode
395
+ // (before runCliMode), so that ensureHooks() writes to the same directory
396
+ // the child will read. Here we only need to inherit the already-resolved
397
+ // CLAUDE_CONFIG_DIR from process.env (which the env copy above already does).
398
+ // Pre-seed onboarding + trust state so Claude never blocks on interactive
399
+ // confirmation dialogs ("Yes, I accept" / "Yes, I trust this folder") in
400
+ // headless environments. Only applies to the IM worker's OWN working directory
401
+ // (imDir) — a user-launched workspace inside an IM worker must NOT silently
402
+ // accept trust on behalf of the user (security boundary).
403
+ if (process.env.CCV_IM_PLATFORM && cwd) {
404
+ const imWorkspace = imDir(process.env.CCV_IM_PLATFORM);
405
+ if (resolve(cwd) === resolve(imWorkspace)) {
406
+ ensureOnboardingAndTrust({ configDir: env.CLAUDE_CONFIG_DIR, workspacePath: cwd });
407
+ }
408
+ }
392
409
  // Self-report project (2026-10, multi-PTY): every main-PTY claude ALSO tags its
393
410
  // requests with `x-ccv-project-dir` = its own cwd, so the writer routes its
394
411
  // writes to ITS project — not the (possibly re-bound) server project. This is
@@ -599,8 +616,8 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
599
616
  let command = claudePath;
600
617
  let args = ['--settings', settingsJson, ...launchArgs];
601
618
 
602
- // If it is the npm version (cli.js), it must run under node
603
- if (isNpmVersion && claudePath.endsWith('.js')) {
619
+ // If it is the npm version (cli.js / cli.cjs), it must run under node
620
+ if (isNpmVersion && (claudePath.endsWith('.js') || claudePath.endsWith('.cjs'))) {
604
621
  command = nodePath;
605
622
  args = [claudePath, '--settings', settingsJson, ...launchArgs];
606
623
  }
@@ -616,9 +633,13 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
616
633
  // A (re)spawn starts a fresh conversation — drop any sessionId a prior life
617
634
  // on this record resolved to, so a stale sid never misroutes a send.
618
635
  if (s.sessionId) { sidToKey.delete(s.sessionId); s.sessionId = null; }
636
+ // Clear any latched boot-blocked state from a previous life on this record —
637
+ // the respawn may succeed where the prior attempt was blocked.
638
+ s._bootBlockedState = null;
619
639
  // Boot-window anchor for the injection fallback tiers below (same clock as the
620
640
  // comparison — _now(), never Date.now(), so tests can steer both ends together).
621
641
  const spawnedAt = _now();
642
+ s._spawnedAt = spawnedAt; // also stored on the record for getPtyBootState()
622
643
 
623
644
  s.ptyProcess = pty.spawn(command, args, {
624
645
  name: 'xterm-256color',
@@ -1531,6 +1552,84 @@ export function getOutputBuffer() {
1531
1552
  return s ? s.outputBuffer : '';
1532
1553
  }
1533
1554
 
1555
+ // ─── PTY boot-state detection ───
1556
+ // Patterns that indicate the Claude PTY is blocked on an interactive dialog
1557
+ // instead of being ready to accept prompts. Used by the IM bridge to fail fast
1558
+ // with a clear error instead of letting the message sit until the 120s timeout.
1559
+ //
1560
+ // IMPORTANT: Ink renders dialog options as separately positioned words using
1561
+ // cursor-forward ANSI sequences (ESC[<n>G) instead of literal spaces. The raw
1562
+ // output looks like: "Yes,\x1b[12GI\x1b[14Gtrust\x1b[20Gthis\x1b[25Gfolder".
1563
+ // We normalize the buffer by stripping ANSI sequences before matching.
1564
+ //
1565
+ // To avoid false positives from normal conversation (e.g. a user asking about
1566
+ // "trust" or "onboarding"), detection is only active during a boot window
1567
+ // (first N ms after spawn) and only scans the last portion of the buffer.
1568
+ // Once a dialog is detected during the window, the state is LATCHED — it
1569
+ // persists until the PTY exits, so a user messaging minutes after boot still
1570
+ // gets the fail-fast error instead of the 120s timeout.
1571
+ const _BOOT_WINDOW_MS = 30_000; // 30s after spawn — enough for slow container starts
1572
+ const _BOOT_SCAN_TAIL = 4096; // only scan the last 4KB (current screenful)
1573
+
1574
+ // Strip ANSI escape sequences (cursor movement, colors, etc.) so that Ink's
1575
+ // positioned rendering ("Yes,\x1b[12GI\x1b[14Gtrust...") becomes plain text
1576
+ // ("Yes, I trust this folder").
1577
+ function _stripAnsi(str) {
1578
+ // eslint-disable-next-line no-control-regex
1579
+ return str.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, ' ');
1580
+ }
1581
+
1582
+ const _BOOT_PATTERNS = {
1583
+ 'blocked-on-trust': [
1584
+ /yes,?\s+i\s+trust\s+this\s+folder/i,
1585
+ /do\s+you\s+trust\s+this\s+folder/i,
1586
+ ],
1587
+ 'blocked-on-onboarding': [
1588
+ /yes,?\s+i\s+accept/i,
1589
+ ],
1590
+ };
1591
+
1592
+ /**
1593
+ * Detect whether the active PTY is ready, still booting, blocked on an
1594
+ * interactive dialog, or has exited. Returns one of:
1595
+ * 'ready' — PTY is running and no blocking dialog detected
1596
+ * 'booting' — PTY is running but within the boot window
1597
+ * 'blocked-on-trust' — "Yes, I trust this folder" dialog detected (latched)
1598
+ * 'blocked-on-onboarding' — onboarding/first-run dialog detected (latched)
1599
+ * 'exited' — PTY process has exited
1600
+ * 'no-pty' — no PTY record exists
1601
+ *
1602
+ * Latching: once a dialog is detected during the boot window, the state is
1603
+ * stored on the record and returned for the PTY's lifetime. This prevents
1604
+ * the 30s window from expiring while the dialog is still on screen.
1605
+ */
1606
+ export function getPtyBootState() {
1607
+ const s = _active();
1608
+ if (!s) return 'no-pty';
1609
+ if (!s.ptyProcess) return 'exited';
1610
+ // Return latched state if a dialog was previously detected.
1611
+ if (s._bootBlockedState) return s._bootBlockedState;
1612
+ // Only detect blocking dialogs during the boot window. After that, any
1613
+ // match would be a false positive from normal conversation content.
1614
+ const elapsed = _now() - (s._spawnedAt || 0);
1615
+ if (elapsed > _BOOT_WINDOW_MS) return 'ready';
1616
+ const buf = s.outputBuffer || '';
1617
+ if (buf.length < 50) return 'booting';
1618
+ // Only scan the tail of the buffer — the current screen content. Older
1619
+ // output may contain legitimate uses of trigger words from conversation.
1620
+ const tail = _stripAnsi(buf.slice(-_BOOT_SCAN_TAIL));
1621
+ for (const [state, patterns] of Object.entries(_BOOT_PATTERNS)) {
1622
+ for (const re of patterns) {
1623
+ if (re.test(tail)) {
1624
+ // Latch the state so it persists beyond the boot window.
1625
+ s._bootBlockedState = state;
1626
+ return state;
1627
+ }
1628
+ }
1629
+ }
1630
+ return 'ready';
1631
+ }
1632
+
1534
1633
  /**
1535
1634
  * Launch-or-reattach for a workspace cwd (2026-10-06, multi-instance). Now that spawnClaude
1536
1635
  * mints a fresh instanceKey per call and no longer kills an existing same-cwd record, an
@@ -165,10 +165,19 @@ function _publicTask(t) {
165
165
  // List payload keeps the full prompt OUT (it may carry secrets and every logged-in
166
166
  // viewer can read the list — security P2-3). Full prompts only ship when the project
167
167
  // resolves (bound / registry / live instance — see listHandler's fullPrompt gate).
168
+ // Attachments (absolute paths, usernames) and template snapshots get the same treatment.
168
169
  function _listTask(t) {
169
170
  const p = _publicTask(t);
170
171
  p.promptSummary = String(t.prompt || '').replace(/\s+/g, ' ').trim().slice(0, 200);
172
+ // Attachments-only tasks have no prompt text — fall back to file names so the list
173
+ // row and toasts never render blank.
174
+ if (!p.promptSummary && Array.isArray(t.attachments) && t.attachments.length) {
175
+ p.promptSummary = `[${t.attachments.map(a => a.name).filter(Boolean).join(', ')}]`.slice(0, 200);
176
+ }
171
177
  delete p.prompt;
178
+ delete p.attachments;
179
+ delete p.template;
180
+ delete p.templateContent;
172
181
  return p;
173
182
  }
174
183
 
@@ -190,6 +199,8 @@ function createHandler(req, res, parsedUrl, isLocal, deps) {
190
199
  out = await createTask(LOG_DIR, {
191
200
  project, cwd: resolved.cwd, prompt: body.prompt, mode: body.mode,
192
201
  schedule: body.schedule, enabled: body.enabled,
202
+ template: body.template, templateContent: body.templateContent,
203
+ attachments: body.attachments,
193
204
  }, Date.now());
194
205
  } catch (err) {
195
206
  reportSwallowed('scheduled-tasks.create', err);
@@ -210,6 +221,8 @@ function updateHandler(req, res, parsedUrl, isLocal, deps) {
210
221
  try {
211
222
  out = await updateTask(LOG_DIR, id, {
212
223
  prompt: body.prompt, mode: body.mode, schedule: body.schedule, enabled: body.enabled,
224
+ template: body.template, templateContent: body.templateContent,
225
+ attachments: body.attachments,
213
226
  }, Date.now());
214
227
  } catch (err) {
215
228
  reportSwallowed('scheduled-tasks.update', err);