fix: interrupt unanswered questions on restart so Resume asks again (#2021)

This commit is contained in:
Tong Chen 2026-10-07 17:18:01 +08:00 • committed by GitHub
parent 537e96f64f
commit faac00a7dc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 401 additions and 85 deletions

View file

@ -57,6 +57,7 @@ from app.run_journal import (
IdempotencyConflictError,
InvalidRunTransitionError,
OptimisticConcurrencyError,
ProjectExecutionLeaseConflictError,
RunAttemptRecord,
RunEventDraft,
RunNotFoundError,
@ -1918,6 +1919,19 @@ async def start_chat_stream(data: Chat, request: Request):
request_id=request_id,
)
try:
if isinstance(journal, SQLiteRunJournal):
# Attempt admission refuses a Run while another one holds the
# Project execution lease, but only after preparation has
# persisted it. Refuse first, so the rejection leaves no
# pending Run behind.
owner = await asyncio.to_thread(
journal.get_active_project_run, data.project_id
)
if owner is not None and owner.run_id != run_id:
raise ProjectExecutionLeaseConflictError(
project_id=data.project_id,
owner_run_id=owner.run_id,
)
prepared = await _prepare_chat_run(
data,
request,
@ -1964,6 +1978,18 @@ async def post(data: Chat, request: Request):
) from exc
except (ModelCapabilityConfigError, UnsupportedThinkingEffortError) as exc:
raise _model_capability_http_error(exc) from exc
except ProjectExecutionLeaseConflictError as exc:
raise HTTPException(
status_code=409,
detail={
"code": "project_run_active",
"message": (
"Another Run in this Session must finish or be stopped "
"before a new one starts."
),
"run_id": exc.owner_run_id,
},
) from exc
return StreamingResponse(
stream,
media_type="text/event-stream",

View file

@ -91,6 +91,7 @@ from app.run_journal.store import (
InvalidRunTransitionError,
OptimisticConcurrencyError,
OutboxLeaseLostError,
ProjectExecutionLeaseConflictError,
RunJournalError,
RunNotFoundError,
SQLiteRunJournal,
@ -146,6 +147,7 @@ __all__ = [
"InvalidRunTransitionError",
"OptimisticConcurrencyError",
"OutboxLeaseLostError",
"ProjectExecutionLeaseConflictError",
"RunEventDraft",
"RunEventSyncBatch",
"RunEventSyncOutboxRecord",

View file

@ -2586,6 +2586,17 @@ class InvalidRunTransitionError(RunJournalError):
pass
class ProjectExecutionLeaseConflictError(InvalidRunTransitionError):
"""Another Run already holds the Project's execution lease."""
def __init__(self, *, project_id: str, owner_run_id: str) -> None:
self.project_id = project_id
self.owner_run_id = owner_run_id
super().__init__(
f"project {project_id!r} already executes Run {owner_run_id!r}"
)
class UnsafeResumeError(RunJournalError):
def __init__(self, tool_call_ids: list[str]) -> None:
self.tool_call_ids = tuple(tool_call_ids)
@ -13697,9 +13708,9 @@ class SQLiteRunJournal:
).fetchone()
if project_lease is not None:
if project_lease["run_id"] != run_id:
raise InvalidRunTransitionError(
f"project {run['project_id']!r} already executes Run "
f"{project_lease['run_id']!r}"
raise ProjectExecutionLeaseConflictError(
project_id=run["project_id"],
owner_run_id=project_lease["run_id"],
)
# A same-Run lease without an active Attempt is stale. This
# can only be left by a pre-v21 crash or manual DB repair;
@ -13861,9 +13872,8 @@ class SQLiteRunJournal:
(run["project_id"],),
).fetchone()
owner_id = owner["run_id"] if owner is not None else "unknown"
raise InvalidRunTransitionError(
f"project {run['project_id']!r} already executes Run "
f"{owner_id!r}"
raise ProjectExecutionLeaseConflictError(
project_id=run["project_id"], owner_run_id=owner_id
) from exc
environment_payload = (
{
@ -15094,16 +15104,25 @@ class SQLiteRunJournal:
run_id: str,
timestamp: float,
reason: str,
agent_requested_only: bool = False,
) -> int:
"""Close HumanInteractions that cannot outlive a terminal Run."""
"""Close HumanInteractions that cannot outlive a terminal Run.
``agent_requested_only`` limits this to requests an Agent awaits in
the Brain process; system requests such as merge conflicts stay open.
"""
interactions = connection.execute(
"""
SELECT * FROM human_interactions
WHERE run_id = ? AND status IN ('requested', 'presented')
AND (
? = 0 OR requested_by = 'agent'
OR requested_by LIKE 'agent:%'
)
ORDER BY created_at, interaction_id
""",
(run_id,),
(run_id, agent_requested_only),
).fetchall()
cancelled = 0
for interaction in interactions:
@ -17431,6 +17450,17 @@ class SQLiteRunJournal:
""",
(run["run_id"],),
).fetchall()
# An Agent awaits its question inside the process, so
# a restart abandons it like an approval: the Run is
# interrupted and Resume asks again. System requests,
# such as merge conflicts, keep the Run waiting.
self._cancel_open_human_interactions_in_transaction(
connection,
run_id=run["run_id"],
timestamp=timestamp,
reason="brain_restart",
agent_requested_only=True,
)
pending_interaction = connection.execute(
"""
SELECT 1

View file

@ -956,6 +956,100 @@ class TestChatController:
git_coordinator.admit_run.assert_not_called()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"lease_taken", ["before_admission", "during_preparation"]
)
async def test_project_lease_conflict_is_a_typed_409_without_orphan_run(
self,
sample_chat_data,
mock_request,
mock_task_lock,
tmp_path,
lease_taken,
):
chat_data = Chat(
**sample_chat_data,
run_id="run-rejected",
session_mode="single-agent",
)
resolver = MagicMock()
resolver.freeze_task_directories.return_value = SimpleNamespace(
working_directory=tmp_path,
task_output_root=tmp_path / "output",
base_snapshot_id=None,
snapshot=MagicMock(),
binding_source="test",
workdir_mode=None,
)
resolver.space_root.return_value = tmp_path
with SQLiteRunJournal(tmp_path / "journal.sqlite3") as journal:
journal.ensure_run(
run_id="run-blocker", project_id=chat_data.project_id
)
def take_project_lease(*_args):
if not journal.list_run_attempts("run-blocker"):
journal.create_run_attempt(
"run-blocker",
request_id="initial:run-blocker",
reason="initial_execution",
activate=True,
)
if lease_taken == "before_admission":
take_project_lease()
with (
patch(
"app.controller.chat_controller.get_default_run_journal",
return_value=journal,
),
patch(
"app.controller.chat_controller.get_default_run_coordinator",
return_value=RunCoordinator(),
),
patch(
"app.controller.chat_controller.get_or_create_task_lock",
return_value=mock_task_lock,
),
patch(
"app.controller.chat_controller.get_workspace_resolver",
return_value=resolver,
),
patch(
"app.controller.chat_controller."
"get_default_workspace_git_coordinator",
return_value=MagicMock(),
),
patch(
"app.controller.chat_controller."
"_prepare_browser_for_request_with_timeout",
new=AsyncMock(return_value=True),
),
patch(
"app.controller.chat_controller._assemble_runtime_environment",
side_effect=take_project_lease,
),
patch(
"app.controller.chat_controller._camel_log_dir",
return_value=tmp_path / "camel-log",
),
patch("app.controller.chat_controller.set_current_task_id"),
patch("app.controller.chat_controller.load_dotenv"),
patch("app.controller.chat_controller.step_solve") as solve,
):
with pytest.raises(HTTPException) as error:
await post(chat_data, mock_request)
assert error.value.status_code == 409
assert error.value.detail["code"] == "project_run_active"
assert error.value.detail["run_id"] == "run-blocker"
solve.assert_not_called()
assert journal.list_run_attempts("run-rejected") == []
if lease_taken == "before_admission":
assert journal.get_run("run-rejected") is None
def test_bundle_runtime_rejects_legacy_workforce_session_mode(self):
with pytest.raises(EnvironmentSetupRequiredError) as error:
_require_supported_bundle_session_mode("workforce", object())

View file

@ -434,7 +434,82 @@ def test_approval_with_explicit_pending_child_step_blocks_that_child(tmp_path):
assert snapshots[child_step_id].status == "blocked"
def test_generic_interaction_blocks_resume_after_restart(tmp_path):
@pytest.mark.parametrize("requested_by", ["agent:worker", "agent"])
@pytest.mark.parametrize("kept_waiting_by_earlier_startup", [False, True])
def test_restart_interrupts_an_unanswered_agent_question_and_resume_asks_again(
tmp_path, requested_by, kept_waiting_by_earlier_startup
):
path = tmp_path / "journal.sqlite3"
question = dict(
run_id="run-1",
interaction_type="question",
request={"question": "Which file?", "agent": "worker"},
requested_by=requested_by,
)
with SQLiteRunJournal(path) as journal:
attempt = _running_attempt(journal)
journal.create_human_interaction(
interaction_id="question-1",
attempt_id=attempt.attempt_id,
now=3,
**question,
)
if kept_waiting_by_earlier_startup:
# Earlier versions detached only the Attempt and kept the Run waiting
# on its Project execution lease.
with sqlite3.connect(path) as connection:
connection.execute(
"""
UPDATE run_attempts
SET status = 'interrupted', ended_at = 3,
outcome = 'runtime.interrupted'
WHERE attempt_id = ?
""",
(attempt.attempt_id,),
)
connection.execute(
"UPDATE runs SET active_attempt_id = NULL WHERE run_id = 'run-1'"
)
with SQLiteRunJournal(path) as reopened:
result = reopened.reconcile_startup(now=4)
assert reopened.get_human_interaction("question-1").status == (
"cancelled"
)
decisions = reopened.list_human_interaction_decisions("question-1")
assert [decision.decision for decision in decisions] == [
{"decision": "cancelled", "reason": "brain_restart"}
]
run = reopened.get_run("run-1")
assert (run.status, run.terminal_reason) == (
"interrupted",
"brain_restart",
)
assert result.interrupted_run_ids == ("run-1",)
assert reopened.get_active_project_run("project-1") is None
resumed = reopened.create_run_attempt(
"run-1",
request_id="resume-1",
reason="explicit_resume",
activate=True,
now=5,
)
asked_again = reopened.create_human_interaction(
interaction_id="question-2",
attempt_id=resumed.attempt_id,
now=6,
**question,
)
assert asked_again.status == "requested"
assert reopened.get_run("run-1").status == "waiting_for_user"
@pytest.mark.parametrize("durable_request", ["merge_conflict", "approval"])
def test_restart_keeps_system_requests_and_approvals_waiting(
tmp_path, durable_request
):
path = tmp_path / "journal.sqlite3"
with SQLiteRunJournal(path) as journal:
attempt = _running_attempt(journal)
@ -443,20 +518,47 @@ def test_generic_interaction_blocks_resume_after_restart(tmp_path):
run_id="run-1",
attempt_id=attempt.attempt_id,
interaction_type="question",
request={"question": "Continue?"},
request={"question": "Which file?", "agent": "worker"},
requested_by="agent:worker",
now=3,
)
if durable_request == "merge_conflict":
journal.create_human_interaction(
interaction_id="durable-1",
run_id="run-1",
attempt_id=attempt.attempt_id,
interaction_type="merge_conflict",
request={"title": "Agent changes need conflict resolution"},
options=[{"id": "keep_run", "label": "Keep Run version"}],
requested_by="workspace_git",
now=4,
)
else:
journal.create_approval(
approval_id="durable-1",
run_id="run-1",
attempt_id=attempt.attempt_id,
prompt={"question": "Allow write?"},
now=4,
)
with SQLiteRunJournal(path) as reopened:
reopened.reconcile_startup(now=4)
with pytest.raises(
InvalidRunTransitionError, match="pending human interactions"
):
reopened.reconcile_startup(now=5)
assert reopened.get_human_interaction("question-1").status == (
"cancelled"
)
assert reopened.get_human_interaction("durable-1").status == (
"requested"
)
assert reopened.get_run("run-1").status == "waiting_for_user"
assert reopened.get_active_project_run("project-1").run_id == "run-1"
with pytest.raises(InvalidRunTransitionError, match="durable-1"):
reopened.create_run_attempt(
"run-1",
request_id="resume-1",
reason="explicit_resume",
now=5,
now=6,
)

View file

@ -12,6 +12,7 @@
// limitations under the License.
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
import { AgentStep } from '@/types/constants';
import { describe, expect, it } from 'vitest';
import { isTaskListRowHardFailure } from './taskLifecycleUi';
@ -46,4 +47,19 @@ describe('task lifecycle failure projection', () => {
})
).toBe(true);
});
it('identifies a localized error receipt by its step', () => {
expect(
isTaskListRowHardFailure({
messages: [
{
id: 'receipt',
role: 'agent',
content: '❌ **Fehler**: Die Aufgabe konnte nicht starten.',
step: AgentStep.ERROR,
},
],
})
).toBe(true);
});
});

View file

@ -118,7 +118,9 @@ export function getTaskListShelfTone(
export function isTaskListRowHardFailure(task: TaskLifecycleFields): boolean {
return getTaskMessages(task).some((m) => {
if (m.role !== 'agent') return false;
if (m.step === AgentStep.FAILED) return true;
// An error receipt keeps its step in every locale; the English prefix
// below covers receipts recorded without one.
if (m.step === AgentStep.FAILED || m.step === AgentStep.ERROR) return true;
// Message.content is a string by contract, but older caches and legacy SSE
// ingress could contain a structured HumanInteraction payload here. Keep
// derived navigation state total while those messages age out naturally.

View file

@ -4326,6 +4326,69 @@ const chatStore = (initial?: Partial<ChatStore>) =>
]);
let legacyEndRunId: string | null = null;
// Admission failed before the event stream existed. Unlike an execution
// error, no later END frame can clear the optimistic pending state, so
// close it here and surface the typed Brain reason instead of leaving
// the composer stuck on "Preparing".
const failAdmission = (err: any) => {
if (
err?.code === 'project_consumer_active' &&
createdTriggerBinding &&
!startOptions.resumeRequestId &&
triggerExecutionId &&
project_id
) {
forgetRejectedTriggerRun(triggerExecutionId, project_id, newTaskId);
}
finishStartupFailure();
const failureState = targetChatStore.getState();
const failureTask = failureState.tasks[newTaskId];
const userMessage =
typeof err?.userMessage === 'string' && err.userMessage.trim()
? err.userMessage.trim()
: typeof err?.message === 'string' && err.message.trim()
? err.message.trim()
: i18next.t('chat.task-admission-failed', {
defaultValue:
'The task could not be started. Please try again.',
});
const isContinuationClarification =
typeof err?.code === 'string' && err.code.startsWith('continuation_');
const content = isContinuationClarification
? i18next.t('chat.control-input-required-message', {
defaultValue: 'Input required: {{message}}',
message: userMessage,
})
: i18next.t('chat.error-message', {
defaultValue: '❌ **Error**: {{message}}',
message: userMessage,
});
const alreadyRendered = failureTask?.messages.some(
(message) => message.role === 'agent' && message.content === content
);
if (failureTask && !alreadyRendered) {
failureState.addMessages(newTaskId, {
id: generateUniqueId(),
role: 'agent',
content,
...(!isContinuationClarification
? {
step: AgentStep.ERROR,
errorReason: reportError(
err,
{
modelType: effectiveModelType,
modelId: resolvedCloudModelId,
executionId,
},
requestAccount
),
}
: {}),
});
}
};
const guardDelivery =
adoptingSpaceDefault || startOptions.resumeRequestId;
if (!guardDelivery) admissionRequested = true;
@ -7193,6 +7256,12 @@ const chatStore = (initial?: Partial<ChatStore>) =>
modelType: effectiveModelType,
modelId: resolvedCloudModelId,
});
// An awaited admission settles on this rejection and aborts the
// transport, which then never reaches onerror. Settle the new task
// here so it keeps its error receipt. A Resume keeps its
// interrupted task, whose controls ChatBox restores.
if (startOptions.awaitAdmission && !startOptions.resumeRequestId)
failAdmission(error);
rejectResumeStreamOpen?.(error);
throw error;
}
@ -7274,75 +7343,9 @@ const chatStore = (initial?: Partial<ChatStore>) =>
return;
}
if (!resumeStreamOpened) rejectResumeStreamOpen?.(err);
if (!resumeStreamOpened) {
if (
err?.code === 'project_consumer_active' &&
createdTriggerBinding &&
!startOptions.resumeRequestId &&
triggerExecutionId &&
project_id
) {
forgetRejectedTriggerRun(
triggerExecutionId,
project_id,
newTaskId
);
}
// Admission failed before the event stream existed. Unlike an
// execution error, no later END frame can clear the optimistic
// pending state, so close it here and surface the typed Brain
// reason instead of leaving the composer stuck on "Preparing".
finishStartupFailure();
const failureState = targetChatStore.getState();
const failureTask = failureState.tasks[newTaskId];
const userMessage =
typeof err?.userMessage === 'string' && err.userMessage.trim()
? err.userMessage.trim()
: typeof err?.message === 'string' && err.message.trim()
? err.message.trim()
: i18next.t('chat.task-admission-failed', {
defaultValue:
'The task could not be started. Please try again.',
});
const isContinuationClarification =
typeof err?.code === 'string' &&
err.code.startsWith('continuation_');
const content = isContinuationClarification
? i18next.t('chat.control-input-required-message', {
defaultValue: 'Input required: {{message}}',
message: userMessage,
})
: i18next.t('chat.error-message', {
defaultValue: '❌ **Error**: {{message}}',
message: userMessage,
});
const alreadyRendered = failureTask?.messages.some(
(message) =>
message.role === 'agent' && message.content === content
);
if (failureTask && !alreadyRendered) {
failureState.addMessages(newTaskId, {
id: generateUniqueId(),
role: 'agent',
content,
...(!isContinuationClarification
? {
step: AgentStep.ERROR,
errorReason: reportError(
err,
{
modelType: effectiveModelType,
modelId: resolvedCloudModelId,
executionId,
},
requestAccount
),
}
: {}),
});
}
rejectResumeStreamOpen?.(err);
failAdmission(err);
}
// A transport error does not establish a cancelled execution outcome.

View file

@ -13,6 +13,7 @@
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
import { runDomainEventHub, runProjectionStore } from '@/lib/runEvents';
import { getSessionNavLeadPresentation } from '@/lib/sessionNavLead';
import {
forgetRejectedTriggerRun,
trackTriggerExecutionRun,
@ -21,7 +22,7 @@ import { closeSSEConnectionsForTasks, useChatStore } from '@/store/chatStore';
import { useCloudModelStore } from '@/store/cloudModelStore';
import { setConnectionConfig } from '@/store/connectionStore';
import { useUsageNoticeStore } from '@/store/usageNoticeStore';
import { ChatTaskStatus } from '@/types/constants';
import { AgentStep, ChatTaskStatus } from '@/types/constants';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
auth: {} as any,
@ -558,6 +559,46 @@ describe('Fresh Space admission at actual HTTP delivery', () => {
expect(project.metadata.spaceModelDefaultPending).toBe(false);
});
it('keeps the error receipt instead of a completed empty task when admission is refused', async () => {
await useActualTransport();
// A Session after an interruption keeps its pinned model; only the Brain
// refuses the new task, so the awaited admission aborts the transport.
project.metadata = {
modelSelection: { modelType: 'cloud', cloud_model_type: 'global' },
};
vi.stubGlobal(
'fetch',
vi.fn(
async () =>
new Response(
JSON.stringify({
detail: {
code: 'project_run_active',
message: 'Another Run in this Session must finish first.',
run_id: 'interrupted-run',
},
}),
{ status: 409, headers: { 'content-type': 'application/json' } }
)
)
);
await expect(start()).rejects.toMatchObject({
code: 'project_run_active',
});
const task = chat.getState().tasks[request().run_id];
expect(task).toMatchObject({
isPending: false,
status: ChatTaskStatus.FINISHED,
});
expect(task.messages).toEqual([
expect.objectContaining({ role: 'user', content: 'fixture question' }),
expect.objectContaining({ role: 'agent', step: AgentStep.ERROR }),
]);
expect(getSessionNavLeadPresentation(task).kind).toBe('error');
});
it('retains an unknown-ACK receipt and refuses to blindly create another Run', async () => {
await useActualTransport();
const delivery = vi.fn(async () => {