Skip to content
Closed
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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ Pi Durable 1.4.0 stores Bot tasks. Native Harness processes own model loops. Per
- `internal/memory` owns background review. The runtime counts answered turns with `TurnCompleted` and runs a due review with `Review` as the Bot's only task: a separate native session, memory tools only, at most 12 calls and 120 seconds. A review task whose prompt was sent is never sent again.
- `internal/delivery` owns what a product tool shows in chat: `Deliver` appends one tool-result message per call (notice or files), hidden during conditional routine runs. `attach_file` snapshots a workspace file from the Bot's work computer into the Files root in the TypeScript artifact layout. It refuses a path through a symbolic link, a file with more than one hard link, and a path whose `computer.FileInfo` reports no link count; a Target fills `Symlink` and `Links` without following links. Updates and answers stay native assistant messages; do not add a message-sending tool.
- `internal/agent` owns Bots, the chat projection, the chat runtime, and Bot files, as `packages/agent` does. `Runtime.Submit` admits chat input as a submission and a task in one commit; a per-Bot worker runs the tasks in order, each in an `internal/engine` session that closes when the task ends, and `Stop` aborts the session and settles the turn without waiting for it. It reads and writes the pi-durable and Persona documents (`persona.bots`, `pi.agent`, `pi.live`, `persona.engine`) by kind and scope through `Harness.Commit`, and keeps files in the TypeScript `<database>.files` layout under `persona-go.sqlite.files` until the importer copies the TypeScript history. `persona serve` without a hosting config still runs behind the hosted origin guard, as the TypeScript service always does. `internal/server.RegisterAgent` serves its procedures, and chat input only when given a Runtime (`persona serve -pi-extension`); `internal/server.RegisterEngines` serves the remaining models and engines procedures, `persona serve` lists models from `agent.LocalModels` (the local servers `internal/localmodels` detects) until a cloud provider catalog is ported, with a native runtime `engines.get`, `engines.inspect`, `engines.configure`, and `engines.select` serve Pi on the service computer (a ready inspection is saved in `persona.native-models`, so `engines.get` keeps a Bot's catalog across restarts), and the other engine runtime procedures answer `NOT_IMPLEMENTED` for an existing Bot until native engine connections and controls are composed; `internal/server/contract_test.go` requires every fixture of a registered procedure to match, except the listed skips.
- The `internal/agent` runtime opens one `internal/mcpserver` gateway per native task and passes its URL as `PERSONA_PI_MCP_URL`. `internal/engine/pi` refuses a session without it, because `pi-tools.mjs` installs its approval hook only after reading that manifest. Pi approval requests that cannot be answered yet are cancelled.
- The `internal/agent` runtime opens one `internal/mcpserver` gateway per native task and passes its URL as `PERSONA_PI_MCP_URL`. `internal/engine/pi` refuses a session without it, because `pi-tools.mjs` installs its approval hook only after reading that manifest. The runtime asks Pi's approval requests through `internal/approval` and shows pending ones as chat approval cards; a request it cannot ask is cancelled. Native input carries attachments and the composer's skills and context, as `apps/api/src/materials.ts` prepares them, and Pi runs in the Bot's work computer workspace, where uploads land.
- `internal/routines` owns the `persona.routines` document and the `routine_*` tools. Route routine changes through its Service. It sets `enabled` and `nextAt` and leaves `taskId` unset; the routine runner starts tasks for enabled routines and sets `Service.RunNow` for `run_now`, which starts one task per request ID.
- `internal/server.RegisterWork` serves the work panel over `internal/memory`, `internal/routines`, and `internal/skills`; user saves go through each Service with source `user`, as `packages/agent/src/work` does. `work.prompt` needs a native runtime and `work.routines.test` needs `Routines.RunNow`. `work.skills.save`, `preview`, and `restore` stay unregistered until SKILL.md front matter is parsed like the TypeScript YAML failsafe schema.
- `internal/mcp` owns managed MCP connections: the `persona.mcp-connections` document, Bot grants, and secrets in the hosting credential store under `persona-mcp:<id>:<uuid>`, as `packages/agent/src/mcp/connections.ts`. `internal/server.RegisterMCP` serves them. Checks and sign-in run through `Service.Runner`, which `computers.Catalog.MCPRunner` supplies as a fresh worker on the connection's computer, and native connections through `Service.Catalog`, which stays unset until the worker serves native MCP reads. `persona serve` passes `<public URL>/mcp/oauth/callback` to `mcp.login` and completes it through `Config.MCP`.
Expand Down
40 changes: 33 additions & 7 deletions apps/api/test/fixtures/go-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,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 @@ -140,21 +141,28 @@ async function complete(
// Pi runs tools itself, so a gated tool holds the request that reports its result.
const afterTool =
(body.messages as { role: string }[] | undefined)?.at(-1)?.role === "tool";
const waiting = afterTool && toolGate ? toolGate : gate;
const next = scripted.shift();
// Like web-server.ts's faux answer factory, gate holds only the unscripted answer.
const waiting = afterTool && toolGate ? toolGate : next ? undefined : gate;
if (waiting === toolGate) toolGate = undefined;
else gate = undefined;
else if (waiting) gate = undefined;
if (waiting) {
aborted.signal.addEventListener("abort", () => waiting.resolve(), {
once: true,
});
await waiting.promise;
}
const reply = scripted.shift() ?? {
const reply = next ?? {
text: `已收到:${lastUserText(body as never)}。这是一条用于验证流式显示和会话恢复的完整回复。(${model})`,
};
if (reply.stopReason === "error") {
response.writeHead(500, { "Content-Type": "application/json" });
response.end(JSON.stringify({ error: { message: reply.errorMessage } }));
// Pi retries a 500; a faux error without a message is not retried.
response.writeHead(reply.errorMessage ? 500 : 400, {
"Content-Type": "application/json",
});
response.end(
JSON.stringify({ error: { message: reply.errorMessage ?? noMessage } }),
);
return;
}
response.writeHead(200, { "Content-Type": "text/event-stream" });
Expand All @@ -174,6 +182,17 @@ async function complete(
}
}
const calls = reply.toolCalls ?? [];
// Pi declares product tools from the Persona MCP server under mcp__persona__,
// while web-server.ts registers them by their own names.
const declared = new Set(
(body.tools as { function?: { name?: string } }[] | undefined)?.map(
(tool) => tool.function?.name,
),
);
const toolName = (name: string) =>
!declared.has(name) && declared.has(`mcp__persona__${name}`)
? `mcp__persona__${name}`
: name;
for (const [index, call] of calls.entries())
chunk(response, model, {
tool_calls: [
Expand All @@ -182,7 +201,7 @@ async function complete(
id: call.id,
type: "function",
function: {
name: call.name,
name: toolName(call.name),
arguments: JSON.stringify(call.arguments),
},
},
Expand Down Expand Up @@ -258,7 +277,13 @@ 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",
extensions: [
fileURLToPath(new URL("./pi-faux-failure.mjs", import.meta.url)),
],
}),
);
await writeFile(
join(agentDir, "models.json"),
Expand Down Expand Up @@ -303,6 +328,7 @@ const options = {
env: {
...process.env,
PI_CODING_AGENT_DIR: agentDir,
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
23 changes: 2 additions & 21 deletions apps/web/test/go-gaps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,8 @@ 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",
],
"fixture tool: web-server.ts scripts a gated, file-publishing test tool; Go serve has no counterpart and the fixture scripts Pi's ls":
[
"Bot identity stays consistent and image previews work in drafts and history",
"attachment retry keeps its request and draft after a lost receipt",
// 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",
"composer menu adds task materials, keeps drafts, and fits both themes",
"delivered images form a gallery with viewer downloads and keyboard navigation",
"file drafts, real tools, and published downloads survive Bot switches and restart",
"image thumbnails scroll horizontally and keep the selected image in view",
"message media leads captions and bubble tails follow both themes",
"published files wait for the complete reply",
"typing follows the Bot and failures retain their error message",
],
"chat window: Go reads a fixed 50-entry page; pi-durable's view window grows to 100 entries and pages older ones":
[
"chat reads older pages and retains them through live updates",
"large histories render a bounded window and retain the earlier reading anchor",
"panel transitions preserve the transcript and draft through rapid toggles and reduced motion",
],
"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"],
"routine tools: Pi's scripted routine_create call shows no routine approval card in chat":
["chat routine changes require confirmation and link runs to Work"],
"native questions: Pi's ask_user is not stored as a shared question card": [
Expand Down
53 changes: 50 additions & 3 deletions internal/agent/chatview.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ import (
)

const (
windowSize = 50
pageEntries = 500
pageMessages = 200
windowSize = 50
pageEntries = 500
pageMessages = 200
// enginePage is the page the get procedure and chat updates read for a
// native runtime.
enginePage = 200
maxSafeInteger = 1<<53 - 1
)

Expand Down Expand Up @@ -177,6 +180,50 @@ func (h *Harness) ReadChat(ctx context.Context, id int64, before string) (ChatVi
return chat, nil
}

// ReadEnginePage returns up to limit messages before the cursor
// "entry:index", read from the newest limit entries, as view in
// runtime/index.ts reads a page for a native runtime.
func (h *Harness) ReadEnginePage(ctx context.Context, id int64, before string, limit int) (ChatView, error) {
view, err := h.conversationDocs(ctx, id)
if err != nil {
return ChatView{}, err
}
entry, index := splitCursor(before)
entries, more, err := h.newest(ctx, id, store.EntryID(entry), limit)
if err != nil {
return ChatView{}, err
}
view.entries = entries
chat := projectChat(view)
var kept []any
for _, message := range chat.Messages {
cursor := messageCursor(message)
if entry != 0 && cursor != "" {
e, i := splitCursor(cursor)
if e > entry || (e == entry && i >= index) {
continue
}
}
kept = append(kept, message)
}
all := len(kept)
if all > limit {
kept = kept[all-limit:]
}
chat.Messages = append([]any{}, kept...)
if more || all > limit {
cursor := ""
if len(chat.Messages) > 0 {
cursor = messageCursor(chat.Messages[0])
}
if cursor == "" && len(entries) > 0 {
cursor = fmt.Sprintf("%d:0", entries[0].ID)
}
chat.Before = &cursor
}
return chat, nil
}

// ReadHistory projects the whole chat, as chatView(readConversationHistory()).
func (h *Harness) ReadHistory(ctx context.Context, id int64) (ChatView, error) {
view, err := h.conversationDocs(ctx, id)
Expand Down
1 change: 1 addition & 0 deletions internal/agent/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ type Draft struct {
ParentID string `json:"parentId,omitempty"`
Activity json.RawMessage `json:"activity,omitempty"`
Attachments json.RawMessage `json:"attachments,omitempty"`
Materials json.RawMessage `json:"materials,omitempty"`
}

func initialEngine() EngineState {
Expand Down
Loading
Loading