diff --git a/AGENTS.md b/AGENTS.md index 6492bd6..2fa254b 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`, which `computers.Catalog.MCPRunner` supplies as a fresh worker on the connection's computer, and native connections through `Service.Catalog`, which stays unset until the worker serves native MCP reads. `persona serve` passes `/mcp/oauth/callback` to `mcp.login` and completes it through `Config.MCP`. - `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. diff --git a/apps/web/src/features/shell/workspace.tsx b/apps/web/src/features/shell/workspace.tsx index eccd36e..974bc04 100644 --- a/apps/web/src/features/shell/workspace.tsx +++ b/apps/web/src/features/shell/workspace.tsx @@ -61,10 +61,25 @@ 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. @@ -72,7 +87,12 @@ export function Workspace({ 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 () => { + 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/chat.spec.ts b/apps/web/test/chat.spec.ts index 013e554..0ce1da8 100644 --- a/apps/web/test/chat.spec.ts +++ b/apps/web/test/chat.spec.ts @@ -3320,9 +3320,18 @@ test("message insertion moves typing continuously and completion fades it out", ); await page.evaluate(() => document.activeViewTransition?.finished); await expect(typing).toHaveCount(0); - // Completion can arrive while the reply's own transition runs, so the exit - // follows in a transition of its own. - await page.evaluate(() => document.activeViewTransition?.finished); + // 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 { diff --git a/apps/web/test/go-gaps.ts b/apps/web/test/go-gaps.ts index 097e2d3..56d3920 100644 --- a/apps/web/test/go-gaps.ts +++ b/apps/web/test/go-gaps.ts @@ -39,7 +39,6 @@ export const goGaps: Record = { ], "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", ], "native Harness controls: unhosted persona serve offers no device pairing": [ "native Harness controls persist and client accounts retain model access", diff --git a/apps/web/test/workspace.spec.ts b/apps/web/test/workspace.spec.ts index cc9c463..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`, @@ -2453,6 +2454,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/agent/docs.go b/internal/agent/docs.go index 8bb9a50..b959b16 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"` @@ -212,9 +214,9 @@ 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"} RoutinesDoc = Doc[RoutinesState]{Kind: "persona.routines", Scope: "session"} SkillsDoc = Doc[SkillsState]{Kind: "persona.skills", Scope: "session"} - RequestsDoc = Doc[ComputerRequests]{Kind: "persona.computer-requests", Scope: "conversation", History: "latest", Fork: "initial"} ) // SkillItem is the part of a persona.skills record the prompt section reads. 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) + } +} diff --git a/internal/cli/serve.go b/internal/cli/serve.go index 5629340..b03abb5 100644 --- a/internal/cli/serve.go +++ b/internal/cli/serve.go @@ -62,7 +62,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 } @@ -173,9 +177,9 @@ func serve(ctx context.Context, args []string, stdout io.Writer) error { 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.