diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index a338cc60c..f557e4392 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -294,6 +294,8 @@ jobs: env: CREATION_WEB_URL: http://127.0.0.1:5180 CREATION_API_URL: http://127.0.0.1:8020 + ASSISTANT_FINISH_FAILURE_SCREENSHOT_EN: ${{ runner.temp }}/assistant-finish-failure-en.png + ASSISTANT_FINISH_FAILURE_SCREENSHOT_ZH: ${{ runner.temp }}/assistant-finish-failure-zh.png run: | export PLAYWRIGHT_MODULE="$RUNNER_TEMP/opendirector-browser/node_modules/playwright-core/index.mjs" python tests/browser/creation_server.py --port 8020 --assistant-fixture >"$RUNNER_TEMP/assistant-creation-server.log" 2>&1 & @@ -311,7 +313,18 @@ jobs: curl --silent --fail "$CREATION_WEB_URL/" >/dev/null node tests/browser/bilingual_defaults.mjs node tests/browser/assistant_auxiliary_panels.mjs + node tests/browser/assistant_finish_failure.mjs node tests/browser/trace_original_export.mjs + - name: Upload finish-failure UI screenshots + if: always() && matrix.journey == 'assistant' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: assistant-finish-failure-screenshots-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/assistant-finish-failure-en.png + ${{ runner.temp }}/assistant-finish-failure-zh.png + retention-days: 14 + if-no-files-found: warn - name: Print isolated service logs on failure if: failure() run: | diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index e049f80c5..04eeec983 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -27,7 +27,7 @@ from opendirector.infrastructure.creation_projects import durable_json from opendirector.infrastructure.local_projects import child, read_json from opendirector.integrations.chat_completions import CHAT_MAX_TOKENS -from opendirector_api.localization import localized_error_for_language +from opendirector_api.localization import localized_error_for_language, wants_english_language logger = logging.getLogger(__name__) @@ -416,6 +416,7 @@ class Chain: task: asyncio.Task | None = None stopped: bool = False last: dict | None = None + unsaved: str | None = None # why the latest reply could not be saved def agent_routes(projects, generation, configs, provider=None, *, active=None) -> APIRouter: @@ -636,6 +637,7 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None steps = None run_session = plan.get('run_session') or chain.session timing: dict = {} + chain.unsaved = chain.last = None turn_started = time.monotonic() renewal: asyncio.Task | None = None @@ -739,20 +741,33 @@ async def renew_session() -> None: except Exception: logger.exception(f'agent.turn.unfinished project_id={project_id} turn_id={turn_id}') saved = None + # The reply was streamed but never saved: say so instead of ending + # as if nothing went wrong, keep any earlier run error beside it, + # and do not let the chain start a queued message behind it. + unsaved = ('The reply could not be saved. Check the backend log.' + if wants_english_language(plan.get('accept_language')) + else '回复未能保存,请检查后端日志。') + error = f'{error}\n{unsaved}' if error else unsaved + chain.unsaved = error + if status == 'complete': + status = 'interrupted' finally: if renewal is not None: renewal.cancel() with suppress(asyncio.CancelledError): await renewal + # Measurement and the lease are both best effort and independent: + # losing either may cost a file or a lock, never the turn's end. try: - # Measurement and the lease are both best effort: losing - # either may cost a file or a lock, never the turn's reply. await asyncio.to_thread(agent_timing.write, plan['directory'], turn_id, timing, round(time.monotonic() - turn_started, 3)) + except Exception: + logger.exception(f'agent.turn.timing.failed project_id={project_id} turn_id={turn_id}') + try: if plan.get('run_session'): await asyncio.to_thread(projects.local.release_agent_session, plan['run_session']) except Exception: - logger.exception(f'agent.turn.timing.failed project_id={project_id} turn_id={turn_id}') + logger.exception(f'agent.session.release.failed project_id={project_id} turn_id={turn_id}') chain.last = saved return saved, error, status @@ -786,7 +801,7 @@ async def run_chain(chain: Chain, plan: dict) -> None: plan['run_session'] = run_session saved = None except asyncio.CancelledError: - status, error = 'stopped', None + status, error = 'stopped', chain.unsaved raise finally: chain.events.put({'type': 'end', 'turnId': str(turn_id), 'nextTurnId': None, diff --git a/src/canvas/useAssistantChat.ts b/src/canvas/useAssistantChat.ts index 0f9eb127c..8f92fed7c 100644 --- a/src/canvas/useAssistantChat.ts +++ b/src/canvas/useAssistantChat.ts @@ -585,6 +585,19 @@ export function useAssistantChat( if (event.status !== "running") onEnd.current(); } else if (event.type === "end") { if (event.conversation) setValue(event.conversation); + else { + // The turn ended without a durable conversation snapshot. Keep + // the streamed text visible, but do not leave the reply streaming. + setValue((previous) => ({ + ...previous, + messages: previous.messages.map((message) => + message.id === assistantId && message.status === "streaming" + ? { ...message, status: "interrupted" } + : message, + ), + })); + } + setThinkingNow(false); if (event.error) setError(displayError(event.error)); } }, diff --git a/tests/assistantFinishFailure.test.ts b/tests/assistantFinishFailure.test.ts new file mode 100644 index 000000000..19a4141eb --- /dev/null +++ b/tests/assistantFinishFailure.test.ts @@ -0,0 +1,30 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { streamChat, type ChatEvent } from "../src/backend/chat.ts"; + +// #502: when the final write fails the server ends the stream with +// `{type: "end", conversation: null, error}`. The client must deliver that +// frame as the terminal event (not as "interrupted") with the partial text intact. +test("a failed finish ends the stream with its error and no conversation", async (t) => { + const error = "回复未能保存,请检查后端日志。"; + t.mock.method(globalThis, "fetch", async () => + new Response( + [ + { type: "delta", text: "已输出的部分回复" }, + { type: "end", turnId: "t", nextTurnId: null, conversation: null, error }, + ].map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), + { headers: { "Content-Type": "text/event-stream" } }, + ), + ); + const events: ChatEvent[] = []; + await streamChat( + "project", + { id: "t", runtime: "default", text: "x" } as never, + new AbortController().signal, + (event) => events.push(event), + ); + assert.deepEqual(events.map((event) => event.type), ["delta", "end"]); + const end = events[1] as Extract; + assert.equal(end.conversation, null); + assert.equal(end.error, error); +}); diff --git a/tests/browser/assistant_finish_failure.mjs b/tests/browser/assistant_finish_failure.mjs new file mode 100644 index 000000000..652af7554 --- /dev/null +++ b/tests/browser/assistant_finish_failure.mjs @@ -0,0 +1,162 @@ +/** Bilingual UI regression for a terminal finish-write failure. + * Uses the assistant fixture and a mocked SSE terminal response; no model calls. + */ +import assert from "node:assert/strict"; +import { launchBrowser } from "./engine.mjs"; + +const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; +const headers = { + "X-OpenDirector-Request": "1", + "X-OpenDirector-Session": crypto.randomUUID(), + "Content-Type": "application/json", +}; + +async function api(path, body) { + const response = await fetch(base + "/api" + path, { + headers, + ...(body ? { method: "POST", body: JSON.stringify(body) } : {}), + }); + assert.ok(response.ok, await response.clone().text()); + return response.json(); +} + +async function until(read, matches, label) { + const deadline = Date.now() + 15000; + while (true) { + const value = await read(); + if (matches(value)) return value; + assert.ok(Date.now() < deadline, label); + await new Promise((resolve) => setTimeout(resolve, 50)); + } +} + +const health = await api("/creation-test-health"); +assert.equal(health.isolated, true); +assert.equal(health.assistantFixture, true); + +const browser = await launchBrowser(); +try { + for (const locale of ["en-US", "zh-CN"]) { + const projectId = crypto.randomUUID(); + await api("/creation/projects/" + projectId + "/commands", { + type: "project.create", + projectId, + commandId: crypto.randomUUID(), + payload: { name: "Finish failure " + locale }, + }); + + const page = await browser.newPage({ + locale, + viewport: { width: 1440, height: 1000 }, + }); + page.setDefaultTimeout(15000); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + await page.addInitScript((id, selectedLocale) => { + localStorage.setItem("opendirector.modelSetup.v1", "dismissed"); + localStorage.setItem("opendirector.locale.v1", selectedLocale); + localStorage.setItem("opendirector.lastUnifiedFilesystemProject", id); + }, projectId, locale); + await page.route(/\/assistant\/runtimes(?:\?.*)?$/, (route) => + route.fulfill({ + json: [{ + id: "default", + label: "Default", + group: "default", + modelSource: "settings", + available: true, + status: "ready", + modelOverride: false, + supportsSkills: true, + }], + }), + ); + + await page.goto(base); + await page.locator(".cw-save-status .saved").waitFor({ state: "attached" }); + const panel = page.locator("#canvas-assistant"); + if (!(await panel.isVisible())) await page.locator(".cw-chat-button").click(); + const editor = panel.locator('[contenteditable="true"]').first(); + await editor.waitFor(); + const conversationPath = "/creation/projects/" + projectId + "/assistant"; + await until( + () => api(conversationPath), + (value) => !!value.modelSelections.agent, + "default agent model must be ready", + ); + const before = await api(conversationPath); + + const errorText = locale === "en-US" + ? "The reply could not be saved. Check the backend log." + : "回复未能保存,请检查后端日志。"; + const partialText = locale === "en-US" + ? "Partial reply before the failed save" + : "断盘前的部分回复"; + + await page.route(/\/assistant\/turns$/, async (route) => { + if (route.request().method() !== "POST") return route.continue(); + const { id, text: userText } = route.request().postDataJSON(); + const started = { + ...before, + messages: [ + ...before.messages, + { + id: crypto.randomUUID(), + role: "user", + text: userText, + status: "complete", + }, + { id, role: "assistant", text: "", status: "streaming" }, + ], + }; + return route.fulfill({ + status: 200, + contentType: "text/event-stream", + body: [ + { type: "start", conversation: started }, + { type: "delta", text: partialText }, + { + type: "end", + turnId: id, + nextTurnId: null, + conversation: null, + error: errorText, + }, + ].map((event) => "data: " + JSON.stringify(event) + "\n\n").join(""), + }); + }); + + await editor.fill(locale === "en-US" ? "Finish write failure" : "写盘失败"); + await panel.locator(".cw-assistant-send").click(); + await panel.getByRole("alert").filter({ hasText: errorText }).waitFor(); + await panel.getByText(partialText, { exact: true }).waitFor(); + + const failedReply = panel + .locator(".cw-assistant-message.is-assistant") + .filter({ hasText: partialText }); + assert.equal(await failedReply.count(), 1); + assert.equal( + await failedReply.locator('.cw-chat-progress[role="status"]').count(), + 0, + "a terminal end without a saved conversation must stop the message-level progress indicator", + ); + assert.equal( + await panel.locator(".cw-assistant-send").getAttribute("type"), + "submit", + "the global Stop control must be replaced by the normal Send control", + ); + + const screenshotPath = process.env[ + locale === "en-US" + ? "ASSISTANT_FINISH_FAILURE_SCREENSHOT_EN" + : "ASSISTANT_FINISH_FAILURE_SCREENSHOT_ZH" + ] ?? "/tmp/opendirector-finish-failure-" + locale + ".png"; + await page.screenshot({ path: screenshotPath }); + await page.unroute(/\/assistant\/turns$/); + assert.deepEqual(errors, []); + console.log("PASS finish failure terminal UI: " + locale); + await page.close(); + } +} finally { + await browser.close(); +} diff --git a/tests/browser/assistant_sessions.mjs b/tests/browser/assistant_sessions.mjs index 8e14f790a..077c105a2 100644 --- a/tests/browser/assistant_sessions.mjs +++ b/tests/browser/assistant_sessions.mjs @@ -395,6 +395,48 @@ try { await until(() => api(path), (value) => value.messages.length === edited.messages.length + 2 && value.messages.at(-1)?.status === "complete", "Complete the manually submitted turn"); + // #502: a turn whose final write failed ends with `end.error` and no + // conversation. The panel must leave the running state, show the error and + // keep the partial reply. Only the SSE response is faked here. + const unsaved = "回复未能保存,请检查后端日志。"; + const before = await api(path); + await page.route(/\/assistant\/turns$/, (route) => { + if (route.request().method() !== "POST") return route.continue(); + const { id, text } = route.request().postDataJSON(); + const started = { + ...before, + messages: [ + ...before.messages, + { id: crypto.randomUUID(), role: "user", text, status: "complete" }, + { id, role: "assistant", text: "", status: "streaming" }, + ], + }; + return route.fulfill({ + status: 200, + contentType: "text/event-stream", + body: [ + { type: "start", conversation: started }, + { type: "delta", text: "断盘前的部分回复" }, + { type: "end", turnId: id, nextTurnId: null, conversation: null, error: unsaved }, + ].map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), + }); + }); + await editor.fill("写盘失败"); + await send.click(); + await panel.getByRole("alert").filter({ hasText: unsaved }).waitFor(); + await panel.getByText("断盘前的部分回复", { exact: true }).waitFor(); + assert.equal(await panel.getByRole("button", { name: "停止回复", exact: true }).count(), 0); + await send.waitFor(); + const failedReply = panel + .locator(".cw-assistant-message.is-assistant") + .filter({ hasText: "断盘前的部分回复" }); + assert.equal( + await failedReply.locator('.cw-chat-progress[role="status"]').count(), + 0, + "a terminal end without a saved conversation must stop the reply progress indicator", + ); + await page.unroute(/\/assistant\/turns$/); + // History stays inside a narrow assistant, closes outside, and all header controls fit. await panel.evaluate((element) => element.style.setProperty("--assistant-width", "300px"), diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index d116b1321..f0f791540 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -70,6 +70,15 @@ ], "note": "Controls the model-stub gate; runs on its own fixture services." }, + { + "file": "assistant_finish_failure.mjs", + "fixture": true, + "previewSafe": true, + "lanes": [ + "gate" + ], + "note": "Bilingual finish-write failure: preserve partial text and error while clearing the message-level streaming indicator for a terminal end with no saved conversation." + }, { "file": "trace_original_export.mjs", "fixture": true, diff --git a/tests/test_assistant_conversations.py b/tests/test_assistant_conversations.py index 288c5c8ac..dc05e1c39 100644 --- a/tests/test_assistant_conversations.py +++ b/tests/test_assistant_conversations.py @@ -681,3 +681,255 @@ async def stream(self, run, gateway): with store.transaction() as db: assert db.execute('SELECT 1 FROM sessions WHERE id=?', (store.agent_session_key(run_session),)).fetchone() is None + + +# --- #502: a failed final write must still end the stream with an accurate result ------------------------------- + +class FinishProbe: + """Records what the producer queued and which writes the turn attempted.""" + + def __init__(self): + self.ends = [] # `end` frames the producer put into the event queue (not what a client received) + self.begins = 0 + self.finishes = 0 + self.runs = 0 + self.sessions = [] # agent sessions opened for a turn, in order + + +@pytest.fixture +def finish_probe(assistant, monkeypatch): + probe = FinishProbe() + put = agent.RunEvents.put + def recording_put(self, event): + if event['type'] == 'end': + probe.ends.append(event) + return put(self, event) + monkeypatch.setattr(agent.RunEvents, 'put', recording_put) + update = agent.Conversations.update + def counting_update(self, *args, **kwargs): + probe.begins += kwargs.get('begin') is not None + if kwargs.get('finish') is not None: + probe.finishes += 1 + if probe.finish_failure is not None: + raise probe.finish_failure + return update(self, *args, **kwargs) + probe.finish_failure = None + monkeypatch.setattr(agent.Conversations, 'update', counting_update) + start = LocalProjects.start_agent_session + def recording_start(self, db, project_id, path, session): + probe.sessions.append(session) + return start(self, db, project_id, path, session) + monkeypatch.setattr(LocalProjects, 'start_agent_session', recording_start) + return probe + + +def fail_finish_write(monkeypatch): + """OSError from the real durable write of the final reply; the begin write goes through.""" + durable = agent.durable_json + def fail(file, value, *args, **kwargs): + if value['messages'][-1]['status'] != 'streaming': + raise OSError(28, 'No space left on device') + return durable(file, value, *args, **kwargs) + monkeypatch.setattr(agent, 'durable_json', fail) + + +def run_turn(client, path, text='写入', timeout=10): + """POST a turn; a stream that never ends fails the test instead of hanging it.""" + with ThreadPoolExecutor() as pool: + return pool.submit(send, client, path, client.get(path).json()['conversationId'], text).result(timeout) + + +def streaming_stream(probe): + async def stream(self, run): + probe.runs += 1 + yield {'type': 'delta', 'text': '已输出的部分回复'} + return stream + + +def assert_one_failed_end(events, probe, *needles): + ends = [event for event in events if event['type'] == 'end'] + assert len(ends) == 1 and events[-1] is ends[0], [event['type'] for event in events] + assert len(probe.ends) == 1 + assert ends[0]['error'], ends[0] + for needle in needles: + assert needle in ends[0]['error'], ends[0]['error'] + saved = (ends[0]['conversation'] or {'messages': []})['messages'] + assert not saved or saved[-1]['status'] != 'complete', 'an unsaved reply must not be reported as complete' + assert probe.finishes == 1, 'the final write is not retried' + return ends[0] + + +def assert_project_released(client, path, tmp_path, probe): + """The turn's own write lease is gone and the project accepts no stale active turn.""" + assert 'activeTurnId' not in client.get(path).json() + store = LocalProjects(tmp_path) + with store.transaction() as db: + row = db.execute('SELECT 1 FROM sessions WHERE id=?', (store.agent_session_key(probe.sessions[0]),)).fetchone() + assert row is None, 'the turn left its project write lease behind' + + +def test_finish_success_ends_once_with_the_saved_reply(finish_probe, assistant, monkeypatch, tmp_path): + client, path, _ = assistant + monkeypatch.setattr(agent.AgentRuntimes, 'stream', streaming_stream(finish_probe)) + events = frames(run_turn(client, path)) + assert [event['type'] for event in events] == ['start', 'delta', 'end'] + assert events[-1]['error'] is None and events[-1]['conversation']['messages'][-1]['status'] == 'complete' + assert (finish_probe.begins, finish_probe.finishes, finish_probe.runs, len(finish_probe.ends)) == (1, 1, 1, 1) + assert_project_released(client, path, tmp_path, finish_probe) + + +def test_finish_oserror_ends_with_an_error_and_keeps_the_partial_text(finish_probe, assistant, monkeypatch, tmp_path): + client, path, _ = assistant + monkeypatch.setattr(agent.AgentRuntimes, 'stream', streaming_stream(finish_probe)) + fail_finish_write(monkeypatch) + events = frames(run_turn(client, path)) + assert_one_failed_end(events, finish_probe) + assert [event['text'] for event in events if event['type'] == 'delta'] == ['已输出的部分回复'] + assert finish_probe.runs == 1 + assert_project_released(client, path, tmp_path, finish_probe) + # The unsaved reply stays 'streaming' on disk; it was never reported as complete. + assert client.get(path).json()['messages'][-1]['status'] == 'streaming' + + +@pytest.mark.parametrize('failure', [ + agent.ProjectError('该项目正在其他窗口中打开,请先关闭后再试。', 409, code='project_open_elsewhere'), + __import__('sqlite3').OperationalError('database is locked'), + __import__('filelock').Timeout('catalog.lock'), +], ids=['project-authorization', 'sqlite-lock', 'catalog-lock']) +def test_finish_lock_or_authorization_failure_ends_with_an_error(finish_probe, assistant, monkeypatch, tmp_path, failure): + client, path, _ = assistant + monkeypatch.setattr(agent.AgentRuntimes, 'stream', streaming_stream(finish_probe)) + finish_probe.finish_failure = failure + events = frames(run_turn(client, path)) + assert_one_failed_end(events, finish_probe) + assert_project_released(client, path, tmp_path, finish_probe) + + +def test_runtime_error_followed_by_finish_failure_reports_both(finish_probe, assistant, monkeypatch, tmp_path, caplog): + client, path, _ = assistant + async def broken(self, run): + finish_probe.runs += 1 + yield {'type': 'delta', 'text': '部分'} + raise agent.ProjectError('模型额度已用尽', 429) + monkeypatch.setattr(agent.AgentRuntimes, 'stream', broken) + finish_probe.finish_failure = OSError(28, 'No space left on device') + events = frames(run_turn(client, path)) + assert_one_failed_end(events, finish_probe, '模型额度已用尽') + assert events[-1]['error'].count('\n') or len(events[-1]['error']) > len('模型额度已用尽'), 'the save failure is reported too' + logged = caplog.text + assert 'agent.turn.failed' in logged and 'agent.turn.unfinished' in logged and 'No space left' in logged + assert_project_released(client, path, tmp_path, finish_probe) + + +@pytest.mark.parametrize('broken', ['write', 'release']) +def test_ledger_or_lease_release_failure_does_not_block_the_end(finish_probe, assistant, monkeypatch, tmp_path, broken): + client, path, _ = assistant + async def stream(self, run): + finish_probe.runs += 1 + yield {'type': 'tool', 'id': 'a', 'name': 'x', 'status': 'complete', 'timing': {'spawn': 1.0}} + yield {'type': 'delta', 'text': '完成'} + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + released = [] + real_release = LocalProjects.release_agent_session + if broken == 'write': + def explode(*args, **kwargs): + raise RuntimeError('ledger exploded') # not an OSError, so timing.write does not absorb it + monkeypatch.setattr(agent.agent_timing, 'write', explode) + else: + def explode(self, session): + released.append(session) + raise RuntimeError('release exploded') + monkeypatch.setattr(LocalProjects, 'release_agent_session', explode) + events = frames(run_turn(client, path)) + assert events[-1]['type'] == 'end' and events[-1]['error'] is None + assert events[-1]['conversation']['messages'][-1]['status'] == 'complete' + assert len(finish_probe.ends) == 1 and finish_probe.finishes == 1 + assert 'activeTurnId' not in client.get(path).json() + if broken == 'write': + # The ledger failure must not cost the project its write lease. + monkeypatch.setattr(agent.agent_timing, 'write', lambda *a: None) + assert_project_released(client, path, tmp_path, finish_probe) + + +def test_disconnected_client_does_not_stop_the_run_and_a_later_stream_sees_the_failure( + finish_probe, assistant, monkeypatch, tmp_path): + client, path, _ = assistant + release = threading.Event() + async def stream(self, run): + finish_probe.runs += 1 + yield {'type': 'delta', 'text': '断线前'} + await asyncio.to_thread(release.wait, 10) + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + finish_probe.finish_failure = OSError(28, 'No space left on device') + turn_id = str(uuid4()) + disconnect_turn(client, path, turn_id) + assert client.get(path).json()['activeTurnId'] == turn_id + assert finish_probe.ends == [] and finish_probe.finishes == 0 # nothing was delivered to the closed stream + with ThreadPoolExecutor() as pool: + pending = pool.submit(client.get, path + f'/turns/{turn_id}/events') + time.sleep(0.2) + release.set() + events = frames(pending.result(timeout=10)) + # The producer queued exactly one end and a re-attached viewer received it; a viewer that + # never re-attaches would receive nothing (the queue is not a delivery guarantee). + assert_one_failed_end(events, finish_probe) + assert finish_probe.runs == 1 + assert_project_released(client, path, tmp_path, finish_probe) + + +def test_stop_during_the_run_then_a_failed_final_write_ends_once(finish_probe, assistant, monkeypatch, tmp_path): + client, path, _ = assistant + started = threading.Event() + async def stream(self, run): + finish_probe.runs += 1 + yield {'type': 'delta', 'text': '被停止前'} + started.set() + await asyncio.Event().wait() + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + finish_probe.finish_failure = OSError(28, 'No space left on device') + turn_id = str(uuid4()) + with ThreadPoolExecutor() as pool: + pending = pool.submit(client.post, path + '/turns', json={'id': turn_id, 'runtime': 'default', 'text': '停止'}) + assert started.wait(5) + assert client.post(path + f'/turns/{turn_id}/stop').status_code == 200 + events = frames(pending.result(timeout=10)) + assert_one_failed_end(events, finish_probe) + assert_project_released(client, path, tmp_path, finish_probe) + + +def test_failed_final_write_does_not_start_a_queued_message(finish_probe, assistant, monkeypatch, tmp_path): + client, path, _ = assistant + started, release = threading.Event(), threading.Event() + async def stream(self, run): + finish_probe.runs += 1 + yield {'type': 'delta', 'text': '第一轮'} + started.set() + await asyncio.to_thread(release.wait, 10) + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + finish_probe.finish_failure = OSError(28, 'No space left on device') + conversation = client.get(path).json()['conversationId'] + with ThreadPoolExecutor() as pool: + pending = pool.submit(send, client, path, conversation, '第一条') + assert started.wait(5) + queued = client.post(path + '/messages', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': conversation, 'text': '第二条'}) + assert queued.status_code == 202, queued.text + release.set() + events = frames(pending.result(timeout=10)) + assert finish_probe.runs == 1, 'the queued message must not run behind a reply that was not saved' + assert events[-1]['type'] == 'end' and events[-1]['error'] + assert_project_released(client, path, tmp_path, finish_probe) + + +def test_english_client_gets_both_the_run_error_and_the_unsaved_notice(finish_probe, assistant, monkeypatch, tmp_path): + client, path, _ = assistant + async def broken(self, run): + yield {'type': 'delta', 'text': 'partial'} + raise agent.ProjectError('Model quota exhausted', 429) + monkeypatch.setattr(agent.AgentRuntimes, 'stream', broken) + finish_probe.finish_failure = OSError(28, 'No space left on device') + response = client.post(path + '/turns', headers={'Accept-Language': 'en-US'}, json={ + 'id': str(uuid4()), 'runtime': 'default', 'text': 'go', 'conversationId': client.get(path).json()['conversationId']}) + end = assert_one_failed_end(frames(response), finish_probe) + run_error, unsaved = end['error'].split('\n') + assert unsaved == 'The reply could not be saved. Check the backend log.' and run_error != unsaved