Skip to content
Merged
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
15 changes: 13 additions & 2 deletions apps/api/test/fixtures/go-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down Expand Up @@ -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" });
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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.
Expand All @@ -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"],
Expand Down
47 changes: 47 additions & 0 deletions apps/api/test/fixtures/pi-faux-failure.mjs
Original file line number Diff line number Diff line change
@@ -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;
}
},
});
}
31 changes: 24 additions & 7 deletions apps/web/src/features/chat/image-gallery.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 && (
<p role="alert" className="alert">
{error}
Expand Down Expand Up @@ -98,13 +122,6 @@ export function ImageGallery({
<PanelDialog.Popup
className="image-viewer"
finalFocus={() => 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 && (
<>
Expand Down
14 changes: 12 additions & 2 deletions apps/web/src/features/chat/use-chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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();
Expand Down
11 changes: 8 additions & 3 deletions apps/web/test/chat.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ({
Expand Down Expand Up @@ -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 })
Expand Down
17 changes: 3 additions & 14 deletions apps/web/test/go-gaps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,11 @@ export const goGaps: Record<string, string[]> = {
"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",
Expand Down
7 changes: 6 additions & 1 deletion internal/engine/pi/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
23 changes: 20 additions & 3 deletions packages/agent/src/harness/pi-tools.mjs
Original file line number Diff line number Diff line change
@@ -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" });
Expand All @@ -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) {
Expand Down
Loading