diff --git a/apps/api/test/fixtures/go-server.ts b/apps/api/test/fixtures/go-server.ts index 9c0b888..5200316 100644 --- a/apps/api/test/fixtures/go-server.ts +++ b/apps/api/test/fixtures/go-server.ts @@ -25,6 +25,7 @@ const database = process.argv[2]; if (!database) throw new Error("Database required"); const root = fileURLToPath(new URL("../../../..", import.meta.url)); const directory = dirname(database); +const noMessage = "persona-fixture: failure without a message"; const models = [ { id: "faux-1", name: "测试模型一" }, { id: "faux-2", name: "测试模型二", reasoning: true }, @@ -160,7 +161,9 @@ async function complete( response.writeHead(reply.errorMessage ? 500 : 400, { "Content-Type": "application/json", }); - response.end(JSON.stringify({ error: { message: reply.errorMessage } })); + response.end( + JSON.stringify({ error: { message: reply.errorMessage ?? noMessage } }), + ); return; } response.writeHead(200, { "Content-Type": "text/event-stream" }); @@ -276,7 +279,10 @@ const agentDir = join(directory, "pi-agent"); await mkdir(agentDir, { recursive: true }); await writeFile( join(agentDir, "settings.json"), - JSON.stringify({ defaultProvider: "faux", defaultModel: "faux-1" }), + JSON.stringify({ + defaultProvider: "faux", + defaultModel: "faux-1", + }), ); await writeFile( join(agentDir, "models.json"), @@ -328,6 +334,10 @@ const args = [ join(root, "contracts", "api"), "-pi-extension", join(root, "packages", "agent", "src", "harness", "pi-tools.mjs"), + // serve always runs Pi with --no-extensions, so settings.json extensions + // never load; the faux failure stream must be an explicit extension. + "-pi-extension", + fileURLToPath(new URL("./pi-faux-failure.mjs", import.meta.url)), ]; const options = { // Outside the repository so persona.config.json does not select hosted mode. @@ -336,6 +346,7 @@ const options = { ...process.env, PI_CODING_AGENT_DIR: agentDir, ...(hosting ? { PERSONA_CONFIG: config } : {}), + PERSONA_FAUX_NO_MESSAGE: noMessage, PATH: `${bin}${process.platform === "win32" ? ";" : ":"}${process.env.PATH}`, }, stdio: ["pipe", "pipe", "pipe"], diff --git a/apps/api/test/fixtures/pi-faux-failure.mjs b/apps/api/test/fixtures/pi-faux-failure.mjs new file mode 100644 index 0000000..8f44afa --- /dev/null +++ b/apps/api/test/fixtures/pi-faux-failure.mjs @@ -0,0 +1,47 @@ +import { getApiProvider } from "@earendil-works/pi-ai/compat"; + +// web-server.ts scripts failures through pi-ai's faux provider, which streams +// an empty text block and then fails, with no error message when the script +// gives none. Pi's OpenAI-compatible provider always names the HTTP error, so +// go-server.ts marks such a failure with PERSONA_FAUX_NO_MESSAGE and this +// stream replays it the faux way. +const noMessage = process.env.PERSONA_FAUX_NO_MESSAGE; + +export default function (pi) { + pi.registerProvider("faux", { + api: "openai-completions", + async *streamSimple(model, context, options) { + const events = getApiProvider("openai-completions").streamSimple( + model, + context, + options, + ); + for await (const event of events) { + if ( + !noMessage || + event.type !== "error" || + !event.error.errorMessage?.includes(noMessage) + ) { + yield event; + continue; + } + const { errorMessage: _, ...failed } = event.error; + const partial = { + ...failed, + stopReason: "stop", + content: [{ type: "text", text: "" }], + }; + yield { type: "start", partial }; + yield { type: "text_start", contentIndex: 0, partial }; + yield { type: "text_delta", contentIndex: 0, delta: "", partial }; + yield { type: "text_end", contentIndex: 0, content: "", partial }; + yield { + type: "error", + reason: "error", + error: { ...partial, stopReason: "error" }, + }; + return; + } + }, + }); +} diff --git a/apps/web/src/features/chat/image-gallery.tsx b/apps/web/src/features/chat/image-gallery.tsx index 3234a62..6ed58fb 100644 --- a/apps/web/src/features/chat/image-gallery.tsx +++ b/apps/web/src/features/chat/image-gallery.tsx @@ -47,6 +47,30 @@ export function ImageGallery({ inline: "center", }); }, [selected]); + useEffect(() => { + if (!file || files.length < 2) return; + const navigate = (event: KeyboardEvent) => { + if ( + (event.key !== "ArrowLeft" && event.key !== "ArrowRight") || + !(event.target instanceof Element) || + event.target.closest(".image-viewer") === null + ) + return; + event.preventDefault(); + setSelected( + (current) => + ((current ?? 0) + + (event.key === "ArrowRight" ? 1 : -1) + + files.length) % + files.length, + ); + setRotation(0); + setZoomed(false); + }; + // React can drop synthetic key events while a View Transition commits. + window.addEventListener("keydown", navigate, true); + return () => window.removeEventListener("keydown", navigate, true); + }, [file, files.length]); const alert = error && (

{error} @@ -98,13 +122,6 @@ export function ImageGallery({ trigger.current} - onKeyDown={(event) => { - if (files.length < 2) return; - if (event.key === "ArrowLeft" || event.key === "ArrowRight") { - event.preventDefault(); - move(event.key === "ArrowRight" ? 1 : -1); - } - }} > {file && ( <> diff --git a/apps/web/src/features/chat/use-chat.ts b/apps/web/src/features/chat/use-chat.ts index 7533b76..020608e 100644 --- a/apps/web/src/features/chat/use-chat.ts +++ b/apps/web/src/features/chat/use-chat.ts @@ -14,6 +14,7 @@ import { useState, useSyncExternalStore, } from "react"; +import { flushSync } from "react-dom"; import { client } from "../../client.ts"; import { flushModelSettings } from "../models/model-state.ts"; import { chatCopy } from "./copy.ts"; @@ -127,8 +128,17 @@ export function useChat(botId: number, onModelRequired?: () => void) { if (!pending || controller.signal.aborted) return; const next = pending; pending = undefined; - setView(current.current ?? next); - setConnected(true); + const apply = () => { + setView(current.current ?? next); + setConnected(true); + }; + const transition = document.activeViewTransition; + if (!next.busy && store.snapshot().view?.busy && transition) { + // A finishing turn must re-enable the composer even if a transcript + // transition is still waiting to commit its DOM update. + transition.skipTransition(); + flushSync(apply); + } else apply(); }; const visible = () => { if (!document.hidden) flush(); diff --git a/apps/web/test/chat.spec.ts b/apps/web/test/chat.spec.ts index 0ce1da8..f649726 100644 --- a/apps/web/test/chat.spec.ts +++ b/apps/web/test/chat.spec.ts @@ -259,7 +259,12 @@ test.beforeEach(async () => { test.afterEach(async () => { if (worker.exitCode === null) await stop(); - await rm(directory, { recursive: true, force: true, maxRetries: 10 }); + await rm(directory, { + recursive: true, + force: true, + maxRetries: 10, + retryDelay: 100, + }); }); test("model selection updates immediately and restores a failed save", async ({ @@ -3087,14 +3092,14 @@ test("typing follows the Bot and failures retain their error message", async ({ await expect(failure).toContainText(/〔\d+:\d+〕/); await expect(failure.getByRole("alert")).toBeVisible(); await expect(failure.locator('svg[aria-hidden="true"]')).toHaveCount(1); - const errorText = await failure.innerText(); + const errorText = await failure.textContent(); const port = Number(new URL(url).port); await stop(); await start(port); await page.reload(); await expect(send).toBeVisible(); await expect(failure).toHaveCount(1); - await expect(failure).toHaveText(errorText); + await expect(failure).toHaveText(errorText ?? ""); await page .locator("#bot-details") .getByRole("button", { name: "关闭", exact: true }) diff --git a/apps/web/test/go-gaps.ts b/apps/web/test/go-gaps.ts index eb4355d..fc8cdc2 100644 --- a/apps/web/test/go-gaps.ts +++ b/apps/web/test/go-gaps.ts @@ -11,22 +11,11 @@ export const goGaps: Record = { "takeover card first click opens the browser and resumes after completion", "takeover controls the Agent browser and preserves its layout through fullscreen", ], - "parallel tools: Pi runs one response's tool calls concurrently, so attach_file can read report.md before the edit beside it lands; the TypeScript harness runs them in order": - [ - // The fixture holds the model request after ls, not the tool, so input - // steered while it waits joins a later turn instead of that request. - "chat keeps sending available while the Bot is working", - "file drafts, real tools, and published downloads survive Bot switches and restart", - ], - // The spec injects approval requests through the TypeScript worker's - // computer runtime; go-server.ts has no command that opens one in serve. - "shared approval cards: the Go fixture cannot open an approval request": [ - "shared question and approval cards persist answers and terminal states", - ], - "faux failure: Pi's OpenAI-compatible provider always gives a failed reply an error message, so the fixture cannot script web-server.ts's failure without one": - ["typing follows the Bot and failures retain their error message"], + "chat steering: the Go fixture holds the model request after ls, not the tool, so input steered while it waits joins a later turn": + ["chat keeps sending available while the Bot is working"], "native questions: Pi's ask_user is not stored as a shared question card": [ "native questions use the shared card and native replies persist", + "shared question and approval cards persist answers and terminal states", ], "native Work records: work.records does not yet project native turns": [ "Work follows a native turn, opens its record and preserves it after stop and reload", diff --git a/internal/engine/pi/engine.go b/internal/engine/pi/engine.go index 0b78a16..adde251 100644 --- a/internal/engine/pi/engine.go +++ b/internal/engine/pi/engine.go @@ -381,7 +381,12 @@ func writeTools(stateDir string, botID int64, o engine.SessionOptions) (string, if err != nil { return "", err } - data, err := json.Marshal(map[string]any{"url": o.Env["PERSONA_PI_MCP_URL"], "tools": o.Tools, "servers": []any{}}) + data, err := json.Marshal(map[string]any{ + "url": o.Env["PERSONA_PI_MCP_URL"], + "tools": o.Tools, + "servers": []any{}, + "sequentialFileTools": true, + }) if err != nil { return "", err } diff --git a/packages/agent/src/harness/pi-tools.mjs b/packages/agent/src/harness/pi-tools.mjs index 674cbca..92af3c7 100644 --- a/packages/agent/src/harness/pi-tools.mjs +++ b/packages/agent/src/harness/pi-tools.mjs @@ -1,9 +1,11 @@ import { readFileSync } from "node:fs"; import Type from "typebox"; export default function (pi) { - const { url, servers = [] } = JSON.parse( - readFileSync(process.env.PERSONA_PI_TOOLS, "utf8"), - ); + const { + url, + servers = [], + sequentialFileTools, + } = JSON.parse(readFileSync(process.env.PERSONA_PI_TOOLS, "utf8")); pi.registerMcpServer("persona", { url, exposure: "direct", timeout: 600 }); for (const server of servers) pi.registerMcpServer(server.name, { url: server.url, exposure: "direct" }); @@ -12,6 +14,21 @@ export default function (pi) { }); registerPiApprovals(pi); registerPiQuestions(pi); + if (sequentialFileTools) return registerSequentialFiles(pi); +} + +async function registerSequentialFiles(pi) { + const { createEditToolDefinition, createWriteToolDefinition } = await import( + "@earendil-works/pi-coding-agent" + ); + // Pi runs the whole batch in order when it contains a sequential tool. + // This lets attach_file snapshot the result of an earlier workspace edit. + for (const create of [createWriteToolDefinition, createEditToolDefinition]) { + pi.registerTool({ + ...create(process.cwd()), + executionMode: "sequential", + }); + } } export function registerPiApprovals(pi) {