Skip to content
Draft
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
13 changes: 13 additions & 0 deletions .github/workflows/release-checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 &
Expand All @@ -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: |
Expand Down
25 changes: 20 additions & 5 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down
13 changes: 13 additions & 0 deletions src/canvas/useAssistantChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
},
Expand Down
30 changes: 30 additions & 0 deletions tests/assistantFinishFailure.test.ts
Original file line number Diff line number Diff line change
@@ -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<ChatEvent, { type: "end" }>;
assert.equal(end.conversation, null);
assert.equal(end.error, error);
});
162 changes: 162 additions & 0 deletions tests/browser/assistant_finish_failure.mjs
Original file line number Diff line number Diff line change
@@ -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();
}
42 changes: 42 additions & 0 deletions tests/browser/assistant_sessions.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
9 changes: 9 additions & 0 deletions tests/browser/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading