Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
910a668
Shrink the Go Playwright gaps: computer stubs, Pi model controls, fix…
Personed Nov 23, 2026
64d7903
Un-exclude structured messages and kill serve's process group with th…
Personed Nov 23, 2026
198b71f
Ask Pi's native questions through the shared approval cards
Personed Nov 23, 2026
ecefe17
Record the remaining shared approval gap and document native question…
Personed Nov 23, 2026
04e407a
Serve routine, skill, and history product tools to Pi from persona serve
Personed Nov 23, 2026
61764e8
Merge main into devin/1795461052-go-server-gaps
Personed Nov 23, 2026
8f6cc5b
Merge remote-tracking branch 'origin/devin/1795458963-serve-product-t…
Personed Nov 23, 2026
b69b1ed
Open native Work records under Go: Pi native MCP, routine confirmatio…
Personed Nov 23, 2026
a3851ae
Group routines imports for goimports
Personed Nov 23, 2026
e03f048
Document routine confirmation and repeatable -pi-extension
Personed Nov 23, 2026
73a6957
Gate the Go fixture tool like web-server.ts and wait for the typing e…
Personed Nov 23, 2026
5ff4f56
Skip panel view transitions on input events, as #88 does
Personed Nov 23, 2026
072362f
Merge main into devin/work-records-go-v2
Personed Nov 23, 2026
58e04c3
Keep conditional routine turns out of chat previews
Personed Nov 23, 2026
eaf3f2b
Store conditional routine run messages hidden, like projection.ts, so…
Personed Nov 23, 2026
02f9107
Merge main into devin/work-records-go-v2
Personed Nov 23, 2026
8b2929b
Format the Go fixture
Personed Nov 23, 2026
7be8ac7
Merge the pushed conditional-preview fix
Personed Nov 23, 2026
da6c84d
Merge remote-tracking branch 'origin/main' into devin/work-records-go-v2
Personed Nov 24, 2026
e616863
Format the merged specs and drop the non-null assertion
Personed Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<database>.files` layout under `persona-go.sqlite.files` until the importer copies the TypeScript history. `persona serve` without a hosting config still runs behind the hosted origin guard, as the TypeScript service always does. `internal/server.RegisterAgent` serves its procedures, and chat input only when given a Runtime (`persona serve -pi-extension`); `internal/server.RegisterEngines` serves the remaining models and engines procedures, `persona serve` lists models from `agent.LocalModels` (the local servers `internal/localmodels` detects) until a cloud provider catalog is ported, with a native runtime `engines.get`, `engines.inspect`, `engines.configure`, and `engines.select` serve Pi on the service computer (a ready inspection is saved in `persona.native-models`, so `engines.get` keeps a Bot's catalog across restarts), and the other engine runtime procedures answer `NOT_IMPLEMENTED` for an existing Bot until native engine connections and controls are composed; `internal/server/contract_test.go` requires every fixture of a registered procedure to match, except the listed skips.
- `internal/agent` owns Bots, the chat projection, the chat runtime, and Bot files, as `packages/agent` does. `Runtime.Submit` admits chat input as a submission and a task in one commit; a per-Bot worker runs the tasks in order, each in an `internal/engine` session that closes when the task ends, and `Stop` aborts the session and settles the turn without waiting for it. It reads and writes the pi-durable and Persona documents (`persona.bots`, `pi.agent`, `pi.live`, `persona.engine`) by kind and scope through `Harness.Commit`, and keeps files in the TypeScript `<database>.files` layout under `persona-go.sqlite.files` until the importer copies the TypeScript history. `persona serve` without a hosting config still runs behind the hosted origin guard, as the TypeScript service always does. `internal/server.RegisterAgent` serves its procedures, and chat input only when given a Runtime (`persona serve -pi-extension`, 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:<call ID>`, 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:<id>:<uuid>`, as `packages/agent/src/mcp/connections.ts`. `internal/server.RegisterMCP` serves them. Checks and sign-in run through `Service.Runner`, which `computers.Catalog.MCPRunner` supplies as a fresh worker on the connection's computer, and native connections through `Service.Catalog`, which stays unset until the worker serves native MCP reads. `persona serve` passes `<public URL>/mcp/oauth/callback` to `mcp.login` and completes it through `Config.MCP`.
- `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.
Expand Down
22 changes: 21 additions & 1 deletion apps/web/src/features/shell/workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,38 @@ 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("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);
Expand Down
15 changes: 12 additions & 3 deletions apps/web/test/chat.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 0 additions & 1 deletion apps/web/test/go-gaps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ export const goGaps: Record<string, string[]> = {
],
"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",
Expand Down
5 changes: 4 additions & 1 deletion apps/web/test/workspace.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down Expand Up @@ -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();
Expand Down
4 changes: 3 additions & 1 deletion internal/agent/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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.
Expand Down
21 changes: 16 additions & 5 deletions internal/agent/projection.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
10 changes: 9 additions & 1 deletion internal/agent/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}
Expand All @@ -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
Expand Down
29 changes: 29 additions & 0 deletions internal/agent/runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
10 changes: 7 additions & 3 deletions internal/cli/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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))
Expand Down
9 changes: 6 additions & 3 deletions internal/engine/pi/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Mudança de prazo da rotina oculta na confirmação

Ao alterar pelo chat o prazo de 60 para 90 segundos, o cartão reduz ambos os valores a um minuto. A comparação omite o campo, e o usuário pode aprovar a mudança sem ver o novo prazo.

Learn more

O chat chama routine_manage, que aceita o prazo em milissegundos. Ao preparar o cartão, requestFields divide o prazo por 60.000 com aritmética inteira. Em seguida, diffFields compara os textos e descarta os campos iguais. O executor de rotinas lê o prazo em milissegundos e interrompe a execução pelo valor real, não pelo valor exibido no cartão.

Example: Uma rotina tem prazo de 60 segundos. O usuário pede 90 segundos pelo chat. O cartão representa ambos como um minuto e não mostra a alteração, mas, após a aprovação, a rotina passa a ter 90 segundos.

Recommended fix: Formate o prazo em requestFields sem descartar segundos ou milissegundos. Acrescente um teste de confirmação que altere apenas o prazo de 60 para 90 segundos e verifique que o cartão mostra os dois valores.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}

// transient runs one Pi without a session for a short exchange and stops it.
Expand Down
Loading