Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: resume Claude tasks after low-priority switch

[._.]/ Adam Eivy0350af0e5ece
diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.js
index a80c185677..a335fab6d1 100644
--- a/server/lib/aiToolkit/errorDetection.js
+++ b/server/lib/aiToolkit/errorDetection.js
@@ -834,26 +834,45 @@ export function detectClaudeSessionLimitBanner(text, { lineStartTrusted = true }
export function createClaudeSessionLimitBannerDetector({ maxBuffer = 1024 } = {}) {
let line = '';
let lineStartTrusted = true;
+ let lineMatched = false;
const cap = Number.isFinite(maxBuffer) && maxBuffer > 0 ? maxBuffer : 1024;
return (chunk) => {
if (!chunk) return null;
const text = `${line}${String(chunk)}`;
const lines = text.split('\n');
+ let found = null;
for (let i = 0; i < lines.length - 1; i += 1) {
- const analysis = detectClaudeSessionLimitBanner(lines[i].replace(/\r$/, ''), { lineStartTrusted });
- if (analysis) return analysis;
+ if (!lineMatched) {
+ const analysis = detectClaudeSessionLimitBanner(lines[i].replace(/\r$/, ''), { lineStartTrusted });
+ if (analysis) {
+ found ||= analysis;
+ lineMatched = true;
+ }
+ }
lineStartTrusted = true;
+ lineMatched = false;
}
line = lines.at(-1);
if (line.length > cap) {
line = line.slice(-cap);
lineStartTrusted = false;
}
- return detectClaudeSessionLimitBanner(line, { lineStartTrusted });
+ if (!lineMatched) {
+ const analysis = detectClaudeSessionLimitBanner(line, { lineStartTrusted });
+ if (analysis) {
+ found ||= analysis;
+ lineMatched = true;
+ }
+ }
+ return found;
};
}
+// A short pause lets Claude Code process its TUI mode command before the
+// rejected request is pasted again.
+export const CLAUDE_LOW_PRIORITY_RESUBMIT_DELAY_MS = 1500;
+
// Undo JSON string escaping in a value lifted out of a raw error BODY. One pass,
// so an escaped backslash can't be re-read as the start of the next escape
// (`C:\\ntemp` stays a path, not a newline). Only the `json: true` patterns
diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.js
index e2ba1ab18e..8f08a7acd0 100644
--- a/server/lib/aiToolkit/errorDetection.test.js
+++ b/server/lib/aiToolkit/errorDetection.test.js
@@ -508,6 +508,14 @@ describe('Error Detection', () => {
expect(afterLongSession("\n⏺ You've hit your session limit · resets 6:00 PM"))
.toMatchObject({ category: ERROR_CATEGORIES.USAGE_LIMIT, origin: 'provider' });
});
+
+ it('emits once for a painted line and recognizes a later banner line', () => {
+ const detect = createClaudeSessionLimitBannerDetector();
+ const banner = "⏺ You've hit your session limit · resets 6:00 PM";
+ expect(detect(banner)).toMatchObject({ category: ERROR_CATEGORIES.USAGE_LIMIT });
+ expect(detect(' repaint')).toBeNull();
+ expect(detect(`\n${banner}`)).toMatchObject({ category: ERROR_CATEGORIES.USAGE_LIMIT });
+ });
});
describe('detectTerminalModelError', () => {
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index 612665d37a..8a9934b177 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -80,6 +80,7 @@ import {
extractVerifiablePromptPrefix,
isPasteConfirmed,
isPasteCommitted,
+ CLAUDE_LOW_PRIORITY_RESUBMIT_DELAY_MS,
SUBMIT_KEY,
detectMissingTuiBinary,
} from '../../lib/tuiHandshake.js';
@@ -522,6 +523,7 @@ export function createTuiSessionController({
let immediateFallbackAnalysis = null;
const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();
const detectClaudeSessionLimitBanner = createClaudeSessionLimitBannerDetector();
+ let claudeLowPriorityPromptResubmitted = false;
const mayUseClaudeLowPriority = provider?.type === 'tui'
&& provider?.lowPriorityOnUsageLimit === true
&& isClaudeCommand(tuiConfig.command);
@@ -659,6 +661,7 @@ export function createTuiSessionController({
// silently equivalent to "nothing to stop".
let promptTimer = null;
let providerSignalTimer = null;
+ let claudeLowPriorityResubmitTimer = null;
let doneSentinelWatcher = null;
const streamingStrip = createStreamingAnsiStripper();
@@ -769,6 +772,7 @@ export function createTuiSessionController({
const stopRunMachinery = () => {
if (providerSignalTimer) { clearInterval(providerSignalTimer); providerSignalTimer = null; }
if (promptTimer) { clearInterval(promptTimer); promptTimer = null; }
+ if (claudeLowPriorityResubmitTimer) { clearTimeout(claudeLowPriorityResubmitTimer); claudeLowPriorityResubmitTimer = null; }
doneSentinelWatcher?.();
doneSentinelWatcher = null;
// Cancels the paste-attempt timers and releases the post-paste accumulator
@@ -1184,13 +1188,16 @@ export function createTuiSessionController({
recordFirstOutput('tui-pty');
// `/low-priority` is a hidden Claude Code TUI command, not a CLI startup
- // argument or a supported --print/SDK prompt. Only type it after this
- // session's submitted prompt produced the session-limit banner, and only
- // for the provider's explicit opt-in. Latch before writing so a repaint
- // of the same banner never toggles the command back off.
- if (isClaudeCommand(tuiConfig.command) && promptSubmittedAt && !lowPriorityCommandAttempted) {
+ // argument or a supported --print/SDK prompt. On an opted-in session
+ // limit, enable the mode and then re-submit the rejected task. A later
+ // limit after that re-submit means the mode was unavailable or exhausted.
+ if (isClaudeCommand(tuiConfig.command) && promptSubmittedAt) {
const sessionLimit = detectClaudeSessionLimitBanner(stripped);
if (sessionLimit) {
+ if (lowPriorityCommandAttempted) {
+ if (claudeLowPriorityPromptResubmitted) await failOverToFallback(sessionLimit);
+ return;
+ }
if (!mayUseClaudeLowPriority) {
await failOverToFallback(sessionLimit);
return;
@@ -1204,6 +1211,25 @@ export function createTuiSessionController({
}
if (submitted) {
appendLine('⏳ Claude Code session limit reached — sent /low-priority from the provider opt-in');
+ claudeLowPriorityResubmitTimer = setTimeout(() => {
+ claudeLowPriorityResubmitTimer = null;
+ if (sessionPhase !== 'running') return;
+ let promptResubmitted = false;
+ try {
+ promptResubmitted = !!pasteController?.resubmit({ label: 'Claude low-priority continuation' });
+ } catch (err) {
+ emitLog('warn', `TUI agent ${agentId} could not re-submit after Claude low-priority: ${err?.message || err}`, { agentId });
+ }
+ if (promptResubmitted) {
+ claudeLowPriorityPromptResubmitted = true;
+ appendLine('🔁 Re-submitted the task after enabling Claude low-priority mode');
+ return;
+ }
+ failOverToFallback({
+ ...sessionLimit,
+ message: 'Claude Code low-priority mode was enabled, but the task could not be re-submitted',
+ }).catch((err) => emitLog('error', `TUI agent ${agentId} low-priority re-submit fallback failed: ${err?.message || err}`, { agentId }));
+ }, CLAUDE_LOW_PRIORITY_RESUBMIT_DELAY_MS);
} else {
await failOverToFallback({
...sessionLimit,
diff --git a/server/services/agentTuiSpawning/sessionController.test.js b/server/services/agentTuiSpawning/sessionController.test.js
index 27e3facb4b..dde976dfc6 100644
--- a/server/services/agentTuiSpawning/sessionController.test.js
+++ b/server/services/agentTuiSpawning/sessionController.test.js
@@ -176,7 +176,7 @@ describe('TUI session controller — teardown owns its own machinery (#8021)', (
});
it('sends Claude low-priority once after an opted-in session-limit banner', async () => {
- const { controller, write } = makeController({
+ const { controller, write, paste, finalizeAgent } = makeController({
provider: {
id: 'claude-code-tui',
name: 'Claude Code TUI',
@@ -201,11 +201,18 @@ describe('TUI session controller — teardown owns its own machinery (#8021)', (
expect(write).toHaveBeenCalledWith('session-abcdef12', '/low-priority\r');
expect(write.mock.calls.filter(([, keys]) => keys === '/low-priority\r')).toHaveLength(1);
- await controller.handleExit({ exitCode: 1, killed: false });
+ expect(finalizeAgent).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1600);
+ expect(paste).toHaveBeenCalledWith('A sufficiently long prompt for this controller test', expect.objectContaining({
+ label: expect.stringContaining('Claude low-priority continuation'),
+ }));
+
+ await controller.handleData(banner);
+ expect(finalizeAgent).toHaveBeenCalledTimes(1);
});
it('does not send Claude low-priority without the provider opt-in', async () => {
- const { controller, write } = makeController({
+ const { controller, write, finalizeAgent } = makeController({
provider: { id: 'claude-code-tui', name: 'Claude Code TUI', type: 'tui', command: 'claude' },
tuiConfig: { ...TUI_CONFIG, command: 'claude', spawnCommand: '/usr/local/bin/claude', promptDelayMs: 250 },
prompt: 'A sufficiently long prompt for this controller test',
@@ -220,6 +227,6 @@ describe('TUI session controller — teardown owns its own machinery (#8021)', (
await controller.handleData("\n⏺ You've hit your session limit · resets 6:00 PM");
expect(write).not.toHaveBeenCalledWith('session-abcdef12', '/low-priority\r');
- await controller.handleExit({ exitCode: 1, killed: false });
+ expect(finalizeAgent).toHaveBeenCalledTimes(1);
});
});
diff --git a/server/services/tuiPromptRunner.js b/server/services/tuiPromptRunner.js
index 5ccd5058da..c6717936fd 100644
--- a/server/services/tuiPromptRunner.js
+++ b/server/services/tuiPromptRunner.js
@@ -68,6 +68,7 @@ import {
OUTPUT_BUFFER_HEADROOM,
RAW_BUFFER_CAP,
RAW_BUFFER_HEADROOM,
+ CLAUDE_LOW_PRIORITY_RESUBMIT_DELAY_MS,
buildTuiInvocation,
createInputReadyTracker,
detectMissingTuiBinary,
@@ -393,6 +394,7 @@ ${prompt}`;
&& provider.lowPriorityOnUsageLimit === true
&& isClaudeCommand(command);
let lowPriorityCommandAttempted = false;
+ let lowPriorityPromptResubmitted = false;
// One-shot-only: a terminal model-id rejection (Bedrock 400 / Anthropic 404)
// leaves the TUI idle at an unanswered prompt, so without this the run idles to
// a false success and the error screen is scraped as the "response". Scoped here
@@ -450,6 +452,7 @@ ${prompt}`;
let idleWatchTimer = null;
let responseFileWatchTimer = null;
let hardTimeoutTimer = null;
+ let claudeLowPriorityResubmitTimer = null;
// Holds the wait-it-out window for a provider signal carrying a `graceMs`
// (agy's account-eligibility banner). Unlike the long-running agent path this
// needs its OWN timer: `idleWatchTimer` is created lazily on the first
@@ -476,6 +479,7 @@ ${prompt}`;
if (idleWatchTimer) { clearInterval(idleWatchTimer); idleWatchTimer = null; }
if (responseFileWatchTimer) { clearInterval(responseFileWatchTimer); responseFileWatchTimer = null; }
if (hardTimeoutTimer) { clearTimeout(hardTimeoutTimer); hardTimeoutTimer = null; }
+ if (claudeLowPriorityResubmitTimer) { clearTimeout(claudeLowPriorityResubmitTimer); claudeLowPriorityResubmitTimer = null; }
stopSelfClearingTimers();
};
@@ -643,21 +647,55 @@ ${prompt}`;
}
const sessionLimit = isClaudeCommand(command) && promptSubmittedAt
- && (!mayUseClaudeLowPriority || !lowPriorityCommandAttempted)
? detectClaudeSessionLimitBanner(stripped)
: null;
- let sentLowPriorityCommand = false;
- if (sessionLimit && mayUseClaudeLowPriority && !lowPriorityCommandAttempted) {
- lowPriorityCommandAttempted = true;
- try {
- ptyProcess.write(`/low-priority${SUBMIT_KEY}`);
- sentLowPriorityCommand = true;
- console.log(`⏳ TUI run ${runId} reached Claude's session limit; sent /low-priority from the provider opt-in`);
- } catch (err) {
- sessionLimit.message = `Claude Code session limit reached and /low-priority could not be sent: ${err?.message || err}`;
+ let waitingForLowPriorityResubmit = false;
+ if (sessionLimit && mayUseClaudeLowPriority) {
+ if (lowPriorityCommandAttempted && !lowPriorityPromptResubmitted) {
+ // Repaints of the initial rejection can arrive while Claude
+ // processes the mode command. Re-submit below, then treat a fresh
+ // limit banner as a failed continuation.
+ waitingForLowPriorityResubmit = true;
+ } else if (!lowPriorityCommandAttempted) {
+ lowPriorityCommandAttempted = true;
+ try {
+ ptyProcess.write(`/low-priority${SUBMIT_KEY}`);
+ waitingForLowPriorityResubmit = true;
+ console.log(`⏳ TUI run ${runId} reached Claude's session limit; sent /low-priority from the provider opt-in`);
+ claudeLowPriorityResubmitTimer = setTimeout(() => {
+ claudeLowPriorityResubmitTimer = null;
+ if (finalized) return;
+ promptSubmittedAt = Date.now();
+ let resubmitted = false;
+ try {
+ if (submitEnterTimer) clearInterval(submitEnterTimer);
+ submitEnterTimer = null;
+ submitEnterTimer = pasteToSession(runId, wrappedPrompt, {
+ label: `[tuiRun ${runId}] Claude low-priority continuation`,
+ }) || null;
+ resubmitted = !!submitEnterTimer;
+ } catch (err) {
+ sessionLimit.message = `Claude Code low-priority mode was enabled, but the task could not be re-submitted: ${err?.message || err}`;
+ }
+ if (resubmitted) {
+ lowPriorityPromptResubmitted = true;
+ console.log(`🔁 TUI run ${runId} re-submitted its task after enabling Claude low-priority mode`);
+ return;
+ }
+ finishWithFallbackSignal({
+ ...sessionLimit,
+ message: sessionLimit.message
+ || 'Claude Code low-priority mode was enabled, but the task could not be re-submitted',
+ }).catch((err) => {
+ console.error(`❌ TUI run ${runId} low-priority re-submit fallback failed: ${err?.message || err}`);
+ });
+ }, CLAUDE_LOW_PRIORITY_RESUBMIT_DELAY_MS);
+ } catch (err) {
+ sessionLimit.message = `Claude Code session limit reached and /low-priority could not be sent: ${err?.message || err}`;
+ }
}
}
- const fallbackSignal = sentLowPriorityCommand ? null : (sessionLimit || detectImmediateFallbackSignal(stripped))
+ const fallbackSignal = waitingForLowPriorityResubmit ? null : (sessionLimit || detectImmediateFallbackSignal(stripped))
|| detectTerminalModelError(stripped)
|| detectTerminalRequestTimeout(stripped);
// Branch on the SIGNAL's own grace window, never on gate state: the
@@ -723,6 +761,11 @@ ${prompt}`;
// twice over: the gate closes on the first sign of generation, and its
// own timer resolves the deadline regardless.
if (selfClearingGate.armed) return;
+ // A low-priority continuation still owes a complete response file or
+ // process exit. Do not scrape an idle limit/command screen as success,
+ // either while the mode command is being processed or after the task
+ // has been re-submitted.
+ if (lowPriorityCommandAttempted) return;
const idle = Date.now() - lastOutputAt;
if (idle >= idleThresholdMs) {
if (requiresResponseFileForIdleCompletion) return;
diff --git a/server/services/tuiPromptRunner.test.js b/server/services/tuiPromptRunner.test.js
index ea6191aed3..055306dd3d 100644
--- a/server/services/tuiPromptRunner.test.js
+++ b/server/services/tuiPromptRunner.test.js
@@ -1231,8 +1231,23 @@ describe('executeTuiRun', () => {
expect(pty.kill).not.toHaveBeenCalled();
expect(runnerMocks.finalizeRunRecord).not.toHaveBeenCalled();
- pty.emitExit({ exitCode: 1, signal: 0 });
+ const taskPastes = () => pty.write.mock.calls.filter(([keys]) =>
+ String(keys).startsWith('\x1b[200~') && String(keys).includes('complete this task')).length;
+ expect(taskPastes()).toBe(1);
+ await vi.advanceTimersByTimeAsync(1600);
+ expect(taskPastes()).toBe(2);
+ await vi.advanceTimersByTimeAsync(9000);
+ expect(runnerMocks.finalizeRunRecord, 'an idle mode-command screen is not a completed response').not.toHaveBeenCalled();
+
+ pty.emitData("\n⏺ You've hit your session limit · resets 6:00 PM");
+ await flushAsync();
await promise;
+ expect(pty.kill).toHaveBeenCalled();
+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({
+ runId: 'run-low-priority',
+ success: false,
+ extras: expect.objectContaining({ completionReason: 'fallback-signal' }),
+ }));
});
it('falls back on Claude session-limit chrome when low-priority is not enabled', async () => {