-
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathclaude-interactive.js
More file actions
849 lines (783 loc) · 45.6 KB
/
Copy pathclaude-interactive.js
File metadata and controls
849 lines (783 loc) · 45.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
// claude-interactive.js — tmux-driven interactive Claude engine ("subscription" / Max).
//
// Instead of headless `claude -p` (which bills separate Agent SDK credits), this module
// keeps a PERSISTENT interactive Claude Code TUI session alive inside a detached tmux
// session (one per studio session) and exchanges messages with it via tmux buffers,
// reading replies from the session transcript at ~/.claude/projects/<encoded-cwd>/<cid>.jsonl.
// Interactive sessions run on the Claude Max subscription.
//
// Engine capabilities / behavior:
// - mcpServers: passed via --mcp-config at spawn time (works in interactive mode)
// - systemPrompt: applied at spawn time via --append-system-prompt
// - config changes (system prompt / MCP set / model) are detected via a hash stored
// in the tmux session environment — the session is respawned with --resume, which
// keeps writing to the SAME transcript file (verified empirically)
// - image attachments: saved to temp files, paths appended to the prompt (the agent
// reads them with its Read tool); other structured blocks are flattened to text
// - maxTurns is IGNORED (not applicable to interactive sessions)
//
// - the tmux session lives on the PRIVATE `ccstudio` socket (see tmuxArgs below), the
// same one terminal-bridge.js uses, so the browser can attach a read/write view of
// this exact pane via /ws/terminal?view=engine — one claude process, one writer
//
// This module NEVER touches SQLite and NEVER sends the 'done' WS event — the caller
// (server.js WS chat handler) persists collected output and sends 'done' after return.
const { spawn, spawnSync } = require('node:child_process');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const crypto = require('node:crypto');
const { findClaudeBin } = require('./claude-cli');
const { agentsMdPreamble } = require('./agents-md');
// ONE definition of the socket name, imported — never a second copy of the string.
const { TMUX_SOCKET } = require('./terminal-bridge');
// tmux negotiates UTF-8 support for the server from LANG/LC_ALL at the FIRST
// `new-session` call's env — neither the Docker image (node:20-bookworm, no ENV
// LANG) nor a macOS GUI launch sets a UTF-8 locale, so without this the tmux
// server falls back to non-UTF-8 mode and mangles every multi-byte character
// sent through load-buffer/paste-buffer (e.g. each Cyrillic letter becomes
// "–" plus a stray glyph). Same bug and same fix as terminal-bridge.js.
const UTF8_LOCALE = process.platform === 'darwin' ? 'en_US.UTF-8' : 'C.UTF-8';
function utf8Env() {
return { ...process.env, LANG: UTF8_LOCALE, LC_ALL: UTF8_LOCALE };
}
// Idle (inactivity) watchdog — the turn is abandoned after this long with no new
// transcript bytes. A turn that keeps writing output (the normal long-content case)
// resets the clock and is never cut off; a turn that shows the spinner but writes
// nothing for this long is treated as stuck. Default 10 min.
// Config: CLAUDE_IDLE_TIMEOUT_MS (legacy alias CLAUDE_TIMEOUT_MS).
const IDLE_TIMEOUT_MS = parseInt(process.env.CLAUDE_IDLE_TIMEOUT_MS || process.env.CLAUDE_TIMEOUT_MS || '600000', 10) || 600000;
// Optional absolute ceiling — backstop against a turn that stays "busy" forever. 0 = off.
const HARD_CAP_MS = parseInt(process.env.CLAUDE_HARD_CAP_MS || '0', 10) || 0;
// ─── Interactive-prompt watchdog (GitHub #20) ────────────────────────────────
// How often the turn loop looks at the transcript and the pane.
const POLL_MS = 1500;
// Consecutive polls a prompt must stay on screen before the browser is told. One
// frame can catch a half-drawn widget, or one the agent dismisses by itself.
const AWAIT_CONFIRM_POLLS = 2;
// Extra time a turn is held open while a prompt is pending, on top of the ordinary
// quiet-completion budget — the window in which a human can answer in the live pane.
// 0 disables the hold and the turn completes exactly as it did before. The idle
// watchdog above is untouched and stays the backstop for a prompt nobody answers.
const AWAIT_GRACE_MS = parseInt(process.env.CLAUDE_PROMPT_GRACE_MS || '300000', 10) || 0;
// How long a FRESHLY SPAWNED TUI is given to get past a startup dialog before the
// prompt is pasted anyway. 0 restores the old behaviour (paste immediately).
const SPAWN_PROMPT_WAIT_MS = parseInt(process.env.CLAUDE_STARTUP_PROMPT_WAIT_MS || '90000', 10) || 0;
// How many consecutive failed clarification pastes are attempted before the engine
// gives up for the rest of the turn. A dead or unreachable pane fails on every
// poll, and retrying at POLL_MS forever spawns three tmux processes per tick for
// nothing. The messages stay queued either way — the caller's finally block runs
// them as the next turn.
const INJECT_MAX_FAILS = 3;
// ─── tmux socket ─────────────────────────────────────────────────────────────
// The interactive engine's sessions (`ccs-<id>`) live on the SAME private tmux
// server as terminal sessions (socket `ccstudio`, owned by terminal-bridge.js),
// never on the default one. Two reasons, in order of weight:
//
// 1. A chat running on this engine can now be watched live from the browser
// (`/ws/terminal?view=engine`), and terminal-bridge.js can only attach to a
// session on its own socket. Split sockets made the attach impossible.
// 2. `tmux kill-server` typed in any shell is server-wide, so on the default
// socket a single stray command destroys every live subscription session
// mid-turn — the exact failure that moved terminal sessions off it.
//
// EVERY tmux invocation in this file goes through tmuxArgs(). A missed one would
// silently split state across two servers: has-session says "no" while the real
// TUI is still running on the other socket.
function tmuxArgs(args) { return ['-L', TMUX_SOCKET, ...args]; }
// ─── tmux availability (checked once, cached) ───────────────────────────────
let _tmuxAvailable = null;
function tmuxAvailable() {
if (_tmuxAvailable === null) {
try {
const r = spawnSync('tmux', tmuxArgs(['-V']), { stdio: 'ignore' });
_tmuxAvailable = !r.error && r.status === 0;
} catch {
_tmuxAvailable = false;
}
}
return _tmuxAvailable;
}
// ─── helpers ─────────────────────────────────────────────────────────────────
// POSIX single-quote shell escaping: wrap in ', replace embedded ' with '\''
function shq(s) {
return "'" + String(s).replace(/'/g, "'\\''") + "'";
}
function tmuxName(localSessionId) {
return 'ccs-' + String(localSessionId).replace(/[^a-zA-Z0-9_-]/g, '_');
}
function tmuxHasSession(name) {
try {
const r = spawnSync('tmux', tmuxArgs(['has-session', '-t', name]), { stdio: 'ignore' });
return !r.error && r.status === 0;
} catch {
return false;
}
}
function capturePane(name) {
try {
const r = spawnSync('tmux', tmuxArgs(['capture-pane', '-p', '-t', name]), { encoding: 'utf8' });
if (r.error || r.status !== 0) return null;
return r.stdout || '';
} catch {
return null;
}
}
// Is the Claude TUI actively working a turn? Used to hold completion until the
// spinner clears — a single assistant message is written to the transcript as
// SEPARATE records per block (thinking → text → tool_use), all stamped with the
// SAME final stop_reason, up to ~20s apart. So a terminal stop_reason can latch
// on the thinking record well before the final text record is flushed; breaking
// then would drop the trailing text. The spinner animates throughout that gap
// and only clears when the turn truly ends.
//
// Detection is defense-in-depth and version-independent — ANY of three signals
// means busy, biased so a false "busy" only DELAYS completion (caught by the
// safety-net) while never risking a premature break that loses text:
// 1. animation — the spinner's elapsed counter ticks every ~0.5–1s, so the
// captured pane changes between polls during a turn (verified on live
// 2.1.x: idle sessions stay static, working ones change every poll);
// 2. elapsed-timer pattern — a seconds count followed by a "·" or ")", e.g.
// "(8s ·" / "26m 44s ·" / "8s)", shown only during an active turn (the
// persistent statusline uses "⏱ 5m" / "🕐 14:12", which don't match);
// 3. legacy "esc to interrupt" marker (older TUI builds).
function paneBusy(pane, prevPane) {
if (pane === null) return false;
if (prevPane !== null && pane !== prevPane) return true; // 1. spinner animating
if (/\d+s\s*[·)]/.test(pane)) return true; // 2. elapsed timer "(8s ·" / "43s ·" / "8s)"
if (pane.includes('esc to interrupt')) return true; // 3. legacy marker
return false;
}
// Is the TUI blocked on a prompt only a human can answer? (GitHub #20)
//
// Structural, not wording-based. Every blocking prompt the Claude Code TUI renders —
// a tool-permission request, plan approval, the --dangerously-skip-permissions
// acceptance screen, the trust-this-folder dialog, the AskUserQuestion tool, /model —
// is the SAME widget: numbered options with a caret on the selected one.
//
// ❯ 1. Yes
// 2. Yes, and don't ask again this session
// 3. No, and tell Claude what to do differently
//
// Two conditions must BOTH hold, and only in the tail of the pane (the widget is
// always at the bottom, just above the input box):
// - at least two numbered option lines, and
// - a selection caret directly in front of one of those numbers.
//
// The caret is what separates a widget from prose: an ordinary numbered list in
// Claude's answer text has no caret glyph in front of the digit. Wording is
// deliberately not matched — it is version- and locale-specific, and the widget
// shape has been stable across TUI releases.
//
// Known failure modes, both benign by construction:
// - false positive: Claude prints a numbered list whose first item happens to be
// prefixed with '>' or '❯'. Cost is a banner the user ignores plus a longer
// quiet-completion budget for that turn — never a wrong answer sent anywhere.
// - false negative: a prompt that is not this widget (a raw readline question from
// a hook or an MCP server writing to the pane). Cost is the previous behaviour:
// the turn ends on the idle watchdog. The live pane is still reachable by hand.
// Both are why the caller ALSO requires the spinner to be stopped before believing it.
const AWAIT_TAIL_LINES = 24;
function paneAwaitingInput(pane) {
if (typeof pane !== 'string' || !pane) return false;
const lines = pane.split('\n').map(l => l.trim()).filter(Boolean);
let numbered = 0, caret = false;
for (const raw of lines.slice(-AWAIT_TAIL_LINES)) {
// Strip a leading box border so "│ ❯ 1. Yes" reads the same as "❯ 1. Yes".
const line = raw.replace(/^[│┃|╎╏┆┊╷╵]+\s*/, '');
const m = /^([❯➤►▶›»>])?\s*(\d{1,2})[.)]\s+\S/.exec(line);
if (!m) continue;
numbered++;
if (m[1]) caret = true;
}
return numbered >= 2 && caret;
}
// The pane tail the browser banner shows, so the user can recognise the question
// without opening the pane. Never the whole capture: it carries the entire visible
// conversation and is 50 lines of noise.
function promptExcerpt(pane, maxLines = 14) {
return String(pane || '').split('\n').map(l => l.replace(/\s+$/, ''))
.filter(l => l.trim()).slice(-maxLines).join('\n').slice(0, 2000);
}
// Locate <cid>.jsonl under ~/.claude/projects/* — do NOT hand-encode the cwd→dirname
// mapping (macOS realpath/encoding is non-trivial); scan subdirectories instead.
function findTranscript(cid) {
try {
const root = path.join(os.homedir(), '.claude', 'projects');
if (!fs.existsSync(root)) return null;
for (const dir of fs.readdirSync(root)) {
const candidate = path.join(root, dir, cid + '.jsonl');
if (fs.existsSync(candidate)) return candidate;
}
} catch {}
return null;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Write the MCP servers map to a content-addressed temp file for --mcp-config.
// Files are tiny, idempotent by hash, and intentionally not deleted — the TUI
// reads the path at spawn time and a respawn with the same config reuses it.
function mcpConfigPath(mcpServers) {
if (!mcpServers || typeof mcpServers !== 'object' || Object.keys(mcpServers).length === 0) return null;
try {
const json = JSON.stringify({ mcpServers });
const hash = crypto.createHash('sha256').update(json).digest('hex').slice(0, 16);
const p = path.join(os.tmpdir(), `ccs-mcp-${hash}.json`);
// 0600: the config embeds internal MCP secrets (ASK_USER_SECRET etc.)
if (!fs.existsSync(p)) fs.writeFileSync(p, json, { mode: 0o600 });
return p;
} catch {
return null;
}
}
// tmux session environment — survives studio server restarts, dies with the session
function getTmuxEnv(name, key) {
try {
const r = spawnSync('tmux', tmuxArgs(['show-environment', '-t', name, key]), { encoding: 'utf8' });
if (r.error || r.status !== 0) return null;
const line = (r.stdout || '').trim();
const eq = line.indexOf('=');
return eq >= 0 ? line.slice(eq + 1) : null;
} catch {
return null;
}
}
function setTmuxEnv(name, key, val) {
try { spawnSync('tmux', tmuxArgs(['set-environment', '-t', name, key, val]), { stdio: 'ignore' }); } catch {}
}
// ─── public API ──────────────────────────────────────────────────────────────
// One-time upgrade aid. Before the socket move, sessions were created on the
// DEFAULT tmux socket; after it, tmuxHasSession() looks only at `ccstudio` and
// therefore reports "gone" for every session that is in fact still running there.
// The engine handles that on its own — an absent session is respawned with
// `--resume <cid>`, so the conversation continues in the right place — but the
// old TUI keeps running, holding the same transcript open. It is never sent
// anything again (nothing in this process talks to the default socket any more),
// yet a turn that was mid-flight when the server restarted will finish and write
// to that transcript, which the resumed session has also opened.
//
// This is READ-ONLY on purpose: `kill-session` on the default socket would reach
// into a tmux server this project does not own. We report and let the user close
// them. Returns [] when no default tmux server is running at all.
function listOrphanedDefaultSocketSessions() {
try {
const r = spawnSync('tmux', ['list-sessions', '-F', '#{session_name}'], { encoding: 'utf8' });
if (r.error || r.status !== 0) return [];
return String(r.stdout || '').split('\n').map(x => x.trim()).filter(x => /^ccs-/.test(x));
} catch { return []; }
}
// Best-effort tmux session kill (called on studio session delete)
function killInteractiveTmux(localSessionId) {
try {
spawnSync('tmux', tmuxArgs(['kill-session', '-t', tmuxName(localSessionId)]), { stdio: 'ignore' });
} catch {}
}
// Run one message through the persistent interactive tmux session.
// Params: same object as server.js runCliSingle — uses prompt, systemPrompt, model,
// mode, ws, sessionId, abortController, claudeSessionId, workdir, tabId; ignores the rest.
// Returns { cid, completed, resultMeta, fullText, fullThinking, toolEvents }.
async function runInteractiveSingle(params) {
const { prompt, systemPrompt, model, mode, ws, sessionId, abortController, claudeSessionId, workdir, tabId, mcpServers, userContent, drainInterrupts, markInterruptsDelivered, requeueInterrupts, fanout } = params;
const start = Date.now();
const wsSend = (obj) => {
try { ws.send(JSON.stringify({ ...obj, ...(tabId ? { tabId } : {}) })); } catch {}
};
// input_needed / input_resolved are the only frames a SECOND window watching the
// same chat must also receive: they are the difference between "the turn is running"
// and "the turn is blocked waiting for a human", and a window that never sees them
// shows a spinner until the timeout. The rest of the stream reaches other windows
// through history replay, so it stays on wsSend alone. `fanout` is optional — the
// task-runner path already sends through a broadcasting proxy.
const wsSendAll = (obj) => {
wsSend(obj);
if (typeof fanout === 'function') { try { fanout({ ...obj, ...(tabId ? { tabId } : {}) }); } catch {} }
};
let fullText = '', fullThinking = '';
const toolEvents = [];
if (!tmuxAvailable()) {
wsSend({ type: 'error', error: 'tmux not found — interactive engine unavailable' });
return { cid: claudeSessionId || null, completed: false, resultMeta: null, fullText: '', fullThinking: '', toolEvents: [] };
}
const name = tmuxName(sessionId);
let cid = claudeSessionId || null;
// Declared OUTSIDE the try so the finally below can clear the banner. Every early
// return inside — abort, idle timeout, hard cap, grace expiry, dead-end, throw —
// used to leave the browser showing "waiting for your answer" over a dead turn,
// because the client clears it only on input_resolved or on the next send.
let awaitAnnounced = false; // 'input_needed' already sent for the prompt now on screen
try {
// ── Resolve per-session config (system prompt, MCP, model) ─────────────
const mp = mode === 'planning' ? 'MODE: PLANNING ONLY. Analyze, plan, DO NOT modify files.\n\n'
: mode === 'task' ? 'MODE: EXECUTION.\n\n' : '';
// AGENTS.md (issue #54) rides along in the same --append-system-prompt this
// engine already spawns with. It lands in cfgHash below on purpose: editing
// AGENTS.md then respawns the tmux session with --resume, exactly as changing
// skills or the model does. Empty string when there is nothing to add, so a
// project without AGENTS.md keeps its previous hash and does NOT respawn.
const agentsMd = agentsMdPreamble(workdir || process.cwd());
const sp = [(mp + (systemPrompt || '')).trim(), agentsMd].filter(Boolean).join('\n\n');
const modelAlias = /^[a-zA-Z0-9._-]+$/.test(String(model || '')) ? model : 'sonnet';
const mcpPath = mcpConfigPath(mcpServers);
let mcpJson = '';
if (mcpPath) { try { mcpJson = fs.readFileSync(mcpPath, 'utf8'); } catch {} }
const cfgHash = crypto.createHash('sha256').update(JSON.stringify([sp, mcpJson, modelAlias])).digest('hex').slice(0, 16);
// ── Spawn (or reuse) the tmux session ──────────────────────────────────
// tmux alive but no recorded claude session id: without a cid we cannot
// locate the transcript — kill and respawn fresh.
if (!cid && tmuxHasSession(name)) killInteractiveTmux(sessionId);
// Config changed since spawn (skills/mode/MCP/model)? Respawn with --resume —
// verified to keep writing to the SAME <cid>.jsonl transcript.
if (cid && tmuxHasSession(name) && getTmuxEnv(name, 'CCS_CFG') !== cfgHash) {
killInteractiveTmux(sessionId);
}
let spawned = false;
if (!tmuxHasSession(name)) {
spawned = true;
const resuming = !!cid;
if (!cid) cid = crypto.randomUUID();
const idFlag = resuming ? `--resume ${shq(cid)}` : `--session-id ${shq(cid)}`;
const claudeBin = findClaudeBin();
let innerCmd = `env -u CLAUDECODE ${shq(claudeBin)} ${idFlag} --model ${shq(modelAlias)} --dangerously-skip-permissions`;
if (sp) innerCmd += ` --append-system-prompt ${shq(sp)}`;
if (mcpPath) innerCmd += ` --mcp-config ${shq(mcpPath)}`;
const env = utf8Env();
delete env.CLAUDECODE; // parent Claude Code session sets this and it confuses the child
const child = spawn('tmux', tmuxArgs(['new-session', '-d', '-s', name, '-x', '220', '-y', '50', '-c', workdir || process.cwd(), innerCmd]), { env, stdio: 'ignore' });
await new Promise((resolve) => {
child.on('exit', resolve);
child.on('error', resolve);
});
if (!tmuxHasSession(name)) {
wsSend({ type: 'error', error: 'failed to start tmux session for interactive engine' });
return { cid, completed: false, resultMeta: null, fullText: '', fullThinking: '', toolEvents: [] };
}
setTmuxEnv(name, 'CCS_CFG', cfgHash);
// Wait for the TUI to settle: two consecutive identical, non-empty captures
let prev = null;
const settleDeadline = Date.now() + 20000;
while (Date.now() < settleDeadline) {
await sleep(500);
const cap = capturePane(name);
if (cap && cap.trim() && cap === prev) break;
prev = cap;
}
// A brand-new TUI can settle ON A DIALOG rather than on its input box — the
// --dangerously-skip-permissions acceptance screen and the trust-this-folder
// question both look "settled" because they are static. Pasting the user's
// message into one answers it with whichever option the text lands on. Tell
// the browser and give a human a bounded window to clear it in the live pane
// (GitHub #20). On timeout we fall through and paste anyway — the pre-#20
// behaviour — so a false positive costs a delay, never a lost message.
}
// A pane can be sitting on a blocking widget for either reason: a fresh TUI that
// settled on the trust-this-folder / skip-permissions screen, or a REUSED pane
// whose previous turn ended (idle timeout, grace expiry, a closed browser tab)
// while its dialog was still up. Both fail the same way — the paste-buffer below
// answers the widget with whatever option the caret sits on, which can be a
// permission grant. So the check runs before EVERY paste, not only after a spawn.
// On timeout we fall through and paste anyway (the pre-#20 behaviour): a false
// positive costs a delay, never a lost message.
if (SPAWN_PROMPT_WAIT_MS > 0 && paneAwaitingInput(capturePane(name))) {
awaitAnnounced = true;
wsSendAll({ type: 'input_needed', sessionId, engine: 'subscription', phase: spawned ? 'startup' : 'resume', prompt: promptExcerpt(capturePane(name)) });
const until = Date.now() + SPAWN_PROMPT_WAIT_MS;
while (Date.now() < until) {
await sleep(POLL_MS);
if (abortController?.signal?.aborted) break;
if (!paneAwaitingInput(capturePane(name))) break;
}
awaitAnnounced = false;
wsSendAll({ type: 'input_resolved', sessionId });
}
// ── Record transcript offset BEFORE sending ────────────────────────────
let transcriptPath = findTranscript(cid);
let offset = 0;
if (transcriptPath) {
try { offset = fs.statSync(transcriptPath).size; } catch { offset = 0; }
}
// ── Flatten structured userContent: extra text blocks are prepended, image
// blocks are saved to temp files the agent can open with its Read tool ─────
let sendText = String(prompt || '');
if (Array.isArray(userContent)) {
const extra = [];
for (const block of userContent) {
if (!block || typeof block !== 'object') continue;
if (block.type === 'text') {
// the main prompt text is already in sendText — keep only extra blocks (e.g. SSH host info)
if (block.text && block.text !== prompt) extra.push(block.text);
} else if (block.type === 'image' && block.source?.data) {
try {
const ext = String(block.source.media_type || 'image/png').split('/')[1] || 'png';
const imgFile = path.join(os.tmpdir(), `ccs-att-${crypto.randomBytes(6).toString('hex')}.${ext}`);
fs.writeFileSync(imgFile, Buffer.from(block.source.data, 'base64'));
extra.push(`[Attached image saved at: ${imgFile} — use the Read tool to view it]`);
} catch {}
} else if (block.type === 'file' && block.source?.data) {
// Without this branch every non-image attachment is silently dropped on the
// way into the pane. buildAttachmentContentBlocks emits `file` for text files
// AND binaries, and the deferred clarification follow-up (server.js finally
// block) rehydrates base64 specifically so it can travel this path — the
// original temp file is already unlinked by then, so ignoring the block loses
// the attachment outright.
try {
const safe = path.basename(String(block.source.name || 'attachment.bin')).replace(/[^\w.\-]+/g, '_').slice(0, 60) || 'attachment.bin';
const outFile = path.join(os.tmpdir(), `ccs-att-${crypto.randomBytes(6).toString('hex')}-${safe}`);
fs.writeFileSync(outFile, Buffer.from(block.source.data, 'base64'));
extra.push(`[Attached file saved at: ${outFile} — use the Read tool to open it]`);
} catch {}
}
}
if (extra.length) sendText = extra.join('\n') + '\n\n' + sendText;
}
// ── Send the prompt (tmp file → tmux buffer → bracketed paste → Enter) ─
const tmpFile = path.join(os.tmpdir(), `ccs-msg-${crypto.randomBytes(8).toString('hex')}.txt`);
const bufName = `ccsbuf-${crypto.randomBytes(4).toString('hex')}`;
try {
fs.writeFileSync(tmpFile, sendText);
spawnSync('tmux', tmuxArgs(['load-buffer', '-b', bufName, tmpFile]), { stdio: 'ignore' });
spawnSync('tmux', tmuxArgs(['paste-buffer', '-dpr', '-t', name, '-b', bufName]), { stdio: 'ignore' });
await sleep(300);
spawnSync('tmux', tmuxArgs(['send-keys', '-t', name, 'Enter']), { stdio: 'ignore' });
} finally {
try { fs.unlinkSync(tmpFile); } catch {}
}
// ── Poll loop: completion = transcript turn-end (stop_reason) gated by the
// TUI spinner having cleared; pane is the gate, never the primary signal ──
let remainder = '';
let endTurnSeen = false; // latched when an assistant record ends the turn (stop_reason ≠ tool_use)
let sawOutput = false;
let quietPolls = 0; // consecutive polls with spinner gone (!busy) AND no new transcript bytes
let prevPaneCap = null; // previous pane capture — for spinner-animation detection in paneBusy()
let lastActivityAt = start; // idle watchdog cursor — bumped on transcript progress (new bytes)
let injectFails = 0; // consecutive failed clarification pastes — see INJECT_MAX_FAILS
let awaitPolls = 0; // consecutive polls showing a blocking prompt
while (true) {
await sleep(POLL_MS);
if (abortController?.signal?.aborted) {
// Interrupt the turn, keep the tmux session alive
try { spawnSync('tmux', tmuxArgs(['send-keys', '-t', name, 'Escape']), { stdio: 'ignore' }); } catch {}
return { cid, completed: false, resultMeta: { durationMs: Date.now() - start }, fullText, fullThinking, toolEvents };
}
if (Date.now() - lastActivityAt > IDLE_TIMEOUT_MS) {
const mins = Math.round(IDLE_TIMEOUT_MS / 60000);
wsSend({ type: 'error', error: `interactive engine timed out — no activity for ${mins} min (idle). Raise CLAUDE_IDLE_TIMEOUT_MS to allow longer silences.` });
return { cid, completed: false, resultMeta: { durationMs: Date.now() - start }, fullText, fullThinking, toolEvents };
}
if (HARD_CAP_MS > 0 && Date.now() - start > HARD_CAP_MS) {
const mins = Math.round(HARD_CAP_MS / 60000);
wsSend({ type: 'error', error: `interactive engine timed out — exceeded hard cap of ${mins} min (CLAUDE_HARD_CAP_MS).` });
return { cid, completed: false, resultMeta: { durationMs: Date.now() - start }, fullText, fullThinking, toolEvents };
}
// Locate transcript lazily — file may not exist until the first reply starts
if (!transcriptPath) {
transcriptPath = findTranscript(cid);
if (transcriptPath) offset = 0;
}
// Tail new transcript bytes from the recorded offset
let gotNewBytes = false;
if (transcriptPath) {
let size = 0;
try { size = fs.statSync(transcriptPath).size; } catch { size = 0; }
if (size > offset) {
gotNewBytes = true;
let chunk = '';
try {
const fd = fs.openSync(transcriptPath, 'r');
try {
const buf = Buffer.alloc(size - offset);
const bytesRead = fs.readSync(fd, buf, 0, buf.length, offset);
chunk = buf.subarray(0, bytesRead).toString('utf8');
offset += bytesRead;
} finally {
fs.closeSync(fd);
}
} catch {}
const data = remainder + chunk;
const lines = data.split('\n');
remainder = lines.pop() || ''; // keep trailing partial line
for (const line of lines) {
if (!line.trim()) continue;
let rec;
try { rec = JSON.parse(line); } catch { continue; }
if (rec.type !== 'assistant') continue; // ignore user/system/attachment records
const blocks = rec.message?.content;
if (Array.isArray(blocks)) {
for (const block of blocks) {
if (block.type === 'text' && block.text) {
fullText += block.text;
sawOutput = true;
wsSend({ type: 'text', text: block.text });
} else if (block.type === 'thinking' && block.thinking) {
fullThinking += block.thinking;
sawOutput = true;
wsSend({ type: 'thinking', text: block.thinking });
} else if (block.type === 'tool_use') {
const input = JSON.stringify(block.input || {}).substring(0, 600);
toolEvents.push({ name: block.name, input });
sawOutput = true;
wsSend({ type: 'tool', tool: block.name, input });
}
}
}
// Turn-completion signal (authoritative, version-independent):
// `tool_use` is the ONLY stop_reason meaning "the agent will continue
// after the tool result". Every other terminal value — end_turn |
// stop_sequence | refusal (the full set observed across the local
// transcript corpus) — ends the turn. The old code matched only
// `end_turn` AND was gated behind `!busy`, a pane marker
// ('esc to interrupt') that no longer exists in the TUI, so `busy`
// was always false and completion fell through to a 3s-quiet
// heuristic that fired mid-task — reporting "done" while the agent
// was still working.
const _sr = rec.message?.stop_reason;
if (_sr === 'tool_use') endTurnSeen = false;
else if (_sr) endTurnSeen = true;
}
}
}
const pane = capturePane(name);
const busy = paneBusy(pane, prevPaneCap);
prevPaneCap = pane;
// ── Blocked on an interactive prompt? (GitHub #20) ─────────────────────
// The widget is on screen AND the spinner is stopped AND nothing was written
// this poll: the agent is not working, it is waiting for a human. Announce it
// so the browser can offer the live pane instead of letting the turn die on a
// timeout with no explanation. Both edges are reported — the banner has to be
// able to clear itself when the prompt is answered.
const awaiting = !busy && !gotNewBytes && paneAwaitingInput(pane);
awaitPolls = awaiting ? awaitPolls + 1 : 0;
if (awaiting && !awaitAnnounced && awaitPolls >= AWAIT_CONFIRM_POLLS) {
awaitAnnounced = true;
wsSendAll({ type: 'input_needed', sessionId, engine: 'subscription', prompt: promptExcerpt(pane) });
} else if (awaitAnnounced && !awaiting) {
awaitAnnounced = false;
wsSendAll({ type: 'input_resolved', sessionId });
}
// Mid-run clarifications. The hook mechanism the headless engine uses cannot
// apply here — there is no per-run --settings to inject, the CLI is already
// running interactively. The equivalent for a live TUI is to type the message
// into it, which is exactly what a person sitting at the terminal would do —
// and a person cannot type into a busy TUI (spinner running) or into a
// permission/plan prompt without hijacking whatever option is selected. Only
// drain (and thus mark delivered) once the pane genuinely has an open input
// line: not busy, not showing a blocking widget, AND actually captured — a
// failed capture must NOT read as idle (paneBusy/paneAwaitingInput both
// return false for a null pane, the one case we can least confirm it's safe).
//
// This runs BEFORE the completion check below, not after. `busy` normally
// stays true (spinner/timer animation) right up until endTurnSeen latches, so
// the "idle and the loop hasn't exited yet" window IS the tick the turn ends —
// draining after the break left this code effectively dead on a normal,
// healthy completion, silently losing the clarification instead of typing it.
let injected = false;
// Independent re-check of the pane's prompt state, not the `awaiting` variable
// computed above: `awaiting` is forced false whenever `gotNewBytes` is true this
// tick (see its definition), so a permission/plan widget that appears in the
// same poll as trailing transcript bytes would otherwise pass this gate and get
// hijacked by a pasted clarification.
if (pane && !busy && !paneAwaitingInput(pane) && injectFails < INJECT_MAX_FAILS && typeof drainInterrupts === 'function') {
let pending = [];
try { pending = drainInterrupts() || []; } catch {}
// One paste + one Enter for the whole batch: busy/awaiting were sampled
// once for this tick, so pasting item 2 after item 1's Enter already
// restarted the spinner would land in a pane no longer listening.
const parts = [];
for (const m of pending) {
if (m.content) parts.push(m.content);
for (const att of (Array.isArray(m.attachments) ? m.attachments : [])) {
if (att.type === 'ssh') {
// An SSH entry has no `path` — without this it contributed nothing and the
// pane got a bare "[See attached files]". Mirrors buildAttachmentContentBlocks:
// host and key path only, never the credential (this text lands in the CLI
// transcript on disk).
let t = `[SSH Host: ${att.label || att.host || 'SSH'}]\nHost: ${att.host}:${att.port || 22}`;
if (att.sshKeyPath) t += `\nSSH Key: ${att.sshKeyPath}`;
else if (att.authMethod === 'password') t += `\nAuth: password (held server-side, not exposed)`;
parts.push(t);
} else if (att.path) {
parts.push(`[Attached ${att.mimeType && att.mimeType.startsWith('image/') ? 'image' : 'file'}: ${att.name || 'file'}]\nSaved at: ${att.path}\nRead it before continuing.`);
}
}
}
const body = parts.join('\n\n').trim();
if (body) {
const note = `USER CLARIFICATION${pending.length > 1 ? 'S' : ''} (sent while you were working):\n\n${body}`;
const tmpFile = path.join(os.tmpdir(), `ccs-int-${crypto.randomBytes(6).toString('hex')}.txt`);
const bufName = `ccsint-${crypto.randomBytes(4).toString('hex')}`;
let delivered = false;
try {
fs.writeFileSync(tmpFile, note);
const load = spawnSync('tmux', tmuxArgs(['load-buffer', '-b', bufName, tmpFile]), { stdio: 'ignore' });
const paste = spawnSync('tmux', tmuxArgs(['paste-buffer', '-dpr', '-t', name, '-b', bufName]), { stdio: 'ignore' });
if (load.status === 0 && paste.status === 0) {
await sleep(250);
const enter = spawnSync('tmux', tmuxArgs(['send-keys', '-t', name, 'Enter']), { stdio: 'ignore' });
delivered = enter.status === 0;
}
} catch {} finally { try { fs.unlinkSync(tmpFile); } catch {} }
if (delivered) {
injected = true;
injectFails = 0;
if (typeof markInterruptsDelivered === 'function') { try { markInterruptsDelivered(pending); } catch {} }
} else if (typeof requeueInterrupts === 'function') {
// Genuinely undo the drain: put it back for the next idle tick to retry,
// or — if the turn ends first — for the caller's finally-block follow-up
// to run it as the next turn instead of it vanishing after being popped.
try { requeueInterrupts(pending); } catch {}
injectFails++;
// Only the last attempt talks to the user. A dead pane fails every poll,
// and one error frame per ~1.5s tick for the rest of a long turn is a
// toast storm, not a diagnostic.
if (injectFails >= INJECT_MAX_FAILS) {
// nonTerminal: the poll loop is still running this turn. Without the flag the
// client's `error` case tears the turn down — clears isGen, the Stop button
// and tab.generating — and the user is invited to send into a live turn.
wsSend({ type: 'error', nonTerminal: true, error: 'clarification could not be typed into the interactive session — it will be sent as the next message instead' });
}
} else {
// No requeue channel (a caller that predates it): the batch is already
// drained and cannot be put back, so report the loss rather than imply
// a retry that will not happen.
injectFails++;
wsSend({ type: 'error', nonTerminal: true, error: 'clarification could not be typed into the interactive session' });
}
} else if (pending.length && typeof markInterruptsDelivered === 'function') {
// Nothing left to type (e.g. an SSH-only attachment, which has no file path
// to reference) — there's no pane action to retry, so don't leave it queued.
try { markInterruptsDelivered(pending); } catch {}
}
}
if (injected) {
// A new turn was just kicked off in the pane — the endTurnSeen/busy/
// gotNewBytes gathered above describe the turn that just ended, not what
// comes next. Skip the completion checks below and let the next poll
// observe the new turn fresh instead of breaking on stale state.
endTurnSeen = false;
quietPolls = 0;
lastActivityAt = Date.now();
continue;
}
// COMPLETE on the transcript turn-end signal, but ONLY once the spinner has
// cleared and no bytes arrived this poll. `tool_use` is the sole "continue"
// stop_reason; any other terminal value latches endTurnSeen. Because a
// single message's blocks are written as separate records up to ~20s apart
// (thinking → text), endTurnSeen can latch on the thinking record before the
// final text is flushed — the !busy guard (spinner still animating during
// that gap) holds the break until the whole message is out. Pane text is
// never the PRIMARY signal (spinner wording is version-specific); it only
// gates when to trust the already-latched transcript signal.
if (endTurnSeen && !busy && !gotNewBytes) break;
if (gotNewBytes) lastActivityAt = Date.now(); // transcript progress = real work; resets idle watchdog
if (gotNewBytes || busy) quietPolls = 0; else quietPolls++;
// Safety-net completion: output WAS produced, then the spinner cleared and
// no new bytes arrived for ~18s. Covers a missed turn-end stop_reason (e.g.
// a corrupt final transcript line that failed to JSON.parse). Safe because
// a working agent keeps `busy` true (animation/timer), so quietPolls only
// climbs once the turn has genuinely ended.
// While a prompt is pending, "quiet" is the expected state, not a stalled turn:
// widen both quiet-based exits by the grace budget so there is time to answer in
// the live pane. Without this the safety-net below fires ~18s into the wait and
// reports the turn DONE while the TUI is still blocked — after which the next web
// message gets pasted into the open widget instead of into the prompt box.
const graceP = awaitAnnounced ? Math.ceil(AWAIT_GRACE_MS / POLL_MS) : 0;
if (sawOutput && quietPolls >= 12 + graceP) break;
// Dead-end guard: zero output AND spinner gone for ~30s — the message never
// registered with the TUI; fail fast instead of waiting out the idle timeout.
// A long thinking phase or slow first tool keeps `busy` true (spinner
// animating) or writes a record (sawOutput), so neither trips this.
if (!sawOutput && quietPolls >= 20 + graceP) {
wsSend({ type: 'error', error: 'interactive session went idle without producing a reply' });
return { cid, completed: false, resultMeta: { durationMs: Date.now() - start }, fullText, fullThinking, toolEvents };
}
}
return { cid, completed: true, resultMeta: { durationMs: Date.now() - start }, fullText, fullThinking, toolEvents };
} catch (e) {
wsSend({ type: 'error', error: 'interactive engine error: ' + (e?.message || String(e)) });
return { cid, completed: false, resultMeta: { durationMs: Date.now() - start }, fullText, fullThinking, toolEvents };
} finally {
// The turn is over whichever way it ended; the banner must not outlive it.
if (awaitAnnounced) { awaitAnnounced = false; wsSendAll({ type: 'input_resolved', sessionId }); }
}
}
// ─── Catch-up: pull transcript activity done OUTSIDE the web UI ───────────────
// When the user opens a real terminal on a session (the "⚡ Claude Code" button →
// `claude --resume <cid>`), their typing + Claude's replies are appended to the
// SAME <cid>.jsonl this module reads. These helpers let the server pull that gap
// into the web chat on demand. Pure: no tmux, no WebSocket, no SQLite — the
// caller persists the events and re-renders.
// Current byte size of <cid>.jsonl, or null if no transcript exists yet. The
// server calls this to advance the catch-up cursor to EOF after every web turn,
// so a later catch-up only surfaces bytes a terminal session appended afterwards.
function transcriptSize(cid) {
const p = cid ? findTranscript(cid) : null;
if (!p) return null;
try { return fs.statSync(p).size; } catch { return null; }
}
// Extract the human-typed text from a transcript `user` record. Records carrying
// only tool_result / image blocks (tool output fed back to the agent, not
// something a person typed) return '' and are skipped by the caller.
function userRecordText(rec) {
const c = rec && rec.message ? rec.message.content : undefined;
if (typeof c === 'string') return c.trim();
if (Array.isArray(c)) {
const parts = [];
for (const b of c) {
if (b && b.type === 'text' && typeof b.text === 'string') parts.push(b.text);
}
return parts.join('\n').trim();
}
return '';
}
// Read <cid>.jsonl records appended since `startOffset` and return them as an
// ordered event list plus the new byte offset. The offset advances ONLY past
// COMPLETE lines (to the last '\n'); a half-written trailing record is left for
// the next call. Returns { found, offset, events }.
function catchUpFromTranscript({ cid, startOffset = 0 } = {}) {
const out = { found: false, offset: Number(startOffset) || 0, events: [] };
const transcriptPath = cid ? findTranscript(cid) : null;
if (!transcriptPath) return out;
out.found = true;
let size = 0;
try { size = fs.statSync(transcriptPath).size; } catch { return out; }
const from = Math.max(0, Math.min(Number(startOffset) || 0, size));
out.offset = from;
if (size <= from) return out;
let buf;
try {
const fd = fs.openSync(transcriptPath, 'r');
try {
buf = Buffer.alloc(size - from);
const n = fs.readSync(fd, buf, 0, buf.length, from);
buf = buf.subarray(0, n);
} finally { fs.closeSync(fd); }
} catch { return out; }
const lastNl = buf.lastIndexOf(0x0A);
if (lastNl < 0) return out; // no complete line yet — keep offset
out.offset = from + lastNl + 1; // byte-accurate advance past last newline
const text = buf.subarray(0, lastNl + 1).toString('utf8');
for (const line of text.split('\n')) {
if (!line.trim()) continue;
let rec;
try { rec = JSON.parse(line); } catch { continue; }
const ts = rec.timestamp || null; // real record time → caller uses it as created_at
if (rec.type === 'user') {
const txt = userRecordText(rec);
if (txt) out.events.push({ role: 'user', type: 'text', content: txt, ts });
} else if (rec.type === 'assistant') {
const blocks = rec.message && rec.message.content;
if (!Array.isArray(blocks)) continue;
for (const block of blocks) {
if (block.type === 'text' && block.text) {
out.events.push({ role: 'assistant', type: 'text', content: block.text, ts });
} else if (block.type === 'thinking' && block.thinking) {
out.events.push({ role: 'assistant', type: 'thinking', content: block.thinking, ts });
} else if (block.type === 'tool_use') {
out.events.push({ role: 'assistant', type: 'tool', content: JSON.stringify(block.input || {}).substring(0, 600), tool_name: block.name, ts });
}
}
}
}
return out;
}
module.exports = { runInteractiveSingle, killInteractiveTmux, tmuxAvailable, catchUpFromTranscript, transcriptSize, tmuxName, listOrphanedDefaultSocketSessions, paneAwaitingInput, promptExcerpt };