From 910a668d2776c2802d45e94a08414490e010435f Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 18:45:18 +0000 Subject: [PATCH 01/14] Shrink the Go Playwright gaps: computer stubs, Pi model controls, fixture scripting Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- AGENTS.md | 2 +- apps/api/test/fixtures/go-server.ts | 334 ++++++++++++++++++++++------ apps/web/test/fixtures.ts | 46 ---- apps/web/test/go-gaps.ts | 82 +++---- internal/agent/engineconfig.go | 112 ++++++++-- internal/agent/engineconfig_test.go | 36 +++ internal/engine/pi/engine.go | 3 + internal/rpc/handler.go | 5 + internal/rpc/handler_test.go | 23 ++ 9 files changed, 468 insertions(+), 175 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index bf000b8..aaf8884 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,7 +54,7 @@ Pi Durable 1.4.0 stores Bot tasks. Native Harness processes own model loops. Per - `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::`, as `packages/agent/src/mcp/connections.ts`. `internal/server.RegisterMCP` serves them. Checks and sign-in run through `Service.Runner` and native connections through `Service.Catalog`, which the computer runtime supplies; `mcp.login` needs the OAuth callback URL. -- `PERSONA_WEB_SERVER=go` runs the web Playwright suite against `persona serve` through `apps/api/test/fixtures/go-server.ts` (`PERSONA_GO_BIN` names a built binary; otherwise it runs `go build`). `apps/web/test/fixtures.ts` stubs `computer.get`, `setup`, and `list` in that mode only, and `playwright.config.ts` leaves out the tests in `apps/web/test/go-gaps.ts`; remove a title when its gap closes. +- `PERSONA_WEB_SERVER=go` runs the web Playwright suite against `persona serve` through `apps/api/test/fixtures/go-server.ts` (`PERSONA_GO_BIN` names a built binary; otherwise it runs `go build`). `playwright.config.ts` leaves out the tests in `apps/web/test/go-gaps.ts`; remove a title when its gap closes. - `internal/approval` is the shared approval flow. Pass its `Approver` to `internal/mcpserver`; routine changes, computer actions, and engine requests call `Request`. Pending requests stay in the `persona.computer-requests` document and each settled request becomes one `persona.engine-message` entry. Only requests marked `Automatic` skip the question in a Bot's `auto` approval mode; product tool calls always ask. - Use the Go standard library. Add a module dependency only when a piece needs it, and keep `go.mod` on the Go version CI installs. diff --git a/apps/api/test/fixtures/go-server.ts b/apps/api/test/fixtures/go-server.ts index f112974..3acfec4 100644 --- a/apps/api/test/fixtures/go-server.ts +++ b/apps/api/test/fixtures/go-server.ts @@ -1,10 +1,17 @@ // Runs the Go service (`persona serve`) for the web E2E suite with the same -// argv and IPC replies as web-server.ts. A local Ollama double answers the -// model calls the way web-server.ts's faux provider does. Commands that need +// argv and IPC replies as web-server.ts. An OpenAI-compatible double, declared +// to Pi as the "faux" provider in models.json, answers the model calls the way +// web-server.ts's faux provider does. Commands that need // the TypeScript runtime (tool calls, seeded records, approvals, the work // browser) answer { type: "unsupported" }. -import { execFileSync, spawn } from "node:child_process"; +import { + type ChildProcess, + execFileSync, + type SpawnOptions, + spawn, +} from "node:child_process"; import { mkdir, writeFile } from "node:fs/promises"; +import { DatabaseSync } from "node:sqlite"; import { createServer, type ServerResponse } from "node:http"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -17,11 +24,19 @@ const root = fileURLToPath(new URL("../../../..", import.meta.url)); const directory = dirname(database); const models = [ { id: "faux-1", name: "测试模型一" }, - { id: "faux-2", name: "测试模型二" }, + { id: "faux-2", name: "测试模型二", reasoning: true }, ]; -type Reply = { text: string; stopReason?: string; errorMessage?: string }; +type ToolCall = { id: string; name: string; arguments: unknown }; +type Reply = { + text: string; + thinking?: string; + toolCalls?: ToolCall[]; + stopReason?: string; + errorMessage?: string; +}; let scripted: Reply[] = []; let gate: PromiseWithResolvers | undefined; +let toolGate: PromiseWithResolvers | undefined; const modelStarted = Promise.withResolvers(); function lastUserText(body: { @@ -36,6 +51,64 @@ function lastUserText(body: { .join("\n"); } +// Scripted content the double can stream: a string, or text and tool call parts. +function replyOf(item: { + content?: unknown; + stopReason?: string; + errorMessage?: string; +}): Reply | undefined { + const { content, stopReason, errorMessage } = item; + if (typeof content === "string") return { text: content, stopReason, errorMessage }; + if (!Array.isArray(content)) return undefined; + const reply: Reply = { text: "", toolCalls: [], stopReason, errorMessage }; + for (const part of content) { + if (part?.type === "text" && typeof part.text === "string") + reply.text += part.text; + else if (part?.type === "thinking" && typeof part.thinking === "string") + reply.thinking = (reply.thinking ?? "") + part.thinking; + else if (part?.type === "toolCall" && typeof part.name === "string") + reply.toolCalls?.push({ + id: part.id ?? crypto.randomUUID(), + name: part.name, + arguments: part.arguments ?? {}, + }); + else return undefined; + } + return reply; +} + +// Writes chat records into serve's store as one commit, as the TypeScript +// fixture appends them through the harness. +function seed(botId: number, records: unknown[]) { + const db = new DatabaseSync(join(directory, "go-data", "persona-go.sqlite")); + try { + db.exec("PRAGMA busy_timeout=5000; BEGIN IMMEDIATE"); + const { seq, last_id } = db + .prepare("UPDATE store_state SET seq=seq+1 RETURNING seq, last_id") + .get() as { seq: number; last_id: number }; + let id = last_id; + const claim = db.prepare("INSERT INTO record_ids VALUES (?, 'entry')"); + const entry = db.prepare("INSERT INTO entries VALUES (?, ?, ?, NULL, ?)"); + for (const data of records) { + id++; + claim.run(id); + entry.run( + id, + botId, + seq, + JSON.stringify({ id, conversationId: botId, kind: "persona.engine-message", data }), + ); + } + db.prepare("UPDATE store_state SET last_id=?").run(id); + db.exec("COMMIT"); + } catch (error) { + if (db.isTransaction) db.exec("ROLLBACK"); + throw error; + } finally { + db.close(); + } +} + function chunk(response: ServerResponse, model: string, delta: object) { response.write( `data: ${JSON.stringify({ @@ -56,8 +129,12 @@ async function complete( const model = String(body.model ?? ""); const aborted = new AbortController(); response.on("close", () => aborted.abort()); - const waiting = gate; - gate = undefined; + // 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; + if (waiting === toolGate) toolGate = undefined; + else gate = undefined; if (waiting) { aborted.signal.addEventListener("abort", () => waiting.resolve(), { once: true, @@ -74,19 +151,41 @@ async function complete( } response.writeHead(200, { "Content-Type": "text/event-stream" }); chunk(response, model, { role: "assistant", content: "" }); - // 40 one-character tokens per second, as web-server.ts streams. - for (const character of reply.text) { - if (aborted.signal.aborted) return; - chunk(response, model, { content: character }); - await new Promise((resolve) => setTimeout(resolve, 25)); + // One four-character token every 25 ms, as web-server.ts's faux provider streams. + for (const [field, text] of [ + ["reasoning_content", reply.thinking ?? ""], + ["content", reply.text], + ] as const) { + const characters = [...text]; + for (let index = 0; index < characters.length; index += 4) { + await new Promise((resolve) => setTimeout(resolve, 25)); + if (aborted.signal.aborted) return; + chunk(response, model, { + [field]: characters.slice(index, index + 4).join(""), + }); + } } + const calls = reply.toolCalls ?? []; + for (const [index, call] of calls.entries()) + chunk(response, model, { + tool_calls: [ + { + index, + id: call.id, + type: "function", + function: { name: call.name, arguments: JSON.stringify(call.arguments) }, + }, + ], + }); response.write( `data: ${JSON.stringify({ id: "chatcmpl-fixture", object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, - choices: [{ index: 0, delta: {}, finish_reason: "stop" }], + choices: [ + { index: 0, delta: {}, finish_reason: calls.length ? "tool_calls" : "stop" }, + ], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, })}\n\ndata: [DONE]\n\n`, ); @@ -142,72 +241,126 @@ const agentDir = join(directory, "pi-agent"); await mkdir(agentDir, { recursive: true }); await writeFile( join(agentDir, "settings.json"), - JSON.stringify({ defaultProvider: "ollama", defaultModel: "faux-1" }), + JSON.stringify({ defaultProvider: "faux", defaultModel: "faux-1" }), ); -const bin = join(root, "packages", "agent", "node_modules", ".bin"); -const service = spawn( - binary, - [ - "serve", - "-host", - "127.0.0.1", - "-port", - process.argv[3] ?? "0", - "-data", - join(directory, "go-data"), - "-static", - process.env.PERSONA_TEST_STATIC_DIR ?? join(root, "apps", "web", "dist"), - "-contract", - join(root, "contracts", "api"), - "-pi-extension", - join(root, "packages", "agent", "src", "harness", "pi-tools.mjs"), - ], - { - // Outside the repository so persona.config.json does not select hosted mode. - cwd: directory, - env: { - ...process.env, - OLLAMA_HOST: `http://127.0.0.1:${ollamaAddress.port}`, - PI_CODING_AGENT_DIR: agentDir, - PATH: `${bin}${process.platform === "win32" ? ";" : ":"}${process.env.PATH}`, +await writeFile( + join(agentDir, "models.json"), + JSON.stringify({ + providers: { + faux: { + baseUrl: `http://127.0.0.1:${ollamaAddress.port}/v1`, + apiKey: "fixture", + api: "openai-completions", + models: models.map(({ id, name, reasoning }) => ({ + id, + name, + reasoning: reasoning ?? false, + input: ["text", "image"], + contextWindow: 32768, + maxTokens: 8192, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + })), + }, }, - stdio: ["pipe", "pipe", "inherit"], - }, + }), ); +const bin = join(root, "packages", "agent", "node_modules", ".bin"); +const args = [ + "serve", + "-host", + "127.0.0.1", + "-port", + process.argv[3] ?? "0", + "-data", + join(directory, "go-data"), + "-static", + process.env.PERSONA_TEST_STATIC_DIR ?? join(root, "apps", "web", "dist"), + "-contract", + join(root, "contracts", "api"), + "-pi-extension", + join(root, "packages", "agent", "src", "harness", "pi-tools.mjs"), +]; +const options = { + // Outside the repository so persona.config.json does not select hosted mode. + cwd: directory, + env: { + ...process.env, + PI_CODING_AGENT_DIR: agentDir, + PATH: `${bin}${process.platform === "win32" ? ";" : ":"}${process.env.PATH}`, + }, + stdio: ["pipe", "pipe", "inherit"], +} satisfies SpawnOptions; +// Tests stop by killing this fixture, as they kill web-server.ts, and then +// remove its directory. Serve drains for seconds after stdin closes, so on POSIX +// a shell leads serve's process group and kills it as soon as this fixture's pipe closes. +const watchdog = + 'exec 3<&0; "$@" /dev/null; kill -9 0; } & wait $pid'; +const launch = () => + process.platform === "win32" + ? spawn(binary, args, options) + : spawn("sh", ["-c", watchdog, "sh", binary, ...args], { + ...options, + detached: true, + }); +// A restart on the same port can start before the killed serve released it. +const deadline = Date.now() + 15_000; +let service = launch(); +let port = await listening(service); +while (port === undefined && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 100)); + service = launch(); + port = await listening(service); +} +if (port === undefined) process.exit(1); service.on("exit", () => process.exit(1)); -if (!service.stdout) throw new Error("Service output required"); -for await (const line of createInterface({ input: service.stdout })) { - const address = /listening on http:\/\/[^:]+:(\d+)/.exec(line); - if (address) { - const port = Number(address[1]); - await configure(`http://127.0.0.1:${port}`); - process.send?.({ type: "ready", port, toolName: "" }); - break; +await configure(); +// Pi's own ls stands in for web-server.ts's gated test tool. +process.send?.({ type: "ready", port, toolName: "ls" }); + +async function listening(child: ChildProcess) { + if (!child.stdout) throw new Error("Service output required"); + for await (const line of createInterface({ input: child.stdout })) { + const address = /listening on http:\/\/[^:]+:(\d+)/.exec(line); + if (address) { + child.stdout.resume(); + return Number(address[1]); + } } + return undefined; } -service.stdout.resume(); // web-server.ts opens every Bot with the faux model and prepares its engine; // here each Bot is configured through engines.configure instead. -async function configure(origin: string) { - const call = async (path: string, json: unknown) => { - const response = await fetch(`${origin}/rpc/${path}`, { - method: "POST", - headers: { "Content-Type": "application/json", Origin: origin }, - body: JSON.stringify({ json }), - }); - if (!response.ok) - throw new Error(`${path}: ${response.status} ${await response.text()}`); - return ((await response.json()) as { json: unknown }).json; - }; +async function call(path: string, json: unknown) { + const origin = `http://127.0.0.1:${port}`; + const response = await fetch(`${origin}/rpc/${path}`, { + method: "POST", + headers: { "Content-Type": "application/json", Origin: origin }, + body: JSON.stringify({ json }), + }); + if (!response.ok) + throw new Error(`${path}: ${response.status} ${await response.text()}`); + return ((await response.json()) as { json: unknown }).json; +} + +async function firstBot() { + const [bot] = (await call("bots/list", {})) as { id: number }[]; + if (!bot) throw new Error("Bot required"); + return bot.id; +} + +async function configure() { const bots = (await call("bots/list", {})) as { id: number }[]; for (const { id } of bots) { const profile = (await call("engines/get", { botId: id })) as { revision: number; + config: { model: string | null }; }; + // A restart keeps the model the test chose. + if (profile.config.model?.startsWith("faux/")) continue; await call("engines/configure", { botId: id, - config: { provider: "pi", model: "ollama/faux-1" }, + config: { provider: "pi", model: "faux/faux-1" }, revision: profile.revision, requestId: crypto.randomUUID(), }); @@ -226,14 +379,63 @@ process.on("message", async (message) => { } else if (message === "release") { release?.(); process.send?.({ type: "released" }); + } else if (message === "gate-tool") { + toolGate = Promise.withResolvers(); + release = toolGate.resolve; + process.send?.({ type: "gated" }); + } else if ( + typeof message === "object" && + message !== null && + "history" in message && + typeof message.history === "number" + ) { + seed( + await firstBot(), + Array.from({ length: message.history }, (_, index) => { + const turnId = `history:${index}`; + return (["user", "assistant"] as const).map((role) => ({ + id: `${turnId}:${role}`, + turnId, + role, + stopped: false, + content: [ + { + type: "text", + key: `${turnId}:${role}:text`, + text: + role === "user" + ? `历史任务 ${index + 1}` + : `## 报告 ${index + 1}\n\n**资料已核对。**\n\n- 第一项结果\n- 第二项结果`, + }, + ], + })); + }).flat(), + ); + process.send?.({ type: "seeded" }); + } else if ( + typeof message === "object" && + message !== null && + "records" in message && + Array.isArray(message.records) + ) { + seed(await firstBot(), message.records); + process.send?.({ type: "seeded" }); + } else if ( + typeof message === "object" && + message !== null && + "responses" in message && + Array.isArray(message.responses) && + message.responses.every((item) => replyOf(item)) + ) { + scripted = message.responses.map((item) => replyOf(item) as Reply); + process.send?.({ type: "scripted" }); } else if ( typeof message === "object" && message !== null && "content" in message && - typeof message.content === "string" && - !("stopReason" in message && message.stopReason === "toolUse") + replyOf(message) !== undefined ) { - scripted = [{ text: message.content }]; + scripted = [replyOf(message) as Reply]; process.send?.({ type: "scripted" }); } else { process.stderr.write( diff --git a/apps/web/test/fixtures.ts b/apps/web/test/fixtures.ts index a2e09b0..8ccf708 100644 --- a/apps/web/test/fixtures.ts +++ b/apps/web/test/fixtures.ts @@ -40,55 +40,9 @@ export function fixtureServer(name: "web-server" | "onboarding-server") { ); } -const processComputer = { - deployment: "native", - error: null, - id: "process", - kind: "process", - state: "running", - os: "linux", - arch: "x64", - directory: "/tmp", - boundary: "host", - network: "host", - name: "服务所在电脑", - authorized: true, - busy: false, - capabilities: { commands: true, files: true, desktop: false }, -}; -const binding = { computerId: "process", revision: 0, requestId: "" }; - -// The Go service does not serve computer.* yet. Answer the reads the web needs -// to open a Bot with the TypeScript fixture's process computer, in the test -// layer only; every other computer procedure reaches Go unchanged. -async function stubComputer(context: BrowserContext) { - await context.route(/\/rpc\/computer\/(get|setup|list)$/, async (route) => { - const procedure = new URL(route.request().url()).pathname.split("/").pop(); - let json: unknown = { ...binding, computer: processComputer }; - if (procedure === "setup") - json = { deployment: "native", canIsolate: false }; - if (procedure === "list") { - const bots = await route.fetch({ - url: route - .request() - .url() - .replace(/computer\/list$/, "bots/list"), - }); - const { json: list } = (await bots.json()) as { json: { id: number }[] }; - json = { - items: [processComputer], - defaultId: null, - bindings: Object.fromEntries(list.map(({ id }) => [id, binding])), - }; - } - await route.fulfill({ json: { json } }); - }); -} - export const test = base.extend({ context: async ({ context }, use) => { await setTestLanguage(context); - if (goService) await stubComputer(context); await use(context); }, }); diff --git a/apps/web/test/go-gaps.ts b/apps/web/test/go-gaps.ts index c461bef..36f05ca 100644 --- a/apps/web/test/go-gaps.ts +++ b/apps/web/test/go-gaps.ts @@ -2,70 +2,58 @@ // playwright.config.ts leaves them out when PERSONA_WEB_SERVER=go. Remove a // title when its gap closes. export const goGaps: Record = { - "computer.* beyond the fixture's get/setup/list stub (assign, prepare, services, watch, takeover)": + // Waits on the worker's prepare/install/mode/settle/view port (another session). + "computer viewer: the Go worker does not yet stream the work computer's screen or switch browser mode": [ - "Bot identity stays consistent and image previews work in drafts and history", "a failed browser input pauses the viewer and reconnect never replays it", - "computer connection failures keep a direct retry", "computer viewing uses separate tabs and releases control when closed", - "contact rows keep their density and searchable previews across selections", - "contacts keep independent histories, drafts, models, and locations after restart", "continuous wheel input keeps takeover active", - "creation retries keep one contact and themed dialogs work on narrow screens", - "file drafts, real tools, and published downloads survive Bot switches and restart", - "first use prepares the default Bot with a computer and model before shared chat", - "switching contacts keeps the first Bot running while another Bot replies", "takeover card first click opens the browser and resumes after completion", "takeover controls the Agent browser and preserves its layout through fullscreen", - "working contacts retain green status across switches, concurrent work, reload, and stop", - ], - "routine runner: persona.routine tasks and work.routines.test are unported (Go only runs engine/chat turns)": - [ - "Bot details manage identity, memory, shared skills, routines and actual prompts", - ], - "engine controls: Go lists Pi's local model IDs without display names, efforts or native controls": - [ - "Bot model selection saves choices and fits both themes", - "model choices load from the server and selection survives a restart", - "model search and themed popups support keyboard, dismissal, and narrow screens", - "model selection updates immediately and restores a failed save", - "native Harness controls persist and client accounts retain model access", ], - "untriaged: needs web-server.ts scripting (seeded history, tool calls, approvals, files) or an unported Go behavior": + // Owned by the memory/delivery tool registration session. + "product tools: Go registers no approved, file-publishing product tool for scripted calls (attach_file delivery)": [ - "Apps completes and cancels browser OAuth with stored state", - "Apps manages a real MCP connection and Bot grants across reloads and themes", - "Bot details share the desktop with chat and cover narrow screens", - "Markdown keeps one message scale across elements, themes, and text enlargement", - "Work follows a native turn, opens its record and preserves it after stop and reload", - "Work renders native search, file and terminal details in both themes", - "a killed server retains uncertain work and permits an explicit retry", - "a reply arrives complete while typing survives reloads", + "Bot identity stays consistent and image previews work in drafts and history", "attachment retry keeps its request and draft after a lost receipt", - "chat keeps sending available while the Bot is working", - "chat reads older pages and retains them through live updates", - "chat reflows within the frame budget and retains its position", - "chat routine changes require confirmation and link runs to Work", - "chat suggestions fill the draft and dismissal stays complete on other devices and after restart", - "composer fades scrolling messages and covers content below its edge", "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", - "large histories render a bounded window and retain the earlier reading anchor", - "latest bubbles stay above the composer after typing, resizing, and reloading", - "message insertion moves typing continuously and completion fades it out", "message media leads captions and bubble tails follow both themes", - "monitoring stays quiet, delivers one result and opens the native Work record", - "native questions use the shared card and native replies persist", - "panel transitions preserve the transcript and draft through rapid toggles and reduced motion", "published files wait for the complete reply", - "returning to a Bot shows retained messages and draft while its stream is delayed", - "shared question and approval cards persist answers and terminal states", "structured messages keep Markdown and private tool results across reloads", - "two windows can submit while a reply is active", - "typing dots share the avatar color and follow complete messages", "typing follows the Bot and failures retain their error message", ], + "routine runner: persona.routine tasks and work.routines.test are unported (Go only runs engine/chat turns)": + [ + "Bot details manage identity, memory, shared skills, routines and actual prompts", + ], + "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", + ], + "routine tools: serve does not offer routine_* to Pi's native MCP catalog": + ["chat routine changes require confirmation and link runs to Work"], + "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", + "monitoring stays quiet, delivers one result and opens the native Work record", + ], + "MCP apps: Go has no application catalog, connection runner, or OAuth callback composed into serve": + [ + "Apps completes and cancels browser OAuth with stored state", + "Apps manages a real MCP connection and Bot grants across reloads and themes", + ], + "native Harness controls: unhosted persona serve offers no device pairing": + ["native Harness controls persist and client accounts retain model access"], }; export const goGapPatterns = Object.values(goGaps) diff --git a/internal/agent/engineconfig.go b/internal/agent/engineconfig.go index d8a413e..9a40ed8 100644 --- a/internal/agent/engineconfig.go +++ b/internal/agent/engineconfig.go @@ -2,13 +2,40 @@ package agent import ( "context" + "encoding/json" "slices" + + "github.com/Personed/Persona/internal/engine/pi" ) // EngineModel is EngineModel in packages/agent/src/harness/types.ts. type EngineModel struct { - ID string `json:"id"` - Name string `json:"name"` + ID string `json:"id"` + Name string `json:"name"` + Images *bool `json:"images,omitempty"` + Effort *Control `json:"effort,omitempty"` +} + +// catalogEngine is an engine that lists its full model definitions, as Pi's +// get_available_models. +type catalogEngine interface { + Catalog(ctx context.Context) ([]pi.CatalogModel, error) +} + +// engineModel is the model mapping of the Pi provider in +// packages/agent/src/harness/providers/pi.ts. +func engineModel(m pi.CatalogModel) EngineModel { + model := EngineModel{ID: m.Provider + "/" + m.ID, Name: m.Name} + if model.Name == "" { + model.Name = m.ID + } + effort := thinkingControl(Model{Reasoning: m.Reasoning, ThinkingLevelMap: m.ThinkingLevelMap}) + model.Effort = &effort + if m.Input != nil { + images := slices.Contains(m.Input, "image") + model.Images = &images + } + return model } // EngineInspection is a native engine connection check, the result of @@ -28,6 +55,10 @@ type EngineInspection struct { // provider in packages/agent/src/harness/providers/pi.ts. func (r *Runtime) Inspect(ctx context.Context, config EngineConfig) EngineInspection { result := r.inspect(ctx, config) + // A check the caller abandoned says nothing about the engine. + if ctx.Err() != nil { + return result + } r.inspectMu.Lock() defer r.inspectMu.Unlock() if r.inspected == nil { @@ -58,13 +89,23 @@ func (r *Runtime) inspect(ctx context.Context, config EngineConfig) EngineInspec if info.Version != "" { result.Version = &info.Version } - models, err := r.engine.Models(ctx) - if err != nil { - return result - } - for _, m := range models { - id := m.Provider + "/" + m.ModelID - result.Models = append(result.Models, EngineModel{ID: id, Name: m.ModelID}) + if catalog, ok := r.engine.(catalogEngine); ok { + models, err := catalog.Catalog(ctx) + if err != nil { + return result + } + for _, m := range models { + result.Models = append(result.Models, engineModel(m)) + } + } else { + models, err := r.engine.Models(ctx) + if err != nil { + return result + } + for _, m := range models { + id := m.Provider + "/" + m.ModelID + result.Models = append(result.Models, EngineModel{ID: id, Name: m.ModelID}) + } } result.Authenticated = len(result.Models) > 0 return result @@ -92,13 +133,23 @@ func (r *Runtime) Select(ctx context.Context, bot int64, current EngineConfig, m } // Configure replaces the Bot's engine configuration, as configure in -// packages/agent/src/runtime/index.ts. Native option controls are not read -// yet, so a configuration with options is refused. +// packages/agent/src/runtime/index.ts. An option must be one the model's +// effort control or the Bot's last read native controls offer. func (r *Runtime) Configure(ctx context.Context, bot int64, in EngineChange) error { if in.Config.Provider != "pi" { return &WorkError{Code: "NOT_IMPLEMENTED", Message: "Go 服务目前只支持 Pi 引擎。"} } - connection := r.Inspect(ctx, in.Config) + // As connections.snapshot, the last check stands in for a new one. + connection, ok := r.Inspection(in.Config.Provider) + if !ok { + connection = r.Inspect(ctx, in.Config) + } + var effort *Control + if in.Config.Model != nil { + if i := slices.IndexFunc(connection.Models, func(m EngineModel) bool { return m.ID == *in.Config.Model }); i >= 0 { + effort = connection.Models[i].Effort + } + } return r.h.Commit(ctx, func(tx *Tx) error { doc, err := Create(tx, EngineDoc, bot) if err != nil { @@ -117,10 +168,16 @@ func (r *Runtime) Configure(ctx context.Context, bot int64, in EngineChange) err if doc.Revision != in.Revision { return &WorkError{Code: "CONFLICT", Message: "配置已更新。请刷新后重试。"} } - if len(in.Config.Options) > 0 { - return &WorkError{Code: "BAD_REQUEST", Message: "请先读取此模型的原生配置,再选择可用值。"} - } reset := doc.Config.Provider != in.Config.Provider || !equalModel(doc.Config.Model, in.Config.Model) + var native []Control + if !reset { + native = nativeControls(doc.Runtime) + } + for key, value := range in.Config.Options { + if !offered(native, effort, key, value) { + return &WorkError{Code: "BAD_REQUEST", Message: "请先读取此模型的原生配置,再选择可用值。"} + } + } if reset { doc.SessionID = nil } @@ -142,6 +199,31 @@ func (r *Runtime) Configure(ctx context.Context, bot int64, in EngineChange) err }) } +// nativeControls reads the option controls cached in the engine document's +// runtime.controls. +func nativeControls(runtime map[string]any) []Control { + var controls struct { + Options []Control `json:"options"` + } + if data, err := json.Marshal(runtime["controls"]); err == nil { + _ = json.Unmarshal(data, &controls) + } + return controls.Options +} + +// offered reports whether value is a choice of the control named key: a +// native control when one is cached, else the model's effort control. +func offered(native []Control, effort *Control, key string, value any) bool { + var control *Control + if i := slices.IndexFunc(native, func(c Control) bool { return c.ID == key }); i >= 0 { + control = &native[i] + } else if effort != nil && effort.ID == key { + control = effort + } + text, ok := value.(string) + return ok && control != nil && slices.ContainsFunc(control.Options, func(o Option) bool { return o.ID == text }) +} + func equalModel(a, b *string) bool { return (a == nil) == (b == nil) && (a == nil || *a == *b) } diff --git a/internal/agent/engineconfig_test.go b/internal/agent/engineconfig_test.go index 0503894..2853691 100644 --- a/internal/agent/engineconfig_test.go +++ b/internal/agent/engineconfig_test.go @@ -3,9 +3,11 @@ package agent import ( "context" "errors" + "slices" "testing" "github.com/Personed/Persona/internal/engine" + "github.com/Personed/Persona/internal/engine/pi" ) type modelEngine struct{ scriptEngine } @@ -53,3 +55,37 @@ func TestConfigurePreparesInspectedModel(t *testing.T) { t.Fatalf("selected doc = %+v", doc) } } + +type catalogModelEngine struct{ modelEngine } + +func (catalogModelEngine) Catalog(context.Context) ([]pi.CatalogModel, error) { + return []pi.CatalogModel{{Provider: "faux", ID: "r1", Name: "推理模型", Reasoning: true, Input: []string{"text"}}}, nil +} + +func TestSelectAcceptsOfferedEffort(t *testing.T) { + ctx := context.Background() + a := open(t) + rt := NewRuntime(a, RuntimeOptions{Engine: catalogModelEngine{}, Native: true}) + bot := int64(a.Root) + model := "faux/r1" + config := EngineConfig{Provider: "pi", Model: &model} + inspected := rt.Inspect(ctx, config) + if len(inspected.Models) != 1 { + t.Fatalf("models = %+v", inspected.Models) + } + m := inspected.Models[0] + if m.Name != "推理模型" || m.Images == nil || *m.Images || m.Effort == nil || + !slices.ContainsFunc(m.Effort.Options, func(o Option) bool { return o.ID == "high" }) { + t.Fatalf("model = %+v", m) + } + var work *WorkError + if err := rt.Select(ctx, bot, config, &model, map[string]any{"thinkingLevel": "extreme"}, 0, "a"); !errors.As(err, &work) || work.Code != "BAD_REQUEST" { + t.Fatalf("unoffered effort: %v", err) + } + if err := rt.Select(ctx, bot, config, &model, map[string]any{"thinkingLevel": "high"}, 0, "b"); err != nil { + t.Fatal(err) + } + if doc, _, _ := Snapshot(ctx, a.Harness, EngineDoc, bot); doc.Config.Options["thinkingLevel"] != "high" { + t.Fatalf("doc = %+v", doc) + } +} diff --git a/internal/engine/pi/engine.go b/internal/engine/pi/engine.go index 959729c..3a8e52a 100644 --- a/internal/engine/pi/engine.go +++ b/internal/engine/pi/engine.go @@ -156,6 +156,9 @@ type CatalogModel struct { Reasoning bool `json:"reasoning"` ContextWindow int64 `json:"contextWindow"` ThinkingLevels []string `json:"thinkingLevels,omitempty"` + // ThinkingLevelMap is pi-ai's per-level mapping; a null value marks a + // level the model does not support. + ThinkingLevelMap map[string]*string `json:"thinkingLevelMap,omitempty"` } // Catalog returns Pi's full model definitions from get_available_models. diff --git a/internal/rpc/handler.go b/internal/rpc/handler.go index 905b646..5e8d985 100644 --- a/internal/rpc/handler.go +++ b/internal/rpc/handler.go @@ -210,6 +210,11 @@ func (s *Server) serveEvents(w http.ResponseWriter, r *http.Request, stream Stre } close(writes) <-finished + // A stream the service closes while it stops ends like a lost connection, + // so oRPC clients retry instead of reading a finished iterator. + if s.streams.Err() != nil && r.Context().Err() == nil { + panic(http.ErrAbortHandler) + } } // envelope is the RPC serializer body of value: {"json": value}, or {} for Void. diff --git a/internal/rpc/handler_test.go b/internal/rpc/handler_test.go index 107c99d..8ba6d5c 100644 --- a/internal/rpc/handler_test.go +++ b/internal/rpc/handler_test.go @@ -232,6 +232,29 @@ func TestStreamCancel(t *testing.T) { } } +func TestCloseStreamsAbortsConnection(t *testing.T) { + s := newServer(t) + s.HandleStream("subscribe", func(ctx context.Context, _ json.RawMessage, send func(any) error) (any, error) { + if err := send(1); err != nil { + return nil, err + } + <-ctx.Done() + return nil, ctx.Err() + }) + server := httptest.NewServer(s) + defer server.Close() + resp, err := http.Post(server.URL+"/rpc/subscribe", "application/json", strings.NewReader(`{"json":{"botId":1}}`)) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + _, _ = io.ReadFull(resp.Body, make([]byte, 10)) + s.CloseStreams() + if _, err := io.ReadAll(resp.Body); err == nil { + t.Error("closed stream ended cleanly, want an aborted connection") + } +} + func TestVoidStreamDone(t *testing.T) { s := newServer(t) s.HandleStream("work.subscribe", func(context.Context, json.RawMessage, func(any) error) (any, error) { From 64d790399d3088423d6ee1b1b5be144b0539655f Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 19:04:09 +0000 Subject: [PATCH 02/14] Un-exclude structured messages and kill serve's process group with the fixture Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/api/test/fixtures/go-server.ts | 23 ++++++++++++++++----- apps/web/test/go-gaps.ts | 32 ++++++++++++++--------------- 2 files changed, 33 insertions(+), 22 deletions(-) diff --git a/apps/api/test/fixtures/go-server.ts b/apps/api/test/fixtures/go-server.ts index 3acfec4..7e2c03c 100644 --- a/apps/api/test/fixtures/go-server.ts +++ b/apps/api/test/fixtures/go-server.ts @@ -11,11 +11,11 @@ import { spawn, } from "node:child_process"; import { mkdir, writeFile } from "node:fs/promises"; -import { DatabaseSync } from "node:sqlite"; import { createServer, type ServerResponse } from "node:http"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { createInterface } from "node:readline"; +import { DatabaseSync } from "node:sqlite"; import { fileURLToPath } from "node:url"; const database = process.argv[2]; @@ -58,7 +58,8 @@ function replyOf(item: { errorMessage?: string; }): Reply | undefined { const { content, stopReason, errorMessage } = item; - if (typeof content === "string") return { text: content, stopReason, errorMessage }; + if (typeof content === "string") + return { text: content, stopReason, errorMessage }; if (!Array.isArray(content)) return undefined; const reply: Reply = { text: "", toolCalls: [], stopReason, errorMessage }; for (const part of content) { @@ -96,7 +97,12 @@ function seed(botId: number, records: unknown[]) { id, botId, seq, - JSON.stringify({ id, conversationId: botId, kind: "persona.engine-message", data }), + JSON.stringify({ + id, + conversationId: botId, + kind: "persona.engine-message", + data, + }), ); } db.prepare("UPDATE store_state SET last_id=?").run(id); @@ -173,7 +179,10 @@ async function complete( index, id: call.id, type: "function", - function: { name: call.name, arguments: JSON.stringify(call.arguments) }, + function: { + name: call.name, + arguments: JSON.stringify(call.arguments), + }, }, ], }); @@ -184,7 +193,11 @@ async function complete( created: Math.floor(Date.now() / 1000), model, choices: [ - { index: 0, delta: {}, finish_reason: calls.length ? "tool_calls" : "stop" }, + { + index: 0, + delta: {}, + finish_reason: calls.length ? "tool_calls" : "stop", + }, ], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, })}\n\ndata: [DONE]\n\n`, diff --git a/apps/web/test/go-gaps.ts b/apps/web/test/go-gaps.ts index 36f05ca..4438730 100644 --- a/apps/web/test/go-gaps.ts +++ b/apps/web/test/go-gaps.ts @@ -11,8 +11,7 @@ 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", ], - // Owned by the memory/delivery tool registration session. - "product tools: Go registers no approved, file-publishing product tool for scripted calls (attach_file delivery)": + "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", @@ -22,7 +21,6 @@ export const goGaps: Record = { "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", - "structured messages keep Markdown and private tool results across reloads", "typing follows the Bot and failures retain their error message", ], "routine runner: persona.routine tasks and work.routines.test are unported (Go only runs engine/chat turns)": @@ -35,25 +33,25 @@ export const goGaps: Record = { "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", ], - "routine tools: serve does not offer routine_* to Pi's native MCP catalog": - ["chat routine changes require confirmation and link runs to Work"], - "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", - "monitoring stays quiet, delivers one result and opens the native Work record", - ], + "routine tools: serve does not offer routine_* to Pi's native MCP catalog": [ + "chat routine changes require confirmation and link runs to Work", + ], + "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", + "monitoring stays quiet, delivers one result and opens the native Work record", + ], "MCP apps: Go has no application catalog, connection runner, or OAuth callback composed into serve": [ "Apps completes and cancels browser OAuth with stored state", "Apps manages a real MCP connection and Bot grants across reloads and themes", ], - "native Harness controls: unhosted persona serve offers no device pairing": - ["native Harness controls persist and client accounts retain model access"], + "native Harness controls: unhosted persona serve offers no device pairing": [ + "native Harness controls persist and client accounts retain model access", + ], }; export const goGapPatterns = Object.values(goGaps) From 198b71f0380e44b5d7ddaa83c1c341daca374c0e Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 19:14:26 +0000 Subject: [PATCH 03/14] Ask Pi's native questions through the shared approval cards Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/web/test/go-gaps.ts | 1 - internal/agent/chatview.go | 62 ++++++++++++++++++++++++++++++++++++-- internal/agent/docs.go | 7 +++++ internal/agent/runtime.go | 46 +++++++++++++++++++--------- internal/agent/view.go | 2 +- 5 files changed, 99 insertions(+), 19 deletions(-) diff --git a/apps/web/test/go-gaps.ts b/apps/web/test/go-gaps.ts index 4438730..59bc334 100644 --- a/apps/web/test/go-gaps.ts +++ b/apps/web/test/go-gaps.ts @@ -37,7 +37,6 @@ export const goGaps: Record = { "chat routine changes require confirmation and link runs to Work", ], "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": [ diff --git a/internal/agent/chatview.go b/internal/agent/chatview.go index 32b0e91..58dcc0c 100644 --- a/internal/agent/chatview.go +++ b/internal/agent/chatview.go @@ -87,6 +87,8 @@ type conversationView struct { before store.EntryID live LiveState agent Config + // approvals are the pending requests of persona.computer-requests. + approvals []json.RawMessage } func (h *Harness) conversationDocs(ctx context.Context, id int64) (conversationView, error) { @@ -95,7 +97,11 @@ func (h *Harness) conversationDocs(ctx context.Context, id int64) (conversationV if view.live, _, err = Snapshot(ctx, h, LiveDoc, id); err != nil { return view, err } - view.agent, _, err = Snapshot(ctx, h, AgentDoc, id) + if view.agent, _, err = Snapshot(ctx, h, AgentDoc, id); err != nil { + return view, err + } + requests, _, err := Snapshot(ctx, h, RequestsDoc, id) + view.approvals = requests.Approvals return view, err } @@ -428,7 +434,13 @@ func projectChat(view conversationView) ChatView { pendingTool = pendingTool || tool.Status != "done" chat.Tools = append(chat.Tools, LiveTool(tool)) } - chat.Processing = running && (view.live.Generation != nil || pendingTool) + for _, request := range view.approvals { + if message := pendingApproval(request, turnID); message != nil { + chat.Messages = append(chat.Messages, message) + chat.Approvals = append(chat.Approvals, request) + } + } + chat.Processing = running && len(chat.Approvals) == 0 && (view.live.Generation != nil || pendingTool) chat.Failed = failed && !running return chat } @@ -441,3 +453,49 @@ func (c ChatView) Attachments() []string { } return ids } + +// pendingApproval is approvalMessage(request, "pending") in messages.ts, the +// card of a request still waiting for its answer. +func pendingApproval(raw json.RawMessage, turnID *string) map[string]any { + var request struct { + ID string `json:"id"` + Detail string `json:"detail"` + RequestedAt *int64 `json:"requestedAt"` + Takeover map[string]json.RawMessage `json:"takeover"` + Preview map[string]json.RawMessage `json:"preview"` + } + if json.Unmarshal(raw, &request) != nil || request.ID == "" { + return nil + } + requestedAt := int64(0) + if request.RequestedAt != nil { + requestedAt = *request.RequestedAt + } + message := map[string]any{ + "id": fmt.Sprintf("approval:%s:%d", request.ID, requestedAt), "role": "assistant", + "content": []any{}, "pending": true, "stopped": false, + } + if request.RequestedAt != nil { + message["timestamp"] = *request.RequestedAt + } + if turnID != nil { + message["turnId"] = *turnID + } + if request.Takeover == nil { + message["approval"] = map[string]any{"request": raw, "state": "pending"} + return message + } + content := []any{map[string]any{"type": "text", "text": request.Detail, "key": request.ID}} + if request.Preview != nil { + preview := map[string]any{"key": request.ID + ":preview"} + for key, value := range request.Preview { + if key != "key" { + preview[key] = value + } + } + content = append(content, preview) + } + message["content"] = content + message["takeover"] = request.Takeover + return message +} diff --git a/internal/agent/docs.go b/internal/agent/docs.go index 8d7bb73..7264308 100644 --- a/internal/agent/docs.go +++ b/internal/agent/docs.go @@ -212,8 +212,15 @@ var ( MemorySnapshotDoc = Doc[MemorySnapshot]{Kind: memory.SnapshotDocKind, Scope: "task"} UsageTaskDoc = Doc[TaskItems]{Kind: "persona.engine-usage", Scope: "task", Initial: emptyItems} CompactionTaskDoc = Doc[TaskItems]{Kind: "persona.engine-compaction", Scope: "task", Initial: emptyItems} + RequestsDoc = Doc[ComputerRequests]{Kind: "persona.computer-requests", Scope: "conversation", History: "latest", Fork: "initial"} ) +// ComputerRequests is the persona.computer-requests document; internal/approval +// owns its writes and the chat shows its pending approvals. +type ComputerRequests struct { + Approvals []json.RawMessage `json:"approvals"` +} + // Entry kinds read by the chat projection. const ( FileInput = "persona.file-input" diff --git a/internal/agent/runtime.go b/internal/agent/runtime.go index 8735b77..1fa3c6f 100644 --- a/internal/agent/runtime.go +++ b/internal/agent/runtime.go @@ -691,21 +691,37 @@ func (r *Runtime) consume(ctx context.Context, session engine.Session, emit func return settled } -// approve answers one of Pi's approval requests. Answers are not served yet, -// so only an Automatic request in the Bot's auto approval mode is allowed and -// every other request is cancelled rather than left waiting. -func (r *Runtime) approve(ctx context.Context, bot int64, session engine.Session, request map[string]any) { - id, _ := request["id"].(string) - automatic, _ := request["automatic"].(bool) - allow := false - if automatic && r.approvals != nil { - allow, _ = r.approvals.Automatic(ctx, bot) - } - answer := json.RawMessage(`{"cancelled":true}`) - if allow { - answer = json.RawMessage(`{"confirmed":true}`) - } - _ = session.Answer(ctx, id, answer) +// approve asks the user one of Pi's approval requests through the shared +// approval flow and answers Pi with the reply, as execution.ts approve does. A +// stopped task expires the request, and Pi's dialog is cancelled. +func (r *Runtime) approve(ctx context.Context, bot int64, session engine.Session, payload map[string]any) { + var request approval.Request + if data, err := json.Marshal(payload); err == nil { + _ = json.Unmarshal(data, &request) + } + var answer approval.Answer + if r.approvals != nil && request.ID != "" { + answer, _ = r.approvals.Request(ctx, bot, request) + } + response, _ := json.Marshal(piAnswer(request, answer)) + _ = session.Answer(context.WithoutCancel(ctx), request.ID, response) +} + +// piAnswer is the extension_ui_response body for an answered approval, as +// pi-ui.ts answer: cancelled unless allowed, confirmed for a permission, else +// the question's first answer or the free text. +func piAnswer(request approval.Request, answer approval.Answer) map[string]any { + switch { + case !answer.Allow: + return map[string]any{"cancelled": true} + case request.Kind != approval.Question: + return map[string]any{"confirmed": true} + } + value := answer.Text + if values := answer.Answers[request.ID]; len(values) > 0 { + value = values[0] + } + return map[string]any{"value": value} } func (r *Runtime) readContext(ctx context.Context, session engine.Session, p *projection) { diff --git a/internal/agent/view.go b/internal/agent/view.go index 42579bd..c78404c 100644 --- a/internal/agent/view.go +++ b/internal/agent/view.go @@ -40,7 +40,7 @@ func (r *Runtime) View(ctx context.Context, bot int64, before string) (any, erro } processing, _ := doc.Runtime["processing"].(bool) chat.Busy = chat.Busy || len(doc.Tasks) > 0 - chat.Processing = chat.Processing || len(chat.Approvals) > 0 || (doc.ActiveID != nil && processing) + chat.Processing = len(chat.Approvals) == 0 && (chat.Processing || (doc.ActiveID != nil && processing)) if doc.ActiveTurn != nil { chat.ActiveTurnID = doc.ActiveTurn } From ecefe1791deae708ef3947da2a1b04592cc5b53a Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 19:15:32 +0000 Subject: [PATCH 04/14] Record the remaining shared approval gap and document native question flow Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- AGENTS.md | 2 +- apps/web/test/go-gaps.ts | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index aaf8884..10907aa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 `.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, 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 and `ask_user` requests through `internal/approval` and answers Pi with the reply; a stopped task expires the card and cancels Pi's dialog. - `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::`, as `packages/agent/src/mcp/connections.ts`. `internal/server.RegisterMCP` serves them. Checks and sign-in run through `Service.Runner` and native connections through `Service.Catalog`, which the computer runtime supplies; `mcp.login` needs the OAuth callback URL. diff --git a/apps/web/test/go-gaps.ts b/apps/web/test/go-gaps.ts index 59bc334..09bc1a6 100644 --- a/apps/web/test/go-gaps.ts +++ b/apps/web/test/go-gaps.ts @@ -36,7 +36,9 @@ export const goGaps: Record = { "routine tools: serve does not offer routine_* to Pi's native MCP catalog": [ "chat routine changes require confirmation and link runs to Work", ], - "native questions: Pi's ask_user is not stored as a shared question card": [ + // 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", ], "native Work records: work.records does not yet project native turns": [ From 04e407a1efa6175995c619db3225df2b0fcbd2f6 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 18:37:49 +0000 Subject: [PATCH 05/14] Serve routine, skill, and history product tools to Pi from persona serve Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- AGENTS.md | 2 +- internal/agent/runtime.go | 14 +++++++-- internal/agent/runtime_test.go | 53 ++++++++++++++++++++++++++++++++++ internal/cli/serve.go | 30 +++++++++++++------ internal/cli/serve_test.go | 50 ++++++++++++++++++++++++++++++++ 5 files changed, 137 insertions(+), 12 deletions(-) create mode 100644 internal/cli/serve_test.go diff --git a/AGENTS.md b/AGENTS.md index 5a3ac17..2ed01fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,7 +46,7 @@ Pi Durable 1.4.0 stores Bot tasks. Native Harness processes own model loops. Per - The interfaces in `internal/store`, `internal/engine`, `internal/tools`, `internal/computer`, and `internal/hosting` are the boundaries between migration pieces. Change one only with its callers and mocks in the same change. - `internal/store` records mirror pi-durable so existing databases import without translation. Pi is the only engine and runs as `pi --mode rpc` over JSONL on stdio. Pi has no Go SDK. An idle Bot has no engine process. - The Go service serves the oRPC wire in `contracts/api` unchanged: paths, input validation, output shapes, error codes, and HTTP statuses. Regenerate `procedures.json` and the fixtures in the same change as any TypeScript API change. -- `internal/mcpserver` serves the `internal/tools` registry to Pi as one loopback MCP endpoint per Bot task. Add product tools by registering them in the registry; mutating tools set `Mutates` so calls pass the shared approver. A call's `CallID` is its MCP session and JSON-RPC request ID, and a redelivered request gets the recorded outcome. `internal/store/storetest` is the in-memory store for tests until the SQLite store lands. The gateway bounds each result's text for the model, holds the latest complete results, and serves `query_result` over them itself. `internal/history` owns `conversation_read`; a Bot's ID is its conversation ID. +- `internal/mcpserver` serves the `internal/tools` registry to Pi as one loopback MCP endpoint per Bot task. Add product tools by registering them in the registry; mutating tools set `Mutates` so calls pass the shared approver. A call's `CallID` is its MCP session and JSON-RPC request ID, and a redelivered request gets the recorded outcome. `internal/store/storetest` is the in-memory store for tests until the SQLite store lands. The gateway bounds each result's text for the model, holds the latest complete results, and serves `query_result` over them itself. `internal/history` owns `conversation_read`; a Bot's ID is its conversation ID. `persona serve` composes the registry in `productTools` (`internal/cli/serve.go`), and the runtime declares its tools in each session's `persona-tools.json` and the engine prompt document. - `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 `.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. diff --git a/internal/agent/runtime.go b/internal/agent/runtime.go index 076ab93..96fad98 100644 --- a/internal/agent/runtime.go +++ b/internal/agent/runtime.go @@ -627,6 +627,16 @@ func (r *Runtime) executeEngine(ctx context.Context, bot int64, w *worker, task sections["skills"] = text } sections["messaging"] = "Send updates and final results through native assistant messages. Ask for decisions with the Harness native question tool. Wait for the user's answer before dependent work. Do not repeat an update as the final answer. Keep reasoning in the thinking channel. Use short natural paragraphs unless the user requests a structured document." + definitions, err := r.tools.List(ctx, bot) + if err != nil { + return err.Error() + } + names := make([]string, len(definitions)) + specs := make([]engine.ToolSpec, len(definitions)) + for i, definition := range definitions { + names[i] = definition.Name + specs[i] = engine.ToolSpec{Name: definition.Name, Description: definition.Description, InputSchema: definition.InputSchema} + } instructions := joinInstructions(append(append([]string{profile.Instructions()}, sectionTexts(sections)...), toolInstructions)...) if err := r.h.Commit(ctx, func(tx *Tx) error { if !ok { @@ -640,7 +650,7 @@ func (r *Runtime) executeEngine(ctx context.Context, bot int64, w *worker, task if err != nil { return err } - doc.Prompt, err = json.Marshal(map[string]any{"text": instructions, "sections": sections, "tools": []string{}}) + doc.Prompt, err = json.Marshal(map[string]any{"text": instructions, "sections": sections, "tools": names}) return err }); err != nil { return err.Error() @@ -654,7 +664,7 @@ func (r *Runtime) executeEngine(ctx context.Context, bot int64, w *worker, task return err.Error() } defer func() { _ = gateway.Close() }() - options := engine.SessionOptions{BotID: bot, SessionID: sessionID, SystemPrompt: instructions, + options := engine.SessionOptions{BotID: bot, SessionID: sessionID, SystemPrompt: instructions, Tools: specs, Env: map[string]string{"PERSONA_PI_MCP_URL": gateway.URL}} if config.Model != nil { if provider, model, ok := strings.Cut(*config.Model, "/"); ok { diff --git a/internal/agent/runtime_test.go b/internal/agent/runtime_test.go index 640cdee..f917714 100644 --- a/internal/agent/runtime_test.go +++ b/internal/agent/runtime_test.go @@ -10,9 +10,12 @@ import ( "testing" "time" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/Personed/Persona/internal/engine" "github.com/Personed/Persona/internal/memory" "github.com/Personed/Persona/internal/store" + "github.com/Personed/Persona/internal/tools" ) // scriptEngine runs each prompt's frames, and holds the prompt open until @@ -532,3 +535,53 @@ func TestRuntimeTaskSnapshotsMemoryIntoInstructions(t *testing.T) { t.Fatalf("first task snapshot changed to %q", again.Text) } } + +type probeTool struct{} + +func (probeTool) Definition() tools.Definition { + return tools.Definition{Name: "probe_read", Description: "Probe.", InputSchema: json.RawMessage(`{"type":"object"}`)} +} +func (probeTool) Run(context.Context, tools.Call) (tools.Result, error) { return tools.Result{}, nil } + +func TestRuntimeGatewayServesRegistry(t *testing.T) { + ctx := context.Background() + registry := tools.NewRegistry() + if err := registry.Register(probeTool{}); err != nil { + t.Fatal(err) + } + hold := make(chan struct{}) + started := make(chan *scriptSession, 1) + a := open(t) + rt := NewRuntime(a, RuntimeOptions{Native: true, Tools: registry, + Engine: scriptEngine{frames: strings.Split(answerFrames, "\n"), hold: hold, started: started}}) + bot := int64(a.Root) + if _, err := rt.Submit(ctx, SendInput{BotID: bot, Text: "hello", RequestID: "r1"}); err != nil { + t.Fatal(err) + } + session := <-started + if specs := session.options.Tools; len(specs) != 1 || specs[0].Name != "probe_read" { + t.Errorf("declared tools = %+v", specs) + } + client := mcp.NewClient(&mcp.Implementation{Name: "pi-test", Version: "0"}, nil) + mcpSession, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: session.options.Env["PERSONA_PI_MCP_URL"], MaxRetries: -1}, nil) + if err != nil { + t.Fatal(err) + } + listed, err := mcpSession.ListTools(ctx, nil) + _ = mcpSession.Close() + if err != nil { + t.Fatal(err) + } + if !slices.ContainsFunc(listed.Tools, func(tool *mcp.Tool) bool { return tool.Name == "probe_read" }) { + t.Errorf("gateway lists %d tools without probe_read", len(listed.Tools)) + } + close(hold) + idle(t, rt) + doc, _, err := Snapshot(ctx, a.Harness, EngineDoc, bot) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(doc.Prompt), `"tools":["probe_read"]`) { + t.Errorf("prompt = %s", doc.Prompt) + } +} diff --git a/internal/cli/serve.go b/internal/cli/serve.go index 29a8caa..aa0aa25 100644 --- a/internal/cli/serve.go +++ b/internal/cli/serve.go @@ -20,6 +20,7 @@ import ( "github.com/Personed/Persona/internal/contract" "github.com/Personed/Persona/internal/delivery" "github.com/Personed/Persona/internal/engine/pi" + "github.com/Personed/Persona/internal/history" "github.com/Personed/Persona/internal/hosting" "github.com/Personed/Persona/internal/localmodels" "github.com/Personed/Persona/internal/mcp" @@ -33,6 +34,22 @@ import ( "github.com/Personed/Persona/internal/tools" ) +// productTools is the registry each Bot task's MCP gateway serves to Pi. +func productTools(records store.Store, routineSvc *routines.Service, skillSvc *skills.Service, handoff takeover.Handoff) (tools.Registry, error) { + registry := tools.NewRegistry() + for _, register := range []func() error{ + func() error { return takeover.Register(registry, handoff) }, + func() error { return routines.Register(registry, routineSvc) }, + func() error { return skills.Register(registry, skillSvc) }, + func() error { return history.Register(registry, history.NewReader(records)) }, + } { + if err := register(); err != nil { + return nil, err + } + } + return registry, nil +} + // serve runs the local service. Procedures without a Go handler answer NOT_IMPLEMENTED. // Without a model registry in Go yet, models.list is empty. func serve(ctx context.Context, args []string, stdout io.Writer) error { @@ -150,18 +167,18 @@ func serve(ctx context.Context, args []string, stdout io.Writer) error { approvals := approval.NewService(records, nil, 0) // Work services shared by the RPC layer and the product tools below. memorySvc := memory.NewService(records, nil) + routineSvc := routines.NewService(records, nil) skillSvc := skills.NewService(records, os.DirFS(filepath.Join(filesRoot, "skills")), catalog.Workspace) skillSvc.UsePackageDir(filepath.Join(filesRoot, "skills")) - work := server.Work{Memory: memorySvc, Skills: skillSvc, - Routines: routines.NewService(records, nil)} + work := server.Work{Memory: memorySvc, Routines: routineSvc, Skills: skillSvc} var runtime *agent.Runtime if *piExtension != "" { // An idle Bot has no Pi: each closes with the last session of its task. engine := pi.New(pi.Config{Extensions: []string{*piExtension}, IdleTimeout: -1, LocalModels: true, SessionDir: filepath.Join(*dataDir, "pi", "sessions"), StateDir: filepath.Join(*dataDir, "pi", "state")}) defer engine.Close() - registry := tools.NewRegistry() - if err := takeover.Register(registry, catalog.Handoff(approvals)); err != nil { + registry, err := productTools(records, routineSvc, skillSvc, catalog.Handoff(approvals)) + if err != nil { return err } if err := memory.Register(registry, memorySvc); err != nil { @@ -176,11 +193,6 @@ func serve(ctx context.Context, args []string, stdout io.Writer) error { })); err != nil { return err } - routineSvc := routines.NewService(records, nil) - work.Routines = routineSvc - if err := routines.Register(registry, routineSvc); err != nil { - return err - } runtime = agent.NewRuntime(bots, agent.RuntimeOptions{Engine: engine, Native: true, Tools: registry, Approvals: approvals, Memory: memorySvc}) if err := runtime.Recover(ctx); err != nil { diff --git a/internal/cli/serve_test.go b/internal/cli/serve_test.go new file mode 100644 index 0000000..abc5113 --- /dev/null +++ b/internal/cli/serve_test.go @@ -0,0 +1,50 @@ +package cli + +import ( + "context" + "slices" + "testing" + "testing/fstest" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/Personed/Persona/internal/mcpserver" + "github.com/Personed/Persona/internal/routines" + "github.com/Personed/Persona/internal/skills" + "github.com/Personed/Persona/internal/store/storetest" + "github.com/Personed/Persona/internal/takeover" +) + +func TestProductToolsServedToPi(t *testing.T) { + ctx := context.Background() + records := storetest.New() + handoff := takeover.Handoff(func(context.Context, takeover.Request) (bool, error) { return false, nil }) + registry, err := productTools(records, routines.NewService(records, nil), skills.NewService(records, fstest.MapFS{}, nil), handoff) + if err != nil { + t.Fatal(err) + } + gateway, err := mcpserver.Open(ctx, mcpserver.Options{Registry: registry, BotID: 1, TaskID: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = gateway.Close() }) + client := mcp.NewClient(&mcp.Implementation{Name: "pi-test", Version: "0"}, nil) + session, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: gateway.URL, MaxRetries: -1}, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = session.Close() }) + listed, err := session.ListTools(ctx, nil) + if err != nil { + t.Fatal(err) + } + var names []string + for _, tool := range listed.Tools { + names = append(names, tool.Name) + } + for _, want := range []string{"computer_request_takeover", "routine_report", "routine_manage", "routine_list", "routine_create", "skill_read", "conversation_read"} { + if !slices.Contains(names, want) { + t.Errorf("served tools %q lack %s", names, want) + } + } +} From b69b1edf85b5d30c4e03bfff184db4a2dc6072c8 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 20:15:11 +0000 Subject: [PATCH 06/14] Open native Work records under Go: Pi native MCP, routine confirmation cards, gated fixture tool Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/api/test/fixtures/go-server.ts | 60 ++++++- apps/web/src/features/shell/workspace.tsx | 22 ++- apps/web/test/go-gaps.ts | 6 +- apps/web/test/workspace.spec.ts | 2 + internal/cli/serve.go | 11 +- internal/engine/pi/engine.go | 9 +- internal/routines/confirm.go | 186 ++++++++++++++++++++++ internal/routines/routines.go | 4 + internal/routines/routines_test.go | 36 +++-- internal/routines/tools.go | 16 +- 10 files changed, 322 insertions(+), 30 deletions(-) create mode 100644 internal/routines/confirm.go diff --git a/apps/api/test/fixtures/go-server.ts b/apps/api/test/fixtures/go-server.ts index 7e2c03c..b5354a9 100644 --- a/apps/api/test/fixtures/go-server.ts +++ b/apps/api/test/fixtures/go-server.ts @@ -37,7 +37,7 @@ type Reply = { let scripted: Reply[] = []; let gate: PromiseWithResolvers | undefined; let toolGate: PromiseWithResolvers | undefined; -const modelStarted = Promise.withResolvers(); +let modelStarted = Promise.withResolvers(); function lastUserText(body: { messages?: { role: string; content: unknown }[]; @@ -171,7 +171,18 @@ async function complete( }); } } - const calls = reply.toolCalls ?? []; + // Pi declares Persona's product tools as mcp__persona__; tests script + // the product name, as web-server.ts's tools are called. + const declared = new Set( + ((body.tools as { function?: { name?: string } }[] | undefined) ?? []).map( + (tool) => tool.function?.name, + ), + ); + const calls = (reply.toolCalls ?? []).map((call) => + declared.has(`mcp__persona__${call.name}`) + ? { ...call, name: `mcp__persona__${call.name}` } + : call, + ); for (const [index, call] of calls.entries()) chunk(response, model, { tool_calls: [ @@ -205,6 +216,17 @@ async function complete( response.end(); } +// The fixture tool's Pi extension asks here before it returns, so a gated +// tool stays running the way web-server.ts's test tool does. +async function runTool(response: ServerResponse) { + const waiting = toolGate; + if (waiting) { + response.on("close", () => waiting.resolve()); + await waiting.promise; + } + response.end(); +} + const ollama = createServer((request, response) => { let raw = ""; request.on("data", (part) => { @@ -229,6 +251,8 @@ const ollama = createServer((request, response) => { }); if (request.url === "/v1/chat/completions" && request.method === "POST") return void complete(JSON.parse(raw || "{}"), response); + if (request.url === "/tool" && request.method === "POST") + return void runTool(response); response.statusCode = 404; response.end(); }); @@ -277,6 +301,31 @@ await writeFile( }, }), ); +// This Pi extension stands in for web-server.ts's test tool: it returns the +// supplied text after the fixture releases a gated tool. +const toolName = "fixture_echo"; +const toolExtension = join(agentDir, "fixture-tool.js"); +await writeFile( + toolExtension, + `export default function (pi) { + pi.registerTool({ + name: ${JSON.stringify(toolName)}, + label: ${JSON.stringify(toolName)}, + description: "Return the supplied text.", + parameters: { + type: "object", + properties: { text: { type: "string" }, fail: { type: "boolean" } }, + required: ["text"], + }, + async execute(_id, params, signal) { + await fetch(${JSON.stringify(`http://127.0.0.1:${ollamaAddress.port}/tool`)}, { method: "POST", signal }); + if (params.fail) throw new Error(params.text); + return { content: [{ type: "text", text: params.text }], details: {} }; + }, + }); +} +`, +); const bin = join(root, "packages", "agent", "node_modules", ".bin"); const args = [ "serve", @@ -292,6 +341,8 @@ const args = [ join(root, "contracts", "api"), "-pi-extension", join(root, "packages", "agent", "src", "harness", "pi-tools.mjs"), + "-pi-extension", + toolExtension, ]; const options = { // Outside the repository so persona.config.json does not select hosted mode. @@ -327,8 +378,7 @@ while (port === undefined && Date.now() < deadline) { if (port === undefined) process.exit(1); service.on("exit", () => process.exit(1)); await configure(); -// Pi's own ls stands in for web-server.ts's gated test tool. -process.send?.({ type: "ready", port, toolName: "ls" }); +process.send?.({ type: "ready", port, toolName }); async function listening(child: ChildProcess) { if (!child.stdout) throw new Error("Service output required"); @@ -383,6 +433,8 @@ async function configure() { let release: (() => void) | undefined; process.on("message", async (message) => { if (message === "gate") { + // wait-model then waits for the request this gate holds. + modelStarted = Promise.withResolvers(); gate = Promise.withResolvers(); release = gate.resolve; process.send?.({ type: "gated" }); diff --git a/apps/web/src/features/shell/workspace.tsx b/apps/web/src/features/shell/workspace.tsx index 166ae02..242dffe 100644 --- a/apps/web/src/features/shell/workspace.tsx +++ b/apps/web/src/features/shell/workspace.tsx @@ -61,17 +61,37 @@ export function Workspace({ document.activeViewTransition?.skipTransition(); }); useEffect(() => { + let pressed = false; + const release = () => { + pressed = false; + }; + // React starts a queued transition as soon as the skipped one finishes, + // and it would capture the press's pointerup, so skip it as well. + const skip = (transition: ViewTransition) => { + transition.skipTransition(); + const next = () => { + const queued = document.activeViewTransition; + if (pressed && queued && queued !== transition) skip(queued); + }; + transition.finished.then(next, next); + }; const interrupt = (event: Event) => { const transition = document.activeViewTransition; if (!transition || !sizing.root?.contains(event.target as Node)) return; - transition.skipTransition(); + pressed = event.type === "pointerdown"; + skip(transition); flushSync(() => setDragging(false)); }; // React pauses synthetic events while the transition snapshot commits. window.addEventListener("pointerdown", interrupt, true); window.addEventListener("keydown", interrupt, true); window.addEventListener("beforeinput", interrupt, true); + window.addEventListener("pointerup", release, true); + window.addEventListener("pointercancel", release, true); return () => { + release(); + window.removeEventListener("pointerup", release, true); + window.removeEventListener("pointercancel", release, true); window.removeEventListener("pointerdown", interrupt, true); window.removeEventListener("keydown", interrupt, true); window.removeEventListener("beforeinput", interrupt, true); diff --git a/apps/web/test/go-gaps.ts b/apps/web/test/go-gaps.ts index 6d09f16..01a7445 100644 --- a/apps/web/test/go-gaps.ts +++ b/apps/web/test/go-gaps.ts @@ -11,7 +11,7 @@ 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", ], - "fixture tool: web-server.ts scripts a gated, file-publishing test tool; Go serve has no counterpart and the fixture scripts Pi's ls": + "fixture tool: web-server.ts scripts a gated, file-publishing test tool; the Go fixture's echo tool publishes no files": [ "Bot identity stays consistent and image previews work in drafts and history", "attachment retry keeps its request and draft after a lost receipt", @@ -37,10 +37,6 @@ export const goGaps: Record = { "shared approval cards: the Go fixture cannot open an approval request": [ "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", - "monitoring stays quiet, delivers one result and opens the native Work record", - ], "MCP apps: Go has no application catalog, connection runner, or OAuth callback composed into serve": [ "Apps completes and cancels browser OAuth with stored state", diff --git a/apps/web/test/workspace.spec.ts b/apps/web/test/workspace.spec.ts index f25ed53..6aed92b 100644 --- a/apps/web/test/workspace.spec.ts +++ b/apps/web/test/workspace.spec.ts @@ -2453,6 +2453,8 @@ test("Work follows a native turn, opens its record and preserves it after stop a await expect(dialog).toContainText("检查 Work 工作记录"); await page.keyboard.press("Escape"); await expect(card.locator(".work-open")).toBeFocused(); + worker.send("wait-model"); + await once(worker, "message"); await card.getByRole("button", { name: "停止执行", exact: true }).click(); await expect(card).toContainText("已停止"); await expect(dialog).not.toBeVisible(); diff --git a/internal/cli/serve.go b/internal/cli/serve.go index aa0aa25..72aed80 100644 --- a/internal/cli/serve.go +++ b/internal/cli/serve.go @@ -61,7 +61,11 @@ func serve(ctx context.Context, args []string, stdout io.Writer) error { contractDir := flags.String("contract", "contracts/api", "API contract directory") headless := flags.Bool("headless", false, "serve only the API, without the web UI") dataDir := flags.String("data", "data", "data directory, unless a hosting config sets one") - piExtension := flags.String("pi-extension", "", "Pi extension (pi-tools.mjs) that enables chat through pi --mode rpc") + var piExtensions []string + flags.Func("pi-extension", "Pi extension (pi-tools.mjs) that enables chat through pi --mode rpc; repeat to load more", func(path string) error { + piExtensions = append(piExtensions, path) + return nil + }) if err := flags.Parse(args); err != nil { return err } @@ -168,13 +172,14 @@ func serve(ctx context.Context, args []string, stdout io.Writer) error { // Work services shared by the RPC layer and the product tools below. memorySvc := memory.NewService(records, nil) routineSvc := routines.NewService(records, nil) + routineSvc.Confirm = approvals.Request skillSvc := skills.NewService(records, os.DirFS(filepath.Join(filesRoot, "skills")), catalog.Workspace) skillSvc.UsePackageDir(filepath.Join(filesRoot, "skills")) work := server.Work{Memory: memorySvc, Routines: routineSvc, Skills: skillSvc} var runtime *agent.Runtime - if *piExtension != "" { + if len(piExtensions) > 0 { // An idle Bot has no Pi: each closes with the last session of its task. - engine := pi.New(pi.Config{Extensions: []string{*piExtension}, IdleTimeout: -1, LocalModels: true, + engine := pi.New(pi.Config{Extensions: piExtensions, IdleTimeout: -1, LocalModels: true, SessionDir: filepath.Join(*dataDir, "pi", "sessions"), StateDir: filepath.Join(*dataDir, "pi", "state")}) defer engine.Close() registry, err := productTools(records, routineSvc, skillSvc, catalog.Handoff(approvals)) diff --git a/internal/engine/pi/engine.go b/internal/engine/pi/engine.go index 3a8e52a..0b78a16 100644 --- a/internal/engine/pi/engine.go +++ b/internal/engine/pi/engine.go @@ -219,12 +219,15 @@ func (e *Engine) agentDir() string { } // extensions returns the Pi flags that load the packaged approval/tool -// extension. Sessions fail closed: none are launched without one readable file. +// extension between native tool search and native MCP, with discovery off, as +// worker.mjs does. Sessions fail closed: none are launched without one +// readable file. func (e *Engine) extensions() ([]string, error) { if len(e.config.Extensions) == 0 { return nil, errors.New("pi: approval/tool extension is not configured") } - args := make([]string, 0, 2*len(e.config.Extensions)) + args := make([]string, 0, 2*len(e.config.Extensions)+5) + args = append(args, "--no-extensions", "--extension", "builtin:tool-search") for _, path := range e.config.Extensions { info, err := os.Stat(path) if err != nil { @@ -235,7 +238,7 @@ func (e *Engine) extensions() ([]string, error) { } args = append(args, "--extension", path) } - return args, nil + return append(args, "--extension", "builtin:mcp"), nil } // transient runs one Pi without a session for a short exchange and stops it. diff --git a/internal/routines/confirm.go b/internal/routines/confirm.go new file mode 100644 index 0000000..82dcbec --- /dev/null +++ b/internal/routines/confirm.go @@ -0,0 +1,186 @@ +package routines + +import ( + "cmp" + "context" + "fmt" + "regexp" + "slices" + "strconv" + "strings" + "time" + + "github.com/Personed/Persona/internal/approval" +) + +var ( + actionLabels = map[string]string{ + "create": "创建", "update": "修改", "pause": "暂停", + "resume": "恢复", "run_now": "立即执行", "delete": "删除", + } + weekdays = []string{"周日", "周一", "周二", "周三", "周四", "周五", "周六"} + expressionPattern = regexp.MustCompile(`^(\d{1,2}) (\d{1,2}) \* \* (\*|1-5|[0-6])$`) +) + +// confirm asks the user to approve a Bot's routine change on the routine card, +// as Routines.manage in packages/agent/src/work/routines.ts does. A repeated +// request ID needs no answer, since Manage returns the stored routine. +func (s *Service) confirm(ctx context.Context, botID int64, change Change, requestID string) (bool, error) { + if s.Confirm == nil { + return false, &Error{BadRequest, "确认服务尚未启动。"} + } + var doc document + if _, err := s.read(ctx, DocKind, &doc); err != nil { + return false, err + } + index := slices.IndexFunc(doc.Items, func(item Routine) bool { + return item.BotID == botID && (item.RequestID == requestID || change.Action != "create" && item.ID == change.ID) + }) + var current *Routine + if index >= 0 { + if doc.Items[index].RequestID == requestID { + return true, nil + } + current = &doc.Items[index] + } + if change.Action != "create" && current == nil { + return false, &Error{NotFound, "定时任务不存在。"} + } + if current != nil && (change.Revision == nil || *change.Revision != current.Revision) { + return false, &Error{Conflict, "内容已更新,请刷新后重试。"} + } + input := Routine{BotID: botID} + if current != nil { + input = *current + } + if change.Title != nil { + input.Title = *change.Title + } + if change.Instructions != nil { + input.Instructions = *change.Instructions + } + if change.Schedule != nil { + input.Schedule = *change.Schedule + } + if change.SkillIDs != nil { + input.SkillIDs = change.SkillIDs + } + if change.Delivery != "" { + input.Delivery = change.Delivery + } + if change.Condition != nil { + input.Condition = *change.Condition + } + if change.ExecutionMs != nil { + input.ExecutionMs = *change.ExecutionMs + } + if change.Action == "create" || change.Action == "update" { + if strings.TrimSpace(input.Title) == "" || strings.TrimSpace(input.Instructions) == "" || input.Schedule.Type == "" { + return false, &Error{BadRequest, "缺少名称、要求或执行时间。"} + } + if err := input.Schedule.Validate(s.now()); err != nil { + return false, err + } + } + fields := routineFields(input) + var previous []approval.Field + if current != nil { + previous = routineFields(*current) + } + if change.Action == "update" && input.Title != current.Title { + fields = append([]approval.Field{{Label: "任务名称", Value: input.Title}}, fields...) + previous = append([]approval.Field{{Label: "任务名称", Value: current.Title}}, previous...) + } + if len(input.SkillIDs) > 0 || current != nil && len(current.SkillIDs) > 0 { + var skills struct { + Items []skill `json:"items"` + } + if _, err := s.read(ctx, skillsDocKind, &skills); err != nil { + return false, err + } + names := func(ids []string) string { + labels := make([]string, len(ids)) + for i, id := range ids { + labels[i] = id + if at := slices.IndexFunc(skills.Items, func(item skill) bool { return item.ID == id }); at >= 0 { + labels[i] = skills.Items[at].Name + } + } + return cmp.Or(strings.Join(labels, "、"), "未绑定") + } + fields = append(fields, approval.Field{Label: "使用技能", Value: names(input.SkillIDs)}) + var before []string + if current != nil { + before = current.SkillIDs + } + previous = append(previous, approval.Field{Label: "使用技能", Value: names(before)}) + } + if change.Action == "update" { + changed := fields[:0] + for _, field := range fields { + at := slices.IndexFunc(previous, func(item approval.Field) bool { return item.Label == field.Label }) + switch { + case at < 0: + changed = append(changed, field) + case previous[at].Value != field.Value: + changed = append(changed, approval.Field{Label: field.Label, Value: previous[at].Value + " → " + field.Value}) + } + } + fields = changed + } + detail := input.Instructions + if change.Action == "update" && input.Instructions == current.Instructions { + detail = "" + } + answer, err := s.Confirm(ctx, botID, approval.Request{ + ID: "routine:" + requestID, Title: actionLabels[change.Action] + "定时:" + input.Title, + Detail: detail, Kind: approval.Permission, Fields: fields, + ConfirmLabel: actionLabels[change.Action] + "任务", + }) + return answer.Allow, err +} + +// routineFields are the card fields of routineFields in routines.ts. +func routineFields(item Routine) []approval.Field { + when := routineTimeLabel(item.Schedule.Expression) + if item.Schedule.Type == Once { + when = item.Schedule.At + if at, err := time.Parse(time.RFC3339, item.Schedule.At); err == nil { + if location, err := time.LoadLocation(item.Schedule.TimeZone); err == nil { + at = at.In(location) + } + when = at.Format("2006/1/2 15:04:05") + } + } + delivery := "每次交付" + if item.Delivery == Conditional { + delivery = "满足条件才通知:" + item.Condition + } + minutes := strconv.FormatFloat(float64(cmp.Or(item.ExecutionMs, DefaultExecutionMs))/60_000, 'f', -1, 64) + return []approval.Field{ + {Label: "执行时间", Value: when}, + {Label: "时区", Value: item.Schedule.TimeZone}, + {Label: "执行期限", Value: minutes + " 分钟(不含等待)"}, + {Label: "交付方式", Value: delivery}, + } +} + +// routineTimeLabel is schedule-label.ts routineTimeLabel. +func routineTimeLabel(expression string) string { + match := expressionPattern.FindStringSubmatch(expression) + if match == nil { + return expression + } + frequency := "每天" + switch weekday := match[3]; weekday { + case "*": + case "1-5": + frequency = "工作日" + default: + day, _ := strconv.Atoi(weekday) + frequency = "每" + weekdays[day] + } + hour, _ := strconv.Atoi(match[2]) + minute, _ := strconv.Atoi(match[1]) + return fmt.Sprintf("%s %02d:%02d", frequency, hour, minute) +} diff --git a/internal/routines/routines.go b/internal/routines/routines.go index 2752bd7..2482055 100644 --- a/internal/routines/routines.go +++ b/internal/routines/routines.go @@ -12,6 +12,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/Personed/Persona/internal/approval" "slices" "strings" "sync" @@ -151,6 +152,9 @@ type Service struct { // OnChange fires once after each routine write; the routine runner uses it // to recompute its next scheduled fire. nil ignores the notification. OnChange func() + // Confirm asks the user to approve a Bot's routine change, the shared + // approval flow's Request. Without it routine_create and routine_manage fail. + Confirm func(ctx context.Context, botID int64, request approval.Request) (approval.Answer, error) store store.Store now func() time.Time diff --git a/internal/routines/routines_test.go b/internal/routines/routines_test.go index 0d7f6f0..e215028 100644 --- a/internal/routines/routines_test.go +++ b/internal/routines/routines_test.go @@ -4,7 +4,9 @@ import ( "context" "encoding/json" "errors" + "github.com/Personed/Persona/internal/approval" "path/filepath" + "slices" "strings" "testing" "time" @@ -258,19 +260,28 @@ func TestTools(t *testing.T) { if err := routines.Register(registry, service); err != nil { t.Fatal(err) } - approved := 0 - approve := func(context.Context, tools.Call, tools.Definition) (bool, error) { + approved, allow := 0, false + var asked approval.Request + service.Confirm = func(_ context.Context, _ int64, request approval.Request) (approval.Answer, error) { approved++ - return true, nil + asked = request + return approval.Answer{Allow: allow}, nil } - call := func(name, callID, input string, approver tools.Approver) (tools.Result, error) { - return registry.Call(ctx, tools.Call{BotID: 1, TaskID: 7, CallID: callID, Name: name, Input: json.RawMessage(input)}, approver) + call := func(name, callID, input string) (tools.Result, error) { + return registry.Call(ctx, tools.Call{BotID: 1, TaskID: 7, CallID: callID, Name: name, Input: json.RawMessage(input)}, nil) } input := `{"title":"Morning brief","instructions":"Summarize unread mail.","schedule":{"type":"cron","expression":"0 9 * * 1-5","timeZone":"Asia/Shanghai"}}` - if _, err := call("routine_create", "c1", input, nil); !errors.Is(err, tools.ErrDenied) { - t.Fatalf("unapproved create = %v", err) + if result, err := call("routine_create", "c1", input); err != nil || result.Content[0].Text != `{"status":"declined"}` { + t.Fatalf("declined create = %+v, %v", result, err) } - result, err := call("routine_create", "c1", input, approve) + wantFields := []approval.Field{{Label: "执行时间", Value: "工作日 09:00"}, {Label: "时区", Value: "Asia/Shanghai"}, + {Label: "执行期限", Value: "15 分钟(不含等待)"}, {Label: "交付方式", Value: "每次交付"}} + if asked.ID != "routine:c1" || asked.Title != "创建定时:Morning brief" || asked.ConfirmLabel != "创建任务" || + asked.Detail != "Summarize unread mail." || !slices.Equal(asked.Fields, wantFields) { + t.Fatalf("create card = %+v", asked) + } + allow = true + result, err := call("routine_create", "c1", input) if err != nil || result.IsError { t.Fatalf("create = %+v, %v", result, err) } @@ -282,7 +293,7 @@ func TestTools(t *testing.T) { t.Fatalf("created = %+v", created) } - result, err = call("routine_list", "c2", `{}`, nil) + result, err = call("routine_list", "c2", `{}`) if err != nil || result.IsError { t.Fatalf("list = %+v, %v", result, err) } @@ -298,13 +309,16 @@ func TestTools(t *testing.T) { t.Fatalf("listed time zone %q is not schedulable: %v", listing.TimeZone, err) } - if result, err := call("routine_manage", "c3", `{"action":"pause","id":"`+created.ID+`"}`, approve); err != nil || !result.IsError { + if result, err := call("routine_manage", "c3", `{"action":"pause","id":"`+created.ID+`"}`); err != nil || !result.IsError { t.Fatalf("manage without revision = %+v, %v", result, err) } - result, err = call("routine_manage", "c4", `{"action":"pause","id":"`+created.ID+`","revision":1}`, approve) + result, err = call("routine_manage", "c4", `{"action":"pause","id":"`+created.ID+`","revision":1}`) if err != nil || result.IsError || !strings.Contains(result.Content[0].Text, `"enabled":false`) { t.Fatalf("pause = %+v, %v", result, err) } + if asked.Title != "暂停定时:Morning brief" || len(asked.Fields) != 4 { + t.Fatalf("pause card = %+v", asked) + } if approved != 3 { t.Fatalf("approvals = %d", approved) } diff --git a/internal/routines/tools.go b/internal/routines/tools.go index 43cab35..ef6ffab 100644 --- a/internal/routines/tools.go +++ b/internal/routines/tools.go @@ -73,7 +73,6 @@ var ( Name: "routine_manage", Description: "Propose a routine change for user confirmation. Read routine_list first. Supply its stable ID and current revision. Update only the fields that must change. Execution time excludes waiting for user input.", InputSchema: json.RawMessage(`{"type":"object","properties":{"action":{"type":"string","enum":["update","pause","resume","run_now","delete"]},"id":{"type":"string"},"revision":{"type":"integer","minimum":0},` + fieldsSchema + `},"required":["action","id","revision"]}`), - Mutates: true, } listDefinition = tools.Definition{ Name: "routine_list", @@ -85,7 +84,6 @@ var ( Name: "routine_create", Description: "Create a routine after user confirmation. Specify an explicit IANA timeZone. Once uses an ISO timestamp with offset. Cron uses five fields. Bind enabled skills by stable ID. An approval card confirms the schedule and instructions.", InputSchema: json.RawMessage(`{"type":"object","properties":{` + fieldsSchema + `},"required":["title","instructions","schedule"]}`), - Mutates: true, } ) @@ -111,7 +109,7 @@ func (s *Service) runCreate(ctx context.Context, call tools.Call) (any, error) { return nil, err } change.Action, change.ID, change.Revision = "create", "", nil - return s.Manage(ctx, call.BotID, change, call.CallID, source(call)) + return s.confirmed(ctx, call, change) } func (s *Service) runManage(ctx context.Context, call tools.Call) (any, error) { @@ -122,6 +120,18 @@ func (s *Service) runManage(ctx context.Context, call tools.Call) (any, error) { if change.Action == "create" || change.ID == "" || change.Revision == nil { return nil, &Error{BadRequest, "参数无效:需要 action、id 和 revision。"} } + return s.confirmed(ctx, call, change) +} + +// confirmed applies a Bot's change once the user approves it. +func (s *Service) confirmed(ctx context.Context, call tools.Call, change Change) (any, error) { + allowed, err := s.confirm(ctx, call.BotID, change, call.CallID) + if err != nil { + return nil, err + } + if !allowed { + return map[string]string{"status": "declined"}, nil + } return s.Manage(ctx, call.BotID, change, call.CallID, source(call)) } From a3851ae84961ba8de9ef51d99926cf9dffa61b14 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 20:18:11 +0000 Subject: [PATCH 07/14] Group routines imports for goimports Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- internal/routines/routines.go | 3 ++- internal/routines/routines_test.go | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/internal/routines/routines.go b/internal/routines/routines.go index 2482055..3767127 100644 --- a/internal/routines/routines.go +++ b/internal/routines/routines.go @@ -12,13 +12,14 @@ import ( "encoding/json" "errors" "fmt" - "github.com/Personed/Persona/internal/approval" "slices" "strings" "sync" "time" "unicode/utf16" + "github.com/Personed/Persona/internal/approval" + "github.com/Personed/Persona/internal/store" ) diff --git a/internal/routines/routines_test.go b/internal/routines/routines_test.go index e215028..5e1ca7f 100644 --- a/internal/routines/routines_test.go +++ b/internal/routines/routines_test.go @@ -4,13 +4,14 @@ import ( "context" "encoding/json" "errors" - "github.com/Personed/Persona/internal/approval" "path/filepath" "slices" "strings" "testing" "time" + "github.com/Personed/Persona/internal/approval" + "github.com/Personed/Persona/internal/routines" "github.com/Personed/Persona/internal/store" "github.com/Personed/Persona/internal/tools" From e03f048c208905efaedff23f69e4515fca8f6a69 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 20:23:31 +0000 Subject: [PATCH 08/14] Document routine confirmation and repeatable -pi-extension Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1442f5f..8fa9bb8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,9 +49,9 @@ Pi Durable 1.4.0 stores Bot tasks. Native Harness processes own model loops. Per - `internal/mcpserver` serves the `internal/tools` registry to Pi as one loopback MCP endpoint per Bot task. Add product tools by registering them in the registry; mutating tools set `Mutates` so calls pass the shared approver. A call's `CallID` is its MCP session and JSON-RPC request ID, and a redelivered request gets the recorded outcome. `internal/store/storetest` is the in-memory store for tests until the SQLite store lands. The gateway bounds each result's text for the model, holds the latest complete results, and serves `query_result` over them itself. `internal/history` owns `conversation_read`; a Bot's ID is its conversation ID. `persona serve` composes the registry in `productTools` (`internal/cli/serve.go`), and the runtime declares its tools in each session's `persona-tools.json` and the engine prompt document. - `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 `.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. +- `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 `.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`, repeatable; Pi starts with `--no-extensions`, `builtin:tool-search`, the listed extensions, and `builtin:mcp`, like `worker.mjs`); `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. The runtime asks Pi's approval and `ask_user` requests through `internal/approval` and answers Pi with the reply; a stopped task expires the card and cancels Pi's dialog. -- `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/routines` owns the `persona.routines` document and the `routine_*` tools. Route routine changes through its Service. `routine_create` and `routine_manage` do not set `Mutates`: `Service.Confirm` shows the routine card (`routine:`, schedule, time zone, execution limit, delivery, skills) like `packages/agent/src/work/routines.ts`, and a declined change returns `{"status":"declined"}`. 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::`, as `packages/agent/src/mcp/connections.ts`. `internal/server.RegisterMCP` serves them. Checks and sign-in run through `Service.Runner` and native connections through `Service.Catalog`, which the computer runtime supplies; `mcp.login` needs the OAuth callback URL. - `PERSONA_WEB_SERVER=go` runs the web Playwright suite against `persona serve` through `apps/api/test/fixtures/go-server.ts` (`PERSONA_GO_BIN` names a built binary; otherwise it runs `go build`). `playwright.config.ts` leaves out the tests in `apps/web/test/go-gaps.ts`; remove a title when its gap closes. From 73a6957f902df64fd849c9ff5445532e43919301 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 20:30:40 +0000 Subject: [PATCH 09/14] Gate the Go fixture tool like web-server.ts and wait for the typing exit sample Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/api/test/fixtures/go-server.ts | 8 ++------ apps/web/test/chat.spec.ts | 12 ++++++++++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/apps/api/test/fixtures/go-server.ts b/apps/api/test/fixtures/go-server.ts index b5354a9..f1b9350 100644 --- a/apps/api/test/fixtures/go-server.ts +++ b/apps/api/test/fixtures/go-server.ts @@ -135,12 +135,8 @@ async function complete( const model = String(body.model ?? ""); const aborted = new AbortController(); response.on("close", () => aborted.abort()); - // 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; - if (waiting === toolGate) toolGate = undefined; - else gate = undefined; + const waiting = gate; + gate = undefined; if (waiting) { aborted.signal.addEventListener("abort", () => waiting.resolve(), { once: true, diff --git a/apps/web/test/chat.spec.ts b/apps/web/test/chat.spec.ts index 4d4f743..0ce1da8 100644 --- a/apps/web/test/chat.spec.ts +++ b/apps/web/test/chat.spec.ts @@ -3320,6 +3320,18 @@ test("message insertion moves typing continuously and completion fades it out", ); await page.evaluate(() => document.activeViewTransition?.finished); await expect(typing).toHaveCount(0); + // The typing row can leave in a transition after the reply's, so wait for + // the sampler to see its exit. + await expect + .poll(() => + page.evaluate( + () => + ( + window as unknown as { messageMotion: { frames: Sample[] } } + ).messageMotion.frames.filter((frame) => frame.exit).length, + ), + ) + .toBeGreaterThan(2); const frames = await page.evaluate(() => { const state = ( window as unknown as { From 5ff4f56aad91a127793a089cd41b00d571858bb3 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 20:48:31 +0000 Subject: [PATCH 10/14] Skip panel view transitions on input events, as #88 does Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/web/src/features/shell/workspace.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/web/src/features/shell/workspace.tsx b/apps/web/src/features/shell/workspace.tsx index 242dffe..974bc04 100644 --- a/apps/web/src/features/shell/workspace.tsx +++ b/apps/web/src/features/shell/workspace.tsx @@ -86,6 +86,7 @@ export function Workspace({ window.addEventListener("pointerdown", interrupt, true); window.addEventListener("keydown", interrupt, true); window.addEventListener("beforeinput", interrupt, true); + window.addEventListener("input", interrupt, true); window.addEventListener("pointerup", release, true); window.addEventListener("pointercancel", release, true); return () => { @@ -95,6 +96,7 @@ export function Workspace({ window.removeEventListener("pointerdown", interrupt, true); window.removeEventListener("keydown", interrupt, true); window.removeEventListener("beforeinput", interrupt, true); + window.removeEventListener("input", interrupt, true); }; }, [sizing.root]); const dragChange = useCallback( From 58e04c317c3ac17ce816a92f508abb7acb6a933f Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 21:42:12 +0000 Subject: [PATCH 11/14] Keep conditional routine turns out of chat previews Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- internal/agent/docs.go | 2 ++ internal/agent/projection.go | 21 ++++++++++++++++----- internal/agent/runtime.go | 10 +++++++++- internal/agent/runtime_test.go | 29 +++++++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 6 deletions(-) diff --git a/internal/agent/docs.go b/internal/agent/docs.go index 14b32d5..701ab98 100644 --- a/internal/agent/docs.go +++ b/internal/agent/docs.go @@ -153,6 +153,8 @@ type Draft struct { ToolName string `json:"toolName,omitempty"` IsError *bool `json:"isError,omitempty"` ToolStatus string `json:"toolStatus,omitempty"` + Hidden bool `json:"hidden,omitempty"` + Routine json.RawMessage `json:"routine,omitempty"` Native json.RawMessage `json:"native,omitempty"` ParentID string `json:"parentId,omitempty"` Activity json.RawMessage `json:"activity,omitempty"` diff --git a/internal/agent/projection.go b/internal/agent/projection.go index af6fbf7..d03b544 100644 --- a/internal/agent/projection.go +++ b/internal/agent/projection.go @@ -18,11 +18,12 @@ const flushDelay = 50 * time.Millisecond // document, EngineProjection in projection.ts. Events of a turn that is no // longer active are dropped. type projection struct { - r *Runtime - bot int64 - task int64 - turn string - entry store.EntryID + r *Runtime + bot int64 + task int64 + turn string + entry store.EntryID + routine *RoutineRun mu sync.Mutex write sync.Mutex @@ -85,6 +86,16 @@ func (p *projection) emit(ctx context.Context, event map[string]any) { } received := now message = &Draft{ID: messageID, TurnID: p.turn, Role: role, Content: []map[string]any{}, Timestamp: now, ReceivedAt: &received} + if p.routine != nil && p.routine.Delivery == "conditional" { + message.Hidden = true + message.Routine, _ = json.Marshal(map[string]any{ + "runId": p.routine.ID, + "title": p.routine.Title, + "scheduledAt": p.routine.ScheduledAt, + "turnId": p.turn, + "delivery": p.routine.Delivery, + }) + } p.messages = append(p.messages, message) } if native, ok := event["native"]; ok && native != nil { diff --git a/internal/agent/runtime.go b/internal/agent/runtime.go index d6a8e76..0c59e95 100644 --- a/internal/agent/runtime.go +++ b/internal/agent/runtime.go @@ -533,6 +533,7 @@ func (r *Runtime) runEngine(ctx context.Context, bot int64, w *worker, taskID st var drafts []*Draft var config EngineConfig var sessionID string + var routine *RoutineRun err = r.h.Commit(ctx, func(tx *Tx) error { doc, err := Edit(tx, EngineDoc, bot) if err != nil { @@ -556,6 +557,13 @@ func (r *Runtime) runEngine(ctx context.Context, bot int64, w *worker, taskID st } } drafts, config = doc.Drafts, doc.Config + if in.RoutineRunID != "" { + var err error + routine, err = r.routineRun(tx, bot, in.RoutineRunID) + if err != nil { + return err + } + } if doc.SessionID != nil { sessionID = *doc.SessionID } @@ -564,7 +572,7 @@ func (r *Runtime) runEngine(ctx context.Context, bot int64, w *worker, taskID st if err != nil { return } - p := &projection{r: r, bot: bot, task: id, turn: in.TurnID, entry: in.EntryID, messages: drafts} + p := &projection{r: r, bot: bot, task: id, turn: in.TurnID, entry: in.EntryID, routine: routine, messages: drafts} failure := r.executeEngine(ctx, bot, w, id, in, config, sessionID, p) p.flush(context.Background()) reason := failure diff --git a/internal/agent/runtime_test.go b/internal/agent/runtime_test.go index f917714..2fafc51 100644 --- a/internal/agent/runtime_test.go +++ b/internal/agent/runtime_test.go @@ -585,3 +585,32 @@ func TestRuntimeGatewayServesRegistry(t *testing.T) { t.Errorf("prompt = %s", doc.Prompt) } } + +func TestConditionalRoutineStaysOutOfPreview(t *testing.T) { + ctx := context.Background() + a, rt := runtimeFor(t, true, scriptEngine{frames: strings.Split(answerFrames, "\n")}) + bot := int64(a.Root) + if err := a.Harness.Commit(ctx, func(tx *Tx) error { + doc, err := Create(tx, RoutinesDoc, 0) + if err != nil { + return err + } + doc.Runs = append(doc.Runs, RoutineRun{ID: "run-1", RoutineID: "routine-1", BotID: bot, + Title: "version check", ScheduledAt: 7, RequestID: "routine:r1:7", Delivery: "conditional"}) + return nil + }); err != nil { + t.Fatal(err) + } + if _, err := rt.Submit(ctx, SendInput{BotID: bot, Text: "Scheduled task: version check\nUse routine_report once after checking evidence.", + DisplayText: "定时任务:version check", RequestID: "routine:r1:7", Source: "routine", RoutineRunID: "run-1"}); err != nil { + t.Fatal(err) + } + idle(t, rt) + preview, _, err := botPreview(ctx, a.Harness.Store(), bot, "bot instructions") + if err != nil { + t.Fatal(err) + } + if preview != "bot instructions" { + t.Fatalf("preview = %q", preview) + } +} From eaf3f2bfab75127d0c0406a1de8354785a6ac877 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 21:59:24 +0000 Subject: [PATCH 12/14] Store conditional routine run messages hidden, like projection.ts, so silent runs keep the Bot preview Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- internal/agent/docs.go | 2 ++ internal/agent/projection.go | 19 +++++++++++++++++++ internal/agent/runtime.go | 2 +- internal/agent/runtime_test.go | 26 ++++++++++++++++++++++++++ 4 files changed, 48 insertions(+), 1 deletion(-) diff --git a/internal/agent/docs.go b/internal/agent/docs.go index 14b32d5..58964c7 100644 --- a/internal/agent/docs.go +++ b/internal/agent/docs.go @@ -157,6 +157,8 @@ type Draft struct { ParentID string `json:"parentId,omitempty"` Activity json.RawMessage `json:"activity,omitempty"` Attachments json.RawMessage `json:"attachments,omitempty"` + Routine json.RawMessage `json:"routine,omitempty"` + Hidden bool `json:"hidden,omitempty"` } func initialEngine() EngineState { diff --git a/internal/agent/projection.go b/internal/agent/projection.go index af6fbf7..ba07bc5 100644 --- a/internal/agent/projection.go +++ b/internal/agent/projection.go @@ -23,6 +23,9 @@ type projection struct { task int64 turn string entry store.EntryID + // routineRun is the routine run the turn executes; a conditional run's + // messages are stored hidden, as projection.ts does. + routineRun string mu sync.Mutex write sync.Mutex @@ -232,7 +235,16 @@ func (p *projection) flush(ctx context.Context) { return err } } + run, err := p.run(tx) + if err != nil { + return err + } for _, draft := range drafts { + if run != nil && run.Delivery == "conditional" { + draft.Routine, _ = json.Marshal(map[string]any{"runId": run.ID, "title": run.Title, + "scheduledAt": run.ScheduledAt, "turnId": p.turn, "delivery": run.Delivery}) + draft.Hidden = true + } index := slices.IndexFunc(doc.Drafts, func(item *Draft) bool { return item.ID == draft.ID }) if index < 0 { doc.Drafts = append(doc.Drafts, draft) @@ -246,6 +258,13 @@ func (p *projection) flush(ctx context.Context) { } } +func (p *projection) run(tx *Tx) (*RoutineRun, error) { + if p.routineRun == "" { + return nil, nil + } + return p.r.routineRun(tx, p.bot, p.routineRun) +} + func (p *projection) apply(tx *Tx, doc *EngineState, event map[string]any) error { switch event["type"] { case "usage": diff --git a/internal/agent/runtime.go b/internal/agent/runtime.go index d6a8e76..92b489f 100644 --- a/internal/agent/runtime.go +++ b/internal/agent/runtime.go @@ -564,7 +564,7 @@ func (r *Runtime) runEngine(ctx context.Context, bot int64, w *worker, taskID st if err != nil { return } - p := &projection{r: r, bot: bot, task: id, turn: in.TurnID, entry: in.EntryID, messages: drafts} + p := &projection{r: r, bot: bot, task: id, turn: in.TurnID, entry: in.EntryID, routineRun: in.RoutineRunID, messages: drafts} failure := r.executeEngine(ctx, bot, w, id, in, config, sessionID, p) p.flush(context.Background()) reason := failure diff --git a/internal/agent/runtime_test.go b/internal/agent/runtime_test.go index f917714..30bb396 100644 --- a/internal/agent/runtime_test.go +++ b/internal/agent/runtime_test.go @@ -585,3 +585,29 @@ func TestRuntimeGatewayServesRegistry(t *testing.T) { t.Errorf("prompt = %s", doc.Prompt) } } + +func TestRuntimeConditionalRoutineRunKeepsPreview(t *testing.T) { + for delivery, want := range map[string]string{"conditional": "instructions", "always": "Hi there"} { + ctx := context.Background() + a, rt := runtimeFor(t, true, scriptEngine{frames: strings.Split(answerFrames, "\n")}) + bot := int64(a.Root) + if err := a.Harness.Commit(ctx, func(tx *Tx) error { + doc, err := Edit(tx, RoutinesDoc, 0) + if err != nil { + return err + } + doc.Runs = append(doc.Runs, RoutineRun{ID: "run1", BotID: bot, Title: "Monitor", RequestID: "routine:run1", Delivery: delivery}) + return nil + }); err != nil { + t.Fatal(err) + } + if _, err := rt.Submit(ctx, SendInput{BotID: bot, Text: "Scheduled task", RequestID: "routine:run1", + Source: "routine", RoutineRunID: "run1"}); err != nil { + t.Fatal(err) + } + idle(t, rt) + if got, _, err := botPreview(ctx, a.Harness.Store(), bot, "instructions"); err != nil || got != want { + t.Fatalf("%s preview = %q, %v; want %q", delivery, got, err, want) + } + } +} From 8b2929b04888498d18b4cfe9b911ed296b513113 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Mon, 23 Nov 2026 22:00:41 +0000 Subject: [PATCH 13/14] Format the Go fixture Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/api/test/fixtures/go-server.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/api/test/fixtures/go-server.ts b/apps/api/test/fixtures/go-server.ts index 878aaed..570a11b 100644 --- a/apps/api/test/fixtures/go-server.ts +++ b/apps/api/test/fixtures/go-server.ts @@ -402,7 +402,6 @@ service.on("exit", () => process.exit(1)); await configure(); process.send?.({ type: "ready", port, toolName }); - // web-server.ts opens every Bot with the faux model and prepares its engine; // here each Bot is configured through engines.configure instead. async function call(path: string, json: unknown) { From e616863df26e7d6ecd76a5d51cf110cdfe4d3758 Mon Sep 17 00:00:00 2001 From: stoltembergg Date: Tue, 24 Nov 2026 06:35:55 +0000 Subject: [PATCH 14/14] Format the merged specs and drop the non-null assertion Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/web/test/chat.spec.ts | 4 +--- apps/web/test/workspace.spec.ts | 3 ++- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/apps/web/test/chat.spec.ts b/apps/web/test/chat.spec.ts index c29c5da..0ce1da8 100644 --- a/apps/web/test/chat.spec.ts +++ b/apps/web/test/chat.spec.ts @@ -3938,9 +3938,7 @@ test("composer menu adds task materials, keeps drafts, and fits both themes", as await add.click(); const chooser = page.waitForEvent("filechooser"); await page.getByRole("menuitem", { name: "添加图片", exact: true }).click(); - await ( - await chooser - ).setFiles({ + await (await chooser).setFiles({ name: "tiny.png", mimeType: "image/png", buffer: png(1, 1), diff --git a/apps/web/test/workspace.spec.ts b/apps/web/test/workspace.spec.ts index 928a85a..f040b51 100644 --- a/apps/web/test/workspace.spec.ts +++ b/apps/web/test/workspace.spec.ts @@ -515,7 +515,8 @@ test("sending paints the outgoing message before the network receipt", async ({ ) .toBe(1); const duration = await page.evaluate( - () => performance.getEntriesByName("send-paint")[0]!.duration, + () => + performance.getEntriesByName("send-paint")[0]?.duration ?? Number.NaN, ); console.log( `send paint with 320 history messages and 4x CPU: ${duration.toFixed(1)}ms`,