Fix orphaned quick commands, prompt timeouts and worker delete (#6, #21, #34)

- #6: a quick command to a disconnected worker is refused before an
  execution is recorded, instead of leaving one stuck in 'running'.
- #21: an unanswered prompt fails the execution (prompt_timeout) instead
  of continuing as if someone had chosen; prompt and wait steps never
  wait past the execution's deadline, and a wait cut short by it fails
  with execution_timeout. PULSE_PROMPT_TIMEOUT_MS (minimum 1 s, default
  60 min) lets the test stack use 8 s.
- #34: deleting a connected worker is a 409 explaining it would
  re-register on its next heartbeat; offline workers delete as before.

Tests for each (integration 45/45).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-23 00:04:06 -05:00
1 parent 073114c92e
commit d517cae7e6
4 files changed
+85 -11

No files matched your search

+46 -11
View File
@@ -98,6 +98,12 @@ const executionLimiter = rateLimit({
// Named constants for timeouts and limits
const PROMPT_TIMEOUT_MS = 60 * 60 * 1000; // 60 min: how long a prompt waits for user input
// Tests shorten it (minimum 1 s); production keeps the default above.
const PROMPT_TIMEOUT_EFFECTIVE_MS = (() => {
const v = parseInt(process.env.PULSE_PROMPT_TIMEOUT_MS, 10);
return Number.isInteger(v) && v >= 1000 ? v : PROMPT_TIMEOUT_MS;
})();
const PROMPT_TIMED_OUT = Symbol('prompt timed out');
const COMMAND_TIMEOUT_MS = 120_000; // 2 min: workflow step command timeout
const QUICK_CMD_TIMEOUT_MS = 60_000; // 1 min: quick/direct/gandalf command timeout
const WEBHOOK_TIMEOUT_MS = 10_000; // 10 s: outbound webhook HTTP timeout
@@ -1033,7 +1039,17 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam
}
} else if (step.type === 'prompt') {
const response = await executePromptStep(executionId, step, currentIndex + 1);
const response = await executePromptStep(executionId, step, currentIndex + 1, executionDeadline);
if (response === PROMPT_TIMED_OUT) {
// Unanswered: fail rather than carry on as if someone had chosen (#21).
await addExecutionLog(executionId, {
step: currentIndex + 1, step_name: stepLabel, action: 'prompt_timeout',
message: 'Nobody answered the prompt in time',
timestamp: new Date().toISOString()
});
await updateExecutionStatus(executionId, 'failed');
return;
}
if (response !== null) {
execState.state[step.key || 'lastPrompt'] = response;
execState.state.promptResponse = response; // backwards compat
@@ -1051,7 +1067,18 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam
step: currentIndex + 1, action: 'waiting', duration_ms: ms,
timestamp: new Date().toISOString()
});
await abortableDelay(ms, execState.abort && execState.abort.signal);
// Never wait past the execution's deadline (#21).
const remaining = executionDeadline - Date.now();
await abortableDelay(Math.max(0, Math.min(ms, remaining)), execState.abort && execState.abort.signal);
if (ms > remaining && !(execState.abort && execState.abort.signal.aborted)) {
await addExecutionLog(executionId, {
action: 'execution_timeout',
message: `Execution exceeded maximum runtime of ${maxMinutes} minutes during a wait step`,
timestamp: new Date().toISOString()
});
await updateExecutionStatus(executionId, 'failed');
return;
}
} else if (step.type === 'parse') {
// Parse KEY=VALUE lines from last command output into execution state.
@@ -1141,7 +1168,7 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam
// Pause execution and wait for user to respond via POST /api/executions/:id/respond.
// Resolves with the chosen option string, or null on 60-minute timeout.
async function executePromptStep(executionId, step, stepNumber) {
async function executePromptStep(executionId, step, stepNumber, deadline = Infinity) {
const execState = _executionState.get(executionId);
// Apply param substitution to the message so {{server_name}}, {{iface}} etc. work
let message = step.message || 'Please choose an option:';
@@ -1167,11 +1194,13 @@ async function executePromptStep(executionId, step, stepNumber) {
});
return new Promise(resolve => {
// Never wait past the execution's own deadline (#21).
const ms = Math.max(0, Math.min(PROMPT_TIMEOUT_EFFECTIVE_MS, deadline - Date.now()));
const timer = setTimeout(() => {
_executionPrompts.delete(executionId);
console.warn(`[Workflow] Prompt timed out for execution ${executionId}`);
resolve(null);
}, PROMPT_TIMEOUT_MS);
resolve(PROMPT_TIMED_OUT);
}, ms);
_executionPrompts.set(executionId, {
resolve: (response) => {
@@ -2053,6 +2082,11 @@ app.delete('/api/workers/:id', authenticateSSO, async (req, res) => {
if (!req.user.isAdmin) {
return res.status(403).json({ error: 'Admin access required' });
}
// A connected worker would re-register on its next heartbeat (#34).
const live = workers.get(req.params.id);
if (live && live.readyState === WebSocket.OPEN) {
return res.status(409).json({ error: 'Worker is connected. Stop its service first; otherwise it re-registers on its next heartbeat.' });
}
await pool.query('DELETE FROM workers WHERE id = ?', [req.params.id]);
res.json({ success: true });
@@ -2069,8 +2103,14 @@ app.post('/api/workers/:id/command', authenticateSSO, requireJSON, async (req, r
if (!command || typeof command !== 'string' || !command.trim()) {
return res.status(400).json({ error: 'command is required' });
}
const executionId = crypto.randomUUID();
const workerId = req.params.id;
// Check the worker before recording anything, so an offline worker doesn't leave
// an execution stuck in 'running' (#6).
const workerWs = workers.get(workerId);
if (!workerWs || workerWs.readyState !== WebSocket.OPEN) {
return res.status(400).json({ error: 'Worker not connected' });
}
const executionId = crypto.randomUUID();
// Create execution record in database
await pool.query(
@@ -2093,11 +2133,6 @@ app.post('/api/workers/:id/command', authenticateSSO, requireJSON, async (req, r
timeout: QUICK_CMD_TIMEOUT_MS
};
const workerWs = workers.get(workerId);
if (!workerWs || workerWs.readyState !== WebSocket.OPEN) {
return res.status(400).json({ error: 'Worker not connected' });
}
sendCommandToWorker(workerWs, commandMessage);
console.log(`Command sent to worker ${workerId}: ${command}`);