Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions CLAUDE.md

Large diffs are not rendered by default.

10 changes: 9 additions & 1 deletion claude-interactive.js
Original file line number Diff line number Diff line change
Expand Up @@ -595,7 +595,7 @@ function startEngineIdleReaper(opts = {}) {
// 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 { prompt, systemPrompt, model, mode, ws, sessionId, abortController, claudeSessionId, workdir, tabId, mcpServers, userContent, drainInterrupts, markInterruptsDelivered, requeueInterrupts, fanout, onPromptState } = params;
const start = Date.now();
const wsSend = (obj) => {
try { ws.send(JSON.stringify({ ...obj, ...(tabId ? { tabId } : {}) })); } catch {}
Expand All @@ -606,9 +606,17 @@ async function runInteractiveSingle(params) {
// 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.
// `onPromptState` hears the same two edges, so the caller can remember a prompt that
// is still open: a page RELOADED while the turn waits has no socket that saw
// input_needed and no tab state left to redraw the banner from (#130).
const wsSendAll = (obj) => {
wsSend(obj);
if (typeof fanout === 'function') { try { fanout({ ...obj, ...(tabId ? { tabId } : {}) }); } catch {} }
// Only the two prompt edges: any other frame routed through here later must not
// read as "answered" and erase a prompt that is still open.
if (typeof onPromptState === 'function' && (obj.type === 'input_needed' || obj.type === 'input_resolved')) {
try { onPromptState(obj.type === 'input_needed' ? { ...obj, ...(tabId ? { tabId } : {}) } : null); } catch {}
}
};

let fullText = '', fullThinking = '';
Expand Down
39 changes: 39 additions & 0 deletions engine-prompts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';
// The prompt a subscription-engine turn is blocked on, remembered per session (#130).
//
// The engine announces a blocking TUI prompt ONCE (`input_needed`) and withdraws it
// once (`input_resolved`). A browser that reloads while the turn waits gets a new
// socket that saw neither frame and a fresh tab state with nothing to redraw the
// banner from — so the chat shows a running turn and no question. The server is the
// only party that outlives the page, so it keeps the open prompt and hands it to the
// next subscriber.
//
// Pure: no sockets, no SQLite. server.js decides when a session is live and who gets
// the frame; this only answers "what is open right now".

function createEnginePromptStore() {
const open = new Map(); // sessionId -> the input_needed frame, as the engine sent it

return {
// Fed by runInteractiveSingle's onPromptState: a frame while a prompt is open,
// null when it is answered or the turn ends (the engine's finally sends that edge
// on every exit path).
track(sessionId, frame) {
if (!sessionId) return;
if (frame && frame.type === 'input_needed') open.set(sessionId, frame);
else open.delete(sessionId);
},
// The frame to replay to a subscriber, or null. A prompt is only worth replaying
// while its turn is alive: an entry that outlived its turn (a crash between the
// two edges) is dropped here instead of showing a question nobody is asking.
replay(sessionId, isLive) {
const frame = open.get(sessionId);
if (!frame) return null;
if (!isLive) { open.delete(sessionId); return null; }
return { ...frame, tabId: frame.tabId || sessionId, replayed: true };
},
size() { return open.size; },
};
}

module.exports = { createEnginePromptStore };
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"scripts": {
"start": "node server.js",
"dev": "node --watch server.js",
"test": "node --test test/render/*.test.mjs && node test/overload-detector.test.js && node test/usage-limit.test.js && node test/auth-errors.test.js && node test/env-load-order.test.js && node test/multi-agent-result.test.js && node test/terminal-session.test.js && node test/terminal-schema.test.js && node test/bots.test.js && node test/bot-inbox.test.js && node test/bots-api.test.js && node test/running-sessions.test.js && node test/session-liveness.test.js && node test/terminal-bridge.integration.test.js && node test/tmux-composite.test.js && node test/engine-spawn-cmd.test.js && node test/claude-firstrun.test.js && node test/telegram-format.test.js && node test/telegram-behaviour.test.js && node test/ask-user-question.test.js && node test/delegate-terminal.test.js && node test/agent-catalog.test.js && node test/update-flow.test.js && node test/kanban-schedule.test.js && node test/kanban-run-badges.test.js && node test/task-backlog.test.js && node test/i18n-completeness.test.js && node test/config-resolve.test.js && node test/chat-defaults.test.js && node test/chat-defaults-api.test.js && node test/run-continuation.test.js && node test/worktree-manager.test.js && node test/session-expiry.test.js && node test/setup-gate.test.js && node test/path-guard.test.js && node test/subscribe-nocatchup.test.js && node test/cli-import-remote.test.js && node test/remote-list-parse.test.js && node test/config-migrate.test.js && node test/engine-pane.test.js && node test/engine-idle-reaper.test.js && node test/pane-busy.test.js && node test/global-workspace.test.js && node test/ssh-secret.test.js && node test/agent-dag.test.js && node test/ssh-parser.test.js && node test/ssh-termination.test.js && node test/session-restart.test.js && node test/remote-env.test.js && node test/remote-files.test.js && node test/remote-files-api.test.js && node test/auth-token.test.js && node test/cmd-model.test.js && node test/origin-guard.test.js && node test/interrupted-recovery.test.js && node test/queue-persistence.test.js && node test/interrupt-idle-config.test.js && node test/agents-md.test.js && node test/editor-links.test.js && node test/editor-open-api.test.js && node test/interrupt-delivery.test.js && node test/terminal-pane-guard.integration.test.js && node test/composer-terminal.test.js && node test/claude-cli-status.test.js && node test/asar-helpers.test.js && node test/mac-signing.test.js && node test/release-mac.test.js && node test/task-workers.test.js && node test/git-clone.test.js && node test/responsive-ui.test.js && node test/kanban-delegation.test.js && node test/kanban-group-button.test.js && node test/terminal-keys.test.js && node test/electron-navigation.test.js && node test/cli-runtime.test.js && node test/worktree-safety.test.js && node test/auth-boundary.test.js && node test/cli-process-tree.test.js && node test/schedule-actions.test.js && node test/install-hooks.test.js && node test/frontend-recovery.test.js && node test/db-revisions.test.js && node test/frontend-refresh-races.test.js && node test/release-gate.test.js && node test/focused-workspace.test.js && node test/secondary-navigation.test.js && node test/section-controls-ux.test.js && node test/settings-ux.test.js && node test/team-forms-ux.test.js && node test/page-forms-ux.test.js && node test/sidebar-ux.test.js && node test/task-text-limit.test.js && node test/terminal-clipboard.test.js && node test/terminal-addons.test.js && node test/file-preview-copy.test.js && node test/telegram-lang.test.js",
"test": "node --test test/render/*.test.mjs && node test/overload-detector.test.js && node test/usage-limit.test.js && node test/auth-errors.test.js && node test/env-load-order.test.js && node test/multi-agent-result.test.js && node test/terminal-session.test.js && node test/terminal-schema.test.js && node test/bots.test.js && node test/bot-inbox.test.js && node test/bots-api.test.js && node test/running-sessions.test.js && node test/session-liveness.test.js && node test/terminal-bridge.integration.test.js && node test/tmux-composite.test.js && node test/engine-spawn-cmd.test.js && node test/claude-firstrun.test.js && node test/telegram-format.test.js && node test/telegram-behaviour.test.js && node test/ask-user-question.test.js && node test/delegate-terminal.test.js && node test/agent-catalog.test.js && node test/update-flow.test.js && node test/kanban-schedule.test.js && node test/kanban-run-badges.test.js && node test/task-backlog.test.js && node test/i18n-completeness.test.js && node test/config-resolve.test.js && node test/chat-defaults.test.js && node test/chat-defaults-api.test.js && node test/run-continuation.test.js && node test/worktree-manager.test.js && node test/session-expiry.test.js && node test/setup-gate.test.js && node test/path-guard.test.js && node test/subscribe-nocatchup.test.js && node test/cli-import-remote.test.js && node test/remote-list-parse.test.js && node test/config-migrate.test.js && node test/engine-pane.test.js && node test/engine-idle-reaper.test.js && node test/pane-busy.test.js && node test/engine-prompts.test.js && node test/engine-prompt-replay.test.js && node test/global-workspace.test.js && node test/ssh-secret.test.js && node test/agent-dag.test.js && node test/ssh-parser.test.js && node test/ssh-termination.test.js && node test/session-restart.test.js && node test/remote-env.test.js && node test/remote-files.test.js && node test/remote-files-api.test.js && node test/auth-token.test.js && node test/cmd-model.test.js && node test/origin-guard.test.js && node test/interrupted-recovery.test.js && node test/queue-persistence.test.js && node test/interrupt-idle-config.test.js && node test/agents-md.test.js && node test/editor-links.test.js && node test/editor-open-api.test.js && node test/interrupt-delivery.test.js && node test/terminal-pane-guard.integration.test.js && node test/composer-terminal.test.js && node test/claude-cli-status.test.js && node test/asar-helpers.test.js && node test/mac-signing.test.js && node test/release-mac.test.js && node test/task-workers.test.js && node test/git-clone.test.js && node test/responsive-ui.test.js && node test/kanban-delegation.test.js && node test/kanban-group-button.test.js && node test/terminal-keys.test.js && node test/electron-navigation.test.js && node test/cli-runtime.test.js && node test/worktree-safety.test.js && node test/auth-boundary.test.js && node test/cli-process-tree.test.js && node test/schedule-actions.test.js && node test/install-hooks.test.js && node test/frontend-recovery.test.js && node test/db-revisions.test.js && node test/frontend-refresh-races.test.js && node test/release-gate.test.js && node test/focused-workspace.test.js && node test/secondary-navigation.test.js && node test/section-controls-ux.test.js && node test/settings-ux.test.js && node test/team-forms-ux.test.js && node test/page-forms-ux.test.js && node test/sidebar-ux.test.js && node test/task-text-limit.test.js && node test/terminal-clipboard.test.js && node test/terminal-addons.test.js && node test/file-preview-copy.test.js && node test/telegram-lang.test.js",
"postinstall": "node scripts/install-hooks.js",
"release": "node scripts/release.js",
"release:mac": "node scripts/release-mac.js",
Expand Down
13 changes: 13 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ const botsLogic = require('./bots');
// to go on".
const BARE_MENTION_PROMPT = "You were addressed directly with no other text — greet them and ask what they need, or continue naturally if there is relevant prior context in this conversation.";
const { runInteractiveSingle, killInteractiveTmux, tmuxAvailable, catchUpFromTranscript, transcriptSize, tmuxName: interactiveTmuxName, listOrphanedDefaultSocketSessions, startEngineIdleReaper } = require('./claude-interactive');
// The prompt a subscription turn is blocked on, kept so a RELOADED page can be told (#130).
const enginePrompts = require('./engine-prompts').createEnginePromptStore();
const WM = require('./worktree-manager');
const ClaudeSSH = require('./claude-ssh');
const { testSshConnection } = require('./claude-ssh');
Expand Down Expand Up @@ -2130,6 +2132,7 @@ async function startTask(task) {
prompt: currentTaskPrompt, systemPrompt: '', model: session?.model || task.model || 'sonnet',
mode: task.mode || 'auto', ws: _proxy, sessionId, abortController: taskAbort,
claudeSessionId: currentTaskCid, workdir: task.workdir || WORKDIR, mcpServers: taskMcpServers,
onPromptState: (f) => enginePrompts.track(sessionId, f),
// Same gap the chat path had, and found while reviewing that fix: the api
// engine below delivers clarifications through the check-interrupt hook, but
// the subscription engine has no hooks. Without these three callbacks a
Expand Down Expand Up @@ -10344,6 +10347,7 @@ async function processTelegramChat({ sessionId, text, userId, chatId, threadId,
// (mirrors the WS chat handler's subscription branch).
const r = await runInteractiveSingle({
...params,
onPromptState: (f) => enginePrompts.track(params.sessionId, f),
// Matches the web WS handler's subscription branch: without a drain function,
// a clarification typed into a busy Telegram chat on this engine sat in
// pendingInterrupts and was NEVER delivered — this engine has no hook to pull
Expand Down Expand Up @@ -12273,6 +12277,7 @@ wss.on('connection', (ws) => {
// waits for someone to answer a permission prompt. Only the blocked/unblocked
// frames are fanned out; `ws` is excluded because it is served above.
fanout: (obj) => { try { broadcastToSessionExcept(localSessionId, ws, obj); } catch {} },
onPromptState: (f) => enginePrompts.track(localSessionId, f),
// Draining no longer implies delivery: the engine still has to type the text
// into the tmux pane, and that can fail. It reports back through the two
// callbacks below, so a paste that never landed is re-queued instead of
Expand Down Expand Up @@ -13024,6 +13029,14 @@ wss.on('connection', (ws) => {
}
}
}
// A subscription turn blocked on a TUI prompt announced it once; a page reloaded
// since then saw neither that frame nor kept the tab state that redraws the
// banner (#130). Not for noCatchUp: a background tab that never reloaded still
// holds the prompt and would only get the notification a second time.
if (!noCatchUp && ws.readyState === 1) {
const _openPrompt = enginePrompts.replay(sessionId, isSessionLive(sessionId));
if (_openPrompt) { try { ws.send(JSON.stringify(_openPrompt)); } catch {} }
}
// Cancel any pending delayed cleanup — a live WS is reclaiming this session
const _cleanupTimer = sessionQueueCleanupTimers.get(sessionId);
if (_cleanupTimer) { clearTimeout(_cleanupTimer); sessionQueueCleanupTimers.delete(sessionId); }
Expand Down
7 changes: 6 additions & 1 deletion test/claude-firstrun.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,8 @@ process.on('exit', cleanup);
// NAME instead of hanging the suite until the engine's own idle watchdog.
const ac = new AbortController();
const guard = setTimeout(() => ac.abort(), 20000);
const r = await CI.runInteractiveSingle({ prompt: 'please do the thing', model: 'sonnet', mode: 'auto', ws, sessionId: engineSession, workdir: proj, abortController: ac });
const promptStates = [];
const r = await CI.runInteractiveSingle({ prompt: 'please do the thing', model: 'sonnet', mode: 'auto', ws, sessionId: engineSession, workdir: proj, abortController: ac, onPromptState: (f) => promptStates.push(f && f.type) });
clearTimeout(guard);
const cfgFile = path.join(HOME, '.claude.json');
const seeded = fs.existsSync(cfgFile) ? JSON.parse(fs.readFileSync(cfgFile, 'utf8')) : { projects: {} };
Expand All @@ -190,6 +191,10 @@ process.on('exit', cleanup);
const si = argv.indexOf('--settings');
check('--settings reaches the child argv byte-identical', si >= 0 ? argv[si + 1] : null, FR.SKIP_BYPASS_WARNING_SETTINGS);
check('the browser was told the turn is blocked', frames.some(f => f.type === 'input_needed' && f.phase === 'startup'), true);
// #130: the server remembers an open prompt through this callback so a reloaded page
// can be told. It must hear the opening edge AND the closing one the engine's finally
// sends, or a prompt from a dead turn would be replayed forever.
check('onPromptState heard the prompt open, then close', [promptStates[0], promptStates[promptStates.length - 1]], ['input_needed', null]);
const err = frames.find(f => f.type === 'error');
check('a screen still up after the wait is reported with the screen', !!err && /waiting on a screen/.test(err.error) && /Yes, I trust this folder/.test(err.error), true);
check('the turn ends incomplete', r.completed, false);
Expand Down
Loading
Loading