Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(mods): restore reliable Goal run lifecycle and completion
new-Beginner652c4067e1d6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2395e5fa6..b8c7bda06 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -168,10 +168,14 @@ jobs:- name: Build host-corerun: cargo build -p host-core --locked- - name: Run staged mode Host/process E2E+ - name: Run staged mode and Goal Host/process E2Eenv:PI_SCRATCH_DIR: ${{ runner.temp }}- run: node scripts/e2e-mode-definitions.mjs+ run: |+ pnpm --filter @pi-desktop/agent-runtime bundle+ node scripts/e2e-mode-definitions.mjs+ node scripts/e2e-goal-run-repairs.mjs+ node scripts/e2e-goal-completion.mjs- name: Run plugin project enumeration Host/process E2Erun: pnpm test:e2e:plugin-projectsdiff --git a/Cargo.lock b/Cargo.lockindex 194a23646..f0ccd5065 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -589,7 +589,7 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"[[package]]name = "host-core"-version = "0.21.0"+version = "0.21.2"dependencies = ["aes-gcm","anyhow",diff --git a/Cargo.toml b/Cargo.tomlindex 69c6dd8b6..68b371522 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -5,7 +5,7 @@ resolver = "2"[workspace.package]edition = "2021"license = "LGPL-3.0-or-later"-version = "0.21.0"+version = "0.21.2"# Release builds ship inside the installer; nothing reads host-core's symbol# table at runtime (panic messages keep their file:line locations), so strip it.diff --git a/apps/desktop/electron/main/agent-host-bridge.ts b/apps/desktop/electron/main/agent-host-bridge.tsindex 08cba74ca..fe9f04fb4 100644--- a/apps/desktop/electron/main/agent-host-bridge.ts+++ b/apps/desktop/electron/main/agent-host-bridge.ts@@ -143,6 +143,7 @@ export function createAgentHostBridge(options: AgentHostBridgeOptions) {const promptRequest = {sessionId: request.sessionId,content: request.content,+ ...(request.startGoal === undefined ? {} : { startGoal: request.startGoal }),...(request.sessionMessageId ? { sessionMessageId: request.sessionMessageId } : {}),...(request.userMessageId ? { messageId: request.userMessageId } : {}),...(request.voiceOrigin ? { voiceOrigin: request.voiceOrigin } : {}),@@ -282,36 +283,45 @@ export function createAgentHostBridge(options: AgentHostBridgeOptions) {/** The desktop's queue operations, all under the owner principal. */const queue = {- async push(request: AgentQueuePushRequest): Promise<QueuedTurnSummary> {- const result = await forIpc(() =>- agentHost.startTurn(DESKTOP_PRINCIPAL, {- sessionId: request.sessionId,- admission: "queue",- ...(request.idempotencyKey ? { idempotencyKey: request.idempotencyKey } : {}),- input: {- text: request.content,- ...(request.sessionMessageId ? { sessionMessageId: request.sessionMessageId } : {}),- ...(request.userMessageId ? { userMessageId: request.userMessageId } : {}),- ...(request.voiceOrigin ? { voiceOrigin: request.voiceOrigin } : {}),- ...(request.attachments ? { attachments: request.attachments } : {}),- },- context: { requestId: `desktop-queue-${Date.now().toString(36)}` },- }),- );+ async push(request: AgentQueuePushRequest, onGoalAccepted?: () => Promise<void>): Promise<QueuedTurnSummary> {+ const params = {+ sessionId: request.sessionId,+ admission: "queue" as const,+ ...(request.idempotencyKey ? { idempotencyKey: request.idempotencyKey } : {}),+ input: {+ text: request.content,+ startGoal: request.startGoal === true,+ ...(request.sessionMessageId ? { sessionMessageId: request.sessionMessageId } : {}),+ ...(request.userMessageId ? { userMessageId: request.userMessageId } : {}),+ ...(request.voiceOrigin ? { voiceOrigin: request.voiceOrigin } : {}),+ ...(request.attachments ? { attachments: request.attachments } : {}),+ },+ context: { requestId: `desktop-queue-${Date.now().toString(36)}` },+ };+ const result = await forIpc(() => request.startGoal+ ? agentHost.enqueueTurn(DESKTOP_PRINCIPAL, params, async () => {+ try {+ await onGoalAccepted?.();+ } catch (error) {+ // Acceptance is already durable. Keep the queued Goal available;+ // dispatch rechecks replacement before starting its new run.+ options.log("warn", "accepted Goal replacement could not interrupt its predecessor", { sessionId: request.sessionId, error: String(error) });+ }+ })+ : agentHost.startTurn(DESKTOP_PRINCIPAL, params));const entry = agentHost.queueEntries(request.sessionId).find((candidate) => candidate.turn.id === result.turn.id);- return entry- ? toQueueSummary(entry)- : {- id: result.turn.id,- sessionId: request.sessionId,- content: request.content,- ...(request.sessionMessageId ? { sessionMessageId: request.sessionMessageId } : {}),- ...(request.userMessageId ? { userMessageId: request.userMessageId } : {}),- ...(request.voiceOrigin ? { voiceOrigin: request.voiceOrigin } : {}),- ...(request.attachments ? { attachments: request.attachments } : {}),- position: 0,- createdAt: new Date().toISOString(),- };+ return entry ? toQueueSummary(entry) : {+ id: result.turn.id,+ sessionId: request.sessionId,+ content: request.content,+ ...(request.startGoal ? { startGoal: true } : {}),+ ...(request.sessionMessageId ? { sessionMessageId: request.sessionMessageId } : {}),+ ...(request.userMessageId ? { userMessageId: request.userMessageId } : {}),+ ...(request.voiceOrigin ? { voiceOrigin: request.voiceOrigin } : {}),+ ...(request.attachments ? { attachments: request.attachments } : {}),+ position: 0,+ createdAt: new Date().toISOString(),+ };},list(sessionId: string): QueuedTurnSummary[] {return agentHost.queueEntries(sessionId).map(toQueueSummary);diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex 8b71ec165..1a3054a09 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -2,6 +2,7 @@ import { expandMcpInvocation } from "../composer-mcp";import { IPC, ErrorCodes, compactionRecordId, composeMentionPrompt, findSkillMentions, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AgentStopSubagentsRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PendingInteractiveRequests, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type VoiceOrigin } from "@pi-desktop/shared";import type { FinishTurn } from "../runtime/plans";import { modeContinuationOrigin, type ModeRunCoordinator, type PreparedModeTurn } from "../runtime/mode-runs";+import { goalPromptMode, goalStartRequested } from "../runtime/goal-start";import { expandSlashInvocation, visionFromModelConfig, type ComposerTemplate } from "@pi-desktop/agent-runtime";import { appendPromptFallbackPaths, durableUserMessageId, preparePromptAttachments, type PreparedPromptAttachment } from "../prompt-attachments";import { resolveSessionReferences } from "../session-references";@@ -52,7 +53,7 @@ export type AgentIpcDependencies = {composerCommandService: Pick<ComposerCommandService, "buildComposerCommands">;loadComposerTemplatesCached: (root: string | null) => Promise<ComposerTemplate[]>;/** Staged mode runs: claim before the sidecar starts a turn (ADR mode-definitions). */- modeRuns: Pick<ModeRunCoordinator, "definitionForPrompt" | "canContinue" | "prepareTurn" | "abandonTurn">;+ modeRuns: Pick<ModeRunCoordinator, "definitionForPrompt" | "canContinue" | "prepareTurn" | "abandonTurn" | "replaceGoal" | "resetGoalInput">;};function rejectNativeAgentOperation(sessionId: string): void {@@ -189,13 +190,24 @@ export function registerAgentIpc({});});+ async function queueGoal(request: AgentQueuePushRequest) {+ if (!agentHostBridge) throw new Error("agent host unavailable");+ await modeRuns.definitionForPrompt("goal");+ return agentHostBridge.queue.push(request, async () => {+ await modeRuns.replaceGoal(request.sessionId);+ await modeRuns.resetGoalInput(request.sessionId);+ });+ }+handle(IPC.invoke.agentPrompt, async (req: AgentPromptRequest) => {// Set only on an in-process request built by the Agent Host bridge for a// Host-started mode run turn; a renderer or plugin request never has it.const modeOrigin = modeContinuationOrigin(req);+ const startGoal = goalStartRequested(req);if (!sidecar) throw new Error("sidecar unavailable");const voiceOrigin = parseVoiceOrigin(req.voiceOrigin);if (req.sessionId.startsWith("native-pi:")) {+ if (startGoal) rejectNativeAgentOperation(req.sessionId);// Desktop-managed MCP servers are not installed in native Pi sessions.if (/^\/mcp:\S/.test(req.content)) expandMcpInvocation(req.content, []);if (voiceOrigin) {@@ -216,6 +228,10 @@ export function registerAgentIpc({});}if (!host) throw new Error("host unavailable");+ if (startGoal && activeTurns.has(req.sessionId)) {+ const entry = await queueGoal({ ...req, userMessageId: req.messageId });+ return { accepted: true, turnId: entry.id };+ }const releaseSessionOperation = await acquireSessionOperation(req.sessionId);try {const sessionMessage = await resolveSessionMessageInput(host, req);@@ -360,6 +376,7 @@ export function registerAgentIpc({// A staged mode claims its run for this durable turn before anything runs;// the sidecar then executes the run's own definition snapshot.+ const promptMode = goalPromptMode(launch.sidecarParams.mode ?? "agent", req.startGoal);let preparedMode: PreparedModeTurn | undefined;let modeDefinition: PreparedModeTurn["definition"] | undefined;try {@@ -369,8 +386,9 @@ export function registerAgentIpc({sessionMode: typeof session.mode === "string" ? session.mode : "agent",content: req.content,origin: modeOrigin ?? "user",+ startGoal: req.startGoal,});- modeDefinition = preparedMode?.definition ?? await modeRuns.definitionForPrompt(launch.sidecarParams.mode ?? "agent");+ modeDefinition = preparedMode?.definition ?? await modeRuns.definitionForPrompt(promptMode);} catch (error) {await finishTurn(req.sessionId, modeOrigin ? "aborted" : "error", (error as any)?.errorCode, {turnId: durableTurnId,@@ -511,6 +529,7 @@ export function registerAgentIpc({),role: "user" as const,+ turnId: durableTurnId,content: promptContent,...(sessionMessage ? { sessionMessage: sessionMessage.origin } : {}),createdAt: new Date().toISOString(),@@ -585,6 +604,7 @@ export function registerAgentIpc({"agent.prompt",{...launch.sidecarParams,+ mode: promptMode,...(modeDefinition ? { modeDefinition } : {}),...(preparedMode?.modeTurn? { mode: preparedMode.definition.id, modeDefinition: preparedMode.definition, modeTurn: preparedMode.modeTurn }@@ -634,6 +654,11 @@ export function registerAgentIpc({});throw e;}+ if (result.accepted && !modeOrigin && preparedMode?.definition.id === "goal") {+ await modeRuns.resetGoalInput(req.sessionId).catch((error: unknown) => {+ logger.app("session", "warn", "accepted Goal input mode reset failed", { sessionId: req.sessionId, data: String(error) });+ });+ }logger.app("session", "info", "prompt accepted", {sessionId: req.sessionId,turnId: result.turnId,@@ -786,7 +811,7 @@ export function registerAgentIpc({handle(IPC.invoke.agentQueuePush, async (req: AgentQueuePushRequest) => {rejectNativeAgentOperation(req.sessionId);if (!agentHostBridge) throw new Error("agent host unavailable");- return agentHostBridge.queue.push(req);+ return goalStartRequested(req) ? queueGoal(req) : agentHostBridge.queue.push(req);});handle(IPC.invoke.agentQueueList, async (req: { sessionId: string }) => {rejectNativeAgentOperation(req.sessionId);diff --git a/apps/desktop/electron/main/runtime/goal-start.ts b/apps/desktop/electron/main/runtime/goal-start.tsnew file mode 100644index 000000000..c080dc53f--- /dev/null+++ b/apps/desktop/electron/main/runtime/goal-start.ts@@ -0,0 +1,19 @@+/** Validate explicit user intent, never runtime origin or tool authority. */+export function goalStartRequested(request: {+ startGoal?: unknown;+ content: unknown;+ sessionMessageId?: unknown;+}): boolean {+ if ((request.startGoal !== undefined && typeof request.startGoal !== "boolean") ||+ (request.startGoal === true && (typeof request.content !== "string" ||+ !request.content.trim() || Buffer.byteLength(request.content, "utf8") > 100_000 || request.sessionMessageId !== undefined))) {+ throw Object.assign(new Error("Invalid Goal startup input"), { errorCode: "INVALID_ARGUMENT" });+ }+ return request.startGoal === true;+}++/** A queued ordinary prompt cannot become a Goal because input preferences changed. */+export function goalPromptMode(sessionMode: string, startGoal: boolean | undefined): string {+ if (startGoal === true) return "goal";+ return startGoal === false && sessionMode === "goal" ? "agent" : sessionMode;+}diff --git a/apps/desktop/electron/main/runtime/mode-runs.ts b/apps/desktop/electron/main/runtime/mode-runs.tsindex 360c9a6de..9c5469bcd 100644--- a/apps/desktop/electron/main/runtime/mode-runs.ts+++ b/apps/desktop/electron/main/runtime/mode-runs.ts@@ -22,6 +22,7 @@ import type {ModeUpdateRequest,} from "@pi-desktop/shared";import type { ModeCatalogService } from "./mode-catalog";+import { goalPromptMode } from "./goal-start";type HostCaller = { call<T = unknown>(method: string, params?: unknown): Promise<T> };@@ -135,17 +136,26 @@ export function createModeRunCoordinator(deps: {sessionMode: string;content: string;origin: ModeTurnOrigin;+ startGoal?: boolean;}): Promise<PreparedModeTurn | undefined> {- if (isPlainMode(input.sessionMode)) {- if (input.origin !== "user") throw Object.assign(new Error("mode run is not staged"), { errorCode: "MODE_NOT_STAGED" });- return undefined;- }+ const sessionMode = goalPromptMode(input.sessionMode, input.startGoal);+ const newGoal = input.origin === "user" && (input.startGoal === true || (input.startGoal === undefined && sessionMode === "goal"));+ if (isPlainMode(sessionMode) && input.origin === "user" && !newGoal) return undefined;const hostCaller = host();const { run } = await hostCaller.call<ModeRunResult>("modes.get", { sessionId: input.sessionId });let selected: ModeDefinition | undefined;let claim: ModeClaimResult;- if (!run) {- selected = await this.definitionForPrompt(input.sessionMode);+ if (newGoal) {+ if (run && run.modeId !== "goal") throw Object.assign(new Error("another staged mode run is active"), { errorCode: "MODE_RUN_ACTIVE" });+ selected = await this.definitionForPrompt("goal");+ if (!selected) throw Object.assign(new Error("Goal is unavailable"), { errorCode: "MODE_NOT_FOUND" });+ if (run) await this.replaceGoal(input.sessionId);+ claim = await hostCaller.call<ModeClaimResult>("modes.startGoal", {+ sessionId: input.sessionId, input: input.content, turnId: input.turnId, modeSnapshot: selected,+ });+ } else if (!run) {+ if (isPlainMode(sessionMode)) throw Object.assign(new Error("no open mode run"), { errorCode: "MODE_RUN_NOT_FOUND" });+ selected = await this.definitionForPrompt(sessionMode);if (!selected || selected.stages.length === 0) {if (input.origin !== "user") throw Object.assign(new Error("mode run is not staged"), { errorCode: "MODE_NOT_STAGED" });return selected ? { definition: selected } : undefined;@@ -156,7 +166,7 @@ export function createModeRunCoordinator(deps: {input: input.content,turnId: input.turnId,});- } else if (run.modeId !== input.sessionMode) {+ } else if (run.modeId !== sessionMode && !(run.modeId === "goal" && sessionMode === "agent" && input.origin !== "user")) {if (input.origin !== "user") throw Object.assign(new Error("mode run belongs to another mode"), { errorCode: "MODE_RUN_ACTIVE" });return undefined;} else {@@ -193,6 +203,27 @@ export function createModeRunCoordinator(deps: {};},+ /** Accepted input preference is independent from the Goal run's claim. */+ async resetGoalInput(sessionId: string): Promise<void> {+ await host().call("modes.resetGoalInput", { sessionId });+ },++ /** Called only after a new Goal is durable, or at its serialized dispatch. */+ async replaceGoal(sessionId: string): Promise<void> {+ for (let attempt = 0; attempt < 3; attempt++) {+ const { run } = await this.get(sessionId);+ if (!run || run.modeId !== "goal") return;+ try {+ await this.control({ sessionId, runId: run.id, expectedRevision: run.revision, action: "stop" });+ return;+ } catch (error) {+ const code = (error as { errorCode?: string; data?: { errorCode?: string } }).errorCode ??+ (error as { data?: { errorCode?: string } }).data?.errorCode;+ if (code !== "MODE_REVISION_CONFLICT" || attempt === 2) throw error;+ }+ }+ },+/** Release a claim whose turn never reached the sidecar. */async abandonTurn(sessionId: string, turnId: string): Promise<void> {await this.settleTurn(sessionId, turnId, { reason: "aborted" });@@ -200,7 +231,11 @@ export function createModeRunCoordinator(deps: {async settleTurn(sessionId: string, turnId: string, end: ModeTurnEnd): Promise<void> {const entry = turnRuns.get(turnId);- if (!entry || entry.sessionId !== sessionId) return;+ if (!entry || entry.sessionId !== sessionId) {+ const { run } = await this.get(sessionId);+ if (run?.modeId === "goal" && run.state === "running" && !run.activeTurnId) scheduleContinuation(sessionId, "host");+ return;+ }turnRuns.delete(turnId);const result = await host().call<ModeSettleResult>("modes.settleTurn", {sessionId,diff --git a/apps/desktop/electron/main/runtime/plans.ts b/apps/desktop/electron/main/runtime/plans.tsindex 50c41babc..33caf36ea 100644--- a/apps/desktop/electron/main/runtime/plans.ts+++ b/apps/desktop/electron/main/runtime/plans.ts@@ -272,6 +272,17 @@ function finishTurn(}, 5 * 60 * 1000).unref();}+ if (!isQuitting() && typeof onTurnEnded === "function") {+ try {+ await onTurnEnded(id, turnId, {+ reason,+ ...(turnUsage ? { usage: turnUsage } : {}),+ ...(errorCode ? { errorCode } : {}),+ });+ } catch (error) {+ logger.app("session", "warn", "mode run settlement failed", { sessionId: id, data: String(error) });+ }+ }// The turn can no longer start a plugin tool, and its finalization record// still holds the queue, so the announcement observes a settled turn. Every// delivery failure is isolated inside the announcement itself.@@ -310,18 +321,6 @@ function finishTurn();runtimeState.agentHostBridge?.agentHost.kick(id);}- if (!isQuitting() && typeof onTurnEnded === "function") {- void onTurnEnded(id, turnId, {- reason,- ...(turnUsage ? { usage: turnUsage } : {}),- ...(errorCode ? { errorCode } : {}),- }).catch((error: unknown) => {- logger.app("session", "warn", "mode run settlement failed", {- sessionId: id,- data: String(error),- });- });- }// Settlement of the durable turn is the trigger for the collaborators that// follow it; a turn with no durable end has nothing to settle.if (!isQuitting() && settledTurnId && typeof onTurnSettled === "function") {diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex c63de5e3b..e414a56a1 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/desktop",- "version": "0.21.0",+ "version": "0.21.2","desktopName": "pi-desktop.desktop","private": true,"description": "PI-Desktop Electron application",diff --git a/apps/desktop/src/features/modes/GoalBudgetSettingsRow.tsx b/apps/desktop/src/features/modes/GoalBudgetSettingsRow.tsxindex f6150ce7e..c41cf2cee 100644--- a/apps/desktop/src/features/modes/GoalBudgetSettingsRow.tsx+++ b/apps/desktop/src/features/modes/GoalBudgetSettingsRow.tsx@@ -58,7 +58,7 @@ export function GoalBudgetSettingsRow({const label = t(field === "maxTurns" ? "settings.goalBudgetTurns" : "settings.goalBudgetTokens");return (<label key={field} className="settings-goal-budget-field">- <span>{label}</span>+ <span className="settings-goal-budget-label">{label}</span><InputclassName="settings-goal-budget-input"inputMode="numeric"diff --git a/apps/desktop/src/features/modes/ModeRunElapsed.tsx b/apps/desktop/src/features/modes/ModeRunElapsed.tsxnew file mode 100644index 000000000..f426a4af9--- /dev/null+++ b/apps/desktop/src/features/modes/ModeRunElapsed.tsx@@ -0,0 +1,26 @@+import { useEffect, useReducer } from "react";+import { useTranslation } from "react-i18next";+import { formatModeRunElapsed, modeRunElapsedMs, type ModeRunElapsedInput } from "./mode-run-elapsed";++/** Refreshes only while the Host reports an active interval; never persists time. */+export function ModeRunElapsed({ run }: { run: ModeRunElapsedInput & { id: string; revision: number } }) {+ const { t } = useTranslation();+ const [, refresh] = useReducer((tick: number) => tick + 1, 0);+ const ticking = run.state === "running" && typeof run.activeSinceMs === "number" && Number.isFinite(run.activeSinceMs);++ useEffect(() => {+ if (!ticking) return;+ const timer = setInterval(refresh, 1000);+ return () => clearInterval(timer);+ }, [ticking, run.id, run.revision, run.elapsedMs, run.activeSinceMs]);++ // Compute from current props and the clock, not a previous run's timer state.+ const elapsed = formatModeRunElapsed(modeRunElapsedMs(run, Date.now()), {+ day: "d",+ hour: "h",+ minute: "m",+ second: "s",+ });+ const label = t("modes.run.elapsed", { duration: elapsed });+ return <span className="mode-run-elapsed" title={label} aria-label={label}>{elapsed}</span>;+}diff --git a/apps/desktop/src/features/modes/ModeRunStatusBar.tsx b/apps/desktop/src/features/modes/ModeRunStatusBar.tsxindex dd0fff58c..0c8f3e543 100644--- a/apps/desktop/src/features/modes/ModeRunStatusBar.tsx+++ b/apps/desktop/src/features/modes/ModeRunStatusBar.tsx@@ -1,3 +1,4 @@+import { Pause, Pencil, Play, Trash2 } from "lucide-react";import { useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import {@@ -7,13 +8,14 @@ import {type ModeRun,type ModeUpdateRequest,} from "@pi-desktop/shared";-import { Badge, Button } from "../../components/ui";+import { Badge, Button, TooltipButton } from "../../components/ui";import { useAppStore } from "../../stores/app-store";import { modesApi, type ModeRunControlResult } from "./modes-api";import { useModesStore } from "./modes-store";import { applyRunUpdate, refreshModeRun } from "./modes-sync";import { modeDisplayLabel } from "./mode-picker-model";import { ModeRunEditForm } from "./ModeRunEditForm";+import { ModeRunElapsed } from "./ModeRunElapsed";import {MODE_RUN_STATE_LABEL_KEYS,modeControlRequest,@@ -111,8 +113,11 @@ export function ModeRunStatusPanel({ run }: { run: ModeRun }) {<Badge tone={STATE_TONES[stateKey]} className="mode-run-state">{t(MODE_RUN_STATE_LABEL_KEYS[stateKey])}</Badge>- <span className="mode-run-rounds">- {t("modes.run.rounds", { completed: rounds.completed, max: rounds.max })}+ <span className="mode-run-metrics">+ <span className="mode-run-rounds">+ {t("modes.run.rounds", { completed: rounds.completed, max: rounds.max })}+ </span>+ <ModeRunElapsed run={run} /></span>{run.lastError ? (<span className="mode-run-error" title={run.lastError}>@@ -146,24 +151,24 @@ export function ModeRunStatusPanel({ run }: { run: ModeRun }) {</Button>) : null}{controls.pause ? (- <Button size="sm" variant="ghost" disabled={busy} onClick={() => void control("pause")}>- {t("modes.run.pause")}- </Button>+ <TooltipButton className="icon-btn icon-btn-square" tooltip={t("modes.run.pause")} disabled={busy} onClick={() => void control("pause")}>+ <Pause size={14} aria-hidden="true" />+ </TooltipButton>) : null}{controls.resume ? (- <Button size="sm" disabled={busy} onClick={() => void control("resume")}>- {t("modes.run.resume")}- </Button>+ <TooltipButton className="icon-btn icon-btn-square" tooltip={t("modes.run.resume")} disabled={busy} onClick={() => void control("resume")}>+ <Play size={14} aria-hidden="true" />+ </TooltipButton>) : null}{controls.edit && !editing ? (- <Button size="sm" variant="ghost" disabled={busy} onClick={() => setEditing(true)}>- {t("modes.run.edit")}- </Button>+ <TooltipButton className="icon-btn icon-btn-square" tooltip={t("modes.run.edit")} disabled={busy} onClick={() => setEditing(true)}>+ <Pencil size={14} aria-hidden="true" />+ </TooltipButton>) : null}{controls.remove ? (- <Button size="sm" variant="ghost" disabled={busy} onClick={() => setConfirm("remove")}>- {t("modes.run.remove")}- </Button>+ <TooltipButton className="icon-btn icon-btn-square" tooltip={t("modes.run.remove")} disabled={busy} onClick={() => setConfirm("remove")}>+ <Trash2 size={14} aria-hidden="true" />+ </TooltipButton>) : null}{controls.stop ? (<Button size="sm" variant="ghost" disabled={busy} onClick={() => setConfirm("stop")}>diff --git a/apps/desktop/src/features/modes/mode-run-elapsed.ts b/apps/desktop/src/features/modes/mode-run-elapsed.tsnew file mode 100644index 000000000..af04fd5b5--- /dev/null+++ b/apps/desktop/src/features/modes/mode-run-elapsed.ts@@ -0,0 +1,42 @@+export interface ModeRunElapsedInput {+ state: string;+ elapsedMs?: number;+ activeSinceMs?: number;+}++export interface ModeRunElapsedUnits {+ day: string;+ hour: string;+ minute: string;+ second: string;+}++function nonnegativeFinite(value: number | undefined): number {+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;+}++/** Host-owned active time only; legacy runs never derive time from createdAt. */+export function modeRunElapsedMs(run: ModeRunElapsedInput, nowMs: number): number {+ const accumulated = nonnegativeFinite(run.elapsedMs);+ if (+ run.state !== "running" ||+ typeof run.activeSinceMs !== "number" ||+ !Number.isFinite(run.activeSinceMs) ||+ !Number.isFinite(nowMs)+ ) {+ return accumulated;+ }+ return Math.min(Number.MAX_VALUE, accumulated + Math.max(0, nowMs - run.activeSinceMs));+}++/** Compact whole units, with days retained rather than wrapping at 24 hours. */+export function formatModeRunElapsed(elapsedMs: number, units: ModeRunElapsedUnits): string {+ const seconds = Math.floor(nonnegativeFinite(elapsedMs) / 1000);+ const parts = [+ [Math.floor(seconds / 86_400), units.day],+ [Math.floor((seconds % 86_400) / 3600), units.hour],+ [Math.floor((seconds % 3600) / 60), units.minute],+ [seconds % 60, units.second],+ ] as const;+ return parts.filter(([value]) => value > 0).map(([value, unit]) => `${value} ${unit}`).join(" ") || `0 ${units.second}`;+}diff --git a/apps/desktop/src/features/modes/mode-run-model.ts b/apps/desktop/src/features/modes/mode-run-model.tsindex 7d13136d7..ef61d3841 100644--- a/apps/desktop/src/features/modes/mode-run-model.ts+++ b/apps/desktop/src/features/modes/mode-run-model.ts@@ -33,7 +33,7 @@ export function modeRunStateKey(run: Pick<ModeRun, "state" | "waitReason">): Modreturn "budgetExhausted";case "waiting":if (run.waitReason === "approval") return "waitingApproval";- if (run.waitReason === "retries") return "blocked";+ if (run.waitReason === "retries" || run.waitReason === "blocked") return "blocked";if (run.waitReason === "error") return "error";return "waitingInput";default:@@ -67,9 +67,10 @@ export type ModeRunControls = {export function modeRunControls(run: Pick<ModeRun, "state" | "waitReason">): ModeRunControls {const open = run.state === "running" || run.state === "waiting" || run.state === "paused" || run.state === "budget_exhausted";const awaitingApproval = run.state === "waiting" && run.waitReason === "approval";+ const reportedBlocker = run.state === "waiting" && run.waitReason === "blocked";return {- pause: run.state === "running" || run.state === "waiting",- resume: run.state === "paused" || run.state === "budget_exhausted",+ pause: run.state === "running" || (run.state === "waiting" && !reportedBlocker),+ resume: run.state === "paused" || run.state === "budget_exhausted" || reportedBlocker,stop: open,remove: open,edit: open,diff --git a/apps/desktop/src/lib/assistant-turns.ts b/apps/desktop/src/lib/assistant-turns.tsindex 06f90d2d3..96d5e7816 100644--- a/apps/desktop/src/lib/assistant-turns.ts+++ b/apps/desktop/src/lib/assistant-turns.ts@@ -308,7 +308,13 @@ export function buildTranscriptEntries(}};+ let previousRootTurnId: string | undefined;for (const message of visible) {+ const rootTurnId = typeof message.turnId === "string" ? message.turnId.trim() : undefined;+ if (rootTurnId) {+ if (previousRootTurnId && rootTurnId !== previousRootTurnId) turn = undefined;+ previousRootTurnId = rootTurnId;+ }appendMessage(message);const marks = anchored.get(message.id);if (!marks) continue;diff --git a/apps/desktop/src/lib/transcript-turn-id.ts b/apps/desktop/src/lib/transcript-turn-id.tsnew file mode 100644index 000000000..186bbdbf6--- /dev/null+++ b/apps/desktop/src/lib/transcript-turn-id.ts@@ -0,0 +1,11 @@+import type { AgentEventEnvelope } from "@pi-desktop/shared";++/** Display metadata only; execution authority remains with the Host claim. */+export function withTranscriptTurnId(envelope: AgentEventEnvelope): AgentEventEnvelope {+ const { event, turnId } = envelope;+ if (turnId && (event.type === "message_start" || event.type === "message_update" ||+ event.type === "message_end" || event.type === "user_message_persisted")) {+ return { ...envelope, event: { ...event, message: { ...event.message, turnId } } };+ }+ return envelope;+}diff --git a/apps/desktop/src/stores/app-store.ts b/apps/desktop/src/stores/app-store.tsindex f89ef5b82..c28e06b3d 100644--- a/apps/desktop/src/stores/app-store.ts+++ b/apps/desktop/src/stores/app-store.ts@@ -186,6 +186,7 @@ export const useAppStore = create<AppState>((set, get) => {messageErrorFromUnknown,assistantErrorMessage,materializeDraftSession: materializeDraftSessionInternal,+ flushPendingSessionConfiguration,}),...createTranscriptSlice({diff --git a/apps/desktop/src/stores/runtime/session-runtime.ts b/apps/desktop/src/stores/runtime/session-runtime.tsindex 92c649f29..c1a0267a5 100644--- a/apps/desktop/src/stores/runtime/session-runtime.ts+++ b/apps/desktop/src/stores/runtime/session-runtime.ts@@ -25,6 +25,7 @@ import {import type { ComposerDraftSnapshot } from "../../lib/composer-smart-stop";import { formatToolValue } from "../../lib/tool-display";import { recordPaneTranscript } from "../../lib/session-panes";+import { withTranscriptTurnId } from "../../lib/transcript-turn-id";import type { AppState, SessionHistoryWindow } from "../app-state";import type { StoreAccess } from "../slices/types";@@ -55,6 +56,7 @@ export type SessionRuntime = {readonly submittedComposerDrafts: Map<string, SubmittedComposerDraft>;readonly pendingSessionConfigurations: Map<string, SessionConfiguration>;readonly sessionConfigurationFlushes: Map<string, Promise<void>>;+ readonly sessionModeSelections: Map<string, number>;beginNavigationIntent: () => number;navigationIntentIsCurrent: (intent: number) => boolean;newSessionScopeKey: (projectPath?: string | null) => string;@@ -133,6 +135,7 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntimeconst submittedComposerDrafts = new Map<string, SubmittedComposerDraft>();const pendingSessionConfigurations = new Map<string, SessionConfiguration>();const sessionConfigurationFlushes = new Map<string, Promise<void>>();+ const sessionModeSelections = new Map<string, number>();const sessionDetailLoads = new Map<string, ReturnType<typeof api.getSession>>();const toolStartsByCallId = new Map<string, ToolStart>();const planSyncGenerations = new Map<string, number>();@@ -265,7 +268,7 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime}function projectTranscriptEvent(current: UiMessage[], envelope: AgentEventEnvelope): UiMessage[] {- const { event } = envelope;+ const { event } = withTranscriptTurnId(envelope);let next = current;switch (event.type) {case "message_start":@@ -285,6 +288,7 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntimecase "tool_start":next = upsertLiveSessionMessage(current, {id: event.toolCallId,+ ...(envelope.turnId ? { turnId: envelope.turnId } : {}),role: "tool",content: "",createdAt: new Date(envelope.ts).toISOString(),@@ -321,6 +325,7 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntimeconst completedAt = new Date(envelope.ts).toISOString();const completed: UiMessage = {id: event.toolCallId,+ ...(envelope.turnId ? { turnId: envelope.turnId } : {}),role: "tool",content:typeof event.result === "string"@@ -404,6 +409,7 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntimesubmittedComposerDrafts,pendingSessionConfigurations,sessionConfigurationFlushes,+ sessionModeSelections,beginNavigationIntent: () => navigationIntents.begin(),navigationIntentIsCurrent: (intent) => navigationIntents.isCurrent(intent),newSessionScopeKey: (projectPath) =>diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.tsindex a419761af..1a8b56579 100644--- a/apps/desktop/src/stores/slices/events-slice.ts+++ b/apps/desktop/src/stores/slices/events-slice.ts@@ -41,6 +41,7 @@ import {mergePlanCheckpoint,} from "../../lib/plan-mode-state";import { formatToolValue } from "../../lib/tool-display";+import { withTranscriptTurnId } from "../../lib/transcript-turn-id";import type { AppState } from "../app-state";import { modeAfterPlanningUpdate, visiblePlanningState } from "../helpers/planning-projection";import type { SessionRuntime } from "../runtime/session-runtime";@@ -230,6 +231,7 @@ export function createEventsSlice({},handleAgentEvent: (envelope) => {+ envelope = withTranscriptTurnId(envelope);if (envelope.event.type === "message_end") {const checkpoint = historyCheckpoints.get(envelope.sessionId);if (checkpoint) {@@ -593,6 +595,7 @@ export function createEventsSlice({...state.messages,{id: event.toolCallId,+ ...(envelope.turnId ? { turnId: envelope.turnId } : {}),role: "tool",content: "",createdAt: new Date(envelope.ts).toISOString(),@@ -636,6 +639,7 @@ export function createEventsSlice({);const completed = {id: event.toolCallId,+ ...(envelope.turnId ? { turnId: envelope.turnId } : {}),role: "tool" as const,content:typeof event.result === "string"diff --git a/apps/desktop/src/stores/slices/queue-slice.ts b/apps/desktop/src/stores/slices/queue-slice.tsindex 4da8dbad7..db91970dd 100644--- a/apps/desktop/src/stores/slices/queue-slice.ts+++ b/apps/desktop/src/stores/slices/queue-slice.ts@@ -51,6 +51,7 @@ export type QueueSliceDependencies = StoreAccess & {messageErrorFromUnknown: (error: unknown) => AppError;assistantErrorMessage: (error: AppError) => UiMessage;materializeDraftSession: (intent?: number) => Promise<string | null>;+ flushPendingSessionConfiguration: (sessionId: string) => Promise<void>;};export function createQueueSlice({@@ -63,6 +64,7 @@ export function createQueueSlice({messageErrorFromUnknown,assistantErrorMessage,materializeDraftSession,+ flushPendingSessionConfiguration,}: QueueSliceDependencies): Pick<AppState,| "enqueuePrompt"@@ -79,6 +81,18 @@ export function createQueueSlice({const pendingSubmissions = new Set<string>();const queueRefreshes = new Map<string, object>();+ function resetAcceptedGoalInput(sessionId: string, selection: number): void {+ if ((runtime.sessionModeSelections.get(sessionId) ?? 0) !== selection) return;+ const current = get().sessions.find((session) => session.id === sessionId);+ if (!current || current.mode !== "goal") return;+ const pending = runtime.pendingSessionConfigurations.get(sessionId);+ runtime.pendingSessionConfigurations.set(sessionId, runtime.mergeSessionConfiguration(pending, { ...current, mode: "agent" }));+ set((state) => ({ sessions: state.sessions.map((session) => session.id === sessionId ? { ...session, mode: "agent" } : session) }));+ void flushPendingSessionConfiguration(sessionId).catch((error: unknown) => {+ get().showToast(error instanceof Error ? error.message : String(error), { variant: "error" });+ });+ }+function toQueuedPrompt(entry: QueuedTurnSummary): QueuedPrompt {return {id: entry.id,@@ -146,6 +160,8 @@ export function createQueueSlice({const sessionId = requestedSessionId ?? get().activeSessionId;if (!sessionId) return false;if (isRemoteSession(get().sessions.find((session) => session.id === sessionId)) || sessionId.startsWith("remote:")) return false;+ const startGoal = get().sessions.find((session) => session.id === sessionId)?.mode === "goal";+ const selection = runtime.sessionModeSelections.get(sessionId) ?? 0;const queuedDraft: ComposerDraftSnapshot = draft? {text: draft.text,@@ -169,6 +185,7 @@ export function createQueueSlice({.queuePrompt({sessionId,content,+ startGoal,...(attachments.length ? { attachments } : {}),}).then((entry) => {@@ -181,6 +198,7 @@ export function createQueueSlice({),}));void get().refreshQueuedPrompts(sessionId);+ if (startGoal) resetAcceptedGoalInput(sessionId, selection);return true;}).catch((error) => {@@ -404,6 +422,8 @@ export function createQueueSlice({return accepted;}const startedIn = sessionId;+ const startGoal = get().sessions.find((session) => session.id === sessionId)?.mode === "goal";+ const selection = runtime.sessionModeSelections.get(sessionId) ?? 0;const messageCountBeforeSend =startedIn === get().activeSessionId? get().messages.length@@ -477,6 +497,7 @@ export function createQueueSlice({await api.prompt({sessionId,content,+ startGoal,messageId: optimisticMessage.id,viewingSessionId: isRemoteSession(current) ? null : viewingSessionIdForPrompt(get(), sessionId),attachments: draft ? promptAttachmentsFromDraft(draft.fileReferences) : [],@@ -488,6 +509,7 @@ export function createQueueSlice({if (current?.source !== "pi-native" && current?.source !== "remote") {get().rememberModel(current ?? {});}+ if (startGoal) resetAcceptedGoalInput(startedIn, selection);onAccepted?.(startedIn);return true;} catch (error) {diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.tsindex b11852d0e..2811ca30c 100644--- a/apps/desktop/src/stores/slices/session-slice.ts+++ b/apps/desktop/src/stores/slices/session-slice.ts@@ -827,6 +827,9 @@ export function createSessionSlice({}if (!sessionAllows(get().sessions.find((session) => session.id === sessionId), "canConfigureModel")) return;if (get().pendingPlans[sessionId]?.status === "pending") return;+ if (config.mode !== get().sessions.find((session) => session.id === sessionId)?.mode) {+ runtime.sessionModeSelections.set(sessionId, (runtime.sessionModeSelections.get(sessionId) ?? 0) + 1);+ }if (get().runningSessions[sessionId] ||runtime.sessionConfigurationFlushes.has(sessionId)diff --git a/apps/desktop/src/styles/modes.css b/apps/desktop/src/styles/modes.cssindex de70e39e3..8af33d67e 100644--- a/apps/desktop/src/styles/modes.css+++ b/apps/desktop/src/styles/modes.css@@ -27,6 +27,7 @@.mode-run-summary {display: flex;min-width: 0;+ max-width: 100%;flex: 1 1 auto;flex-wrap: wrap;align-items: center;@@ -49,11 +50,26 @@white-space: nowrap;}-.mode-run-rounds {+.mode-run-metrics {+ display: inline-flex;+ min-width: 0;+ max-width: 100%;+ align-items: baseline;+ gap: 6px;+}++.mode-run-rounds,+.mode-run-elapsed {+ min-width: 0;+ max-width: 100%;color: var(--ds-text-muted);font-variant-numeric: tabular-nums;}+.mode-run-elapsed {+ overflow-wrap: anywhere;+}+.mode-run-error {max-width: min(46vw, 420px);overflow: hidden;@@ -64,7 +80,9 @@.mode-run-actions {display: flex;- flex: 0 0 auto;+ min-width: 0;+ max-width: 100%;+ flex: 0 1 auto;flex-wrap: wrap;align-items: center;justify-content: flex-end;@@ -295,20 +313,45 @@}/* Settings → Agent behavior: Goal default budget. */+.settings-row:has(> .settings-row-control > .settings-goal-budget) {+ flex-wrap: wrap;+ gap: 8px 24px;+}++.settings-row:has(> .settings-row-control > .settings-goal-budget) > .settings-row-copy {+ flex-basis: max-content;+}++.settings-row-control:has(> .settings-goal-budget) {+ max-width: 100%;+}+.settings-goal-budget {display: flex;- flex-wrap: wrap;+ min-width: 0;+ max-width: 100%;+ flex-wrap: nowrap;+ align-items: center;gap: 8px;}.settings-goal-budget-field {display: flex;+ min-width: 0;+ flex: 1 1 auto;align-items: center;gap: 6px;color: var(--ds-text-muted);font-size: var(--text-xs-plus);}-.settings-goal-budget-input {+.settings-goal-budget-label {+ flex: 0 0 auto;+ white-space: nowrap;+}++.settings-goal-budget .settings-goal-budget-input.field-input {width: 96px;+ min-width: 0;+ flex: 0 1 96px;}diff --git a/apps/desktop/test/assistant-turns.test.mjs b/apps/desktop/test/assistant-turns.test.mjsindex 1f04b0259..3608c8580 100644--- a/apps/desktop/test/assistant-turns.test.mjs+++ b/apps/desktop/test/assistant-turns.test.mjs@@ -549,3 +549,24 @@ test("an echoed reasoning replay placeholder is not shown as thinking (#1945)",assert.ok(turn);assert.equal(JSON.stringify(turn).includes('"kind":"thinking"'), false);});++test("autonomous conversations remain separate without synthetic user rows", () => {+ const { entries, visible } = buildTranscriptEntries([+ message("first", "assistant", "First round", { turnId: "root-1" }),+ message("tool", "tool", "read result", { turnId: "root-1", toolName: "Read" }),+ message("answer", "assistant", "First result", { turnId: "root-1" }),+ message("second", "assistant", "Second round", { turnId: "root-2" }),+ ]);+ assert.equal(entries.filter((entry) => entry.kind === "assistant-turn").length, 2);+ assert.equal(visible.filter((row) => row.role === "user").length, 0);+});++test("legacy messages and delegates do not create extra root conversation boundaries", () => {+ const { entries } = buildTranscriptEntries([+ message("first", "assistant", "First round", { turnId: "root-1" }),+ message("legacy", "assistant", "Same round", { turnId: " " }),+ message("delegate", "assistant", "Delegate result", { turnId: "delegate-1", parentToolCallId: "task-1" }),+ message("second", "assistant", "Second round", { turnId: "root-2" }),+ ]);+ assert.equal(entries.filter((entry) => entry.kind === "assistant-turn").length, 2);+});diff --git a/apps/desktop/test/mode-definitions-renderer.test.mjs b/apps/desktop/test/mode-definitions-renderer.test.mjsindex 502aaffd9..785ae8915 100644--- a/apps/desktop/test/mode-definitions-renderer.test.mjs+++ b/apps/desktop/test/mode-definitions-renderer.test.mjs@@ -153,6 +153,14 @@ test("every run state has its own label and the controls the run allows", () =>assert.deepEqual([finished.stop, finished.remove, finished.edit], [false, false, false]);});+test("a model-reported blocker uses the existing blocked label and requires explicit Resume", () => {+ const blocked = { state: "waiting", waitReason: "blocked" };+ assert.equal(runModel.modeRunStateKey(blocked), "blocked");+ assert.deepEqual(runModel.modeRunControls(blocked), {+ pause: false, resume: true, stop: true, remove: true, edit: true, approve: false, reject: false,+ });+});+test("a run edit sends only what changed and rejects an empty objective or an out-of-range budget", () => {const run = { ...RUN, input: "ship it", maxTurns: 20, maxTokens: null };const draft = runModel.modeRunDraft(run);diff --git a/apps/desktop/test/mode-run-elapsed.test.mjs b/apps/desktop/test/mode-run-elapsed.test.mjsnew file mode 100644index 000000000..2effc3b19--- /dev/null+++ b/apps/desktop/test/mode-run-elapsed.test.mjs@@ -0,0 +1,189 @@+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { after, test } from "node:test";+import { fileURLToPath } from "node:url";+import { build } from "esbuild";++const root = fileURLToPath(new URL("../../../", import.meta.url));+const temp = await mkdtemp(join(tmpdir(), "pi-mode-elapsed-"));+after(() => rm(temp, { recursive: true, force: true }));+const entry = join(temp, "elapsed.cjs");+await build({+ stdin: {+ contents: `+ import { createElement } from "react";+ import { renderToStaticMarkup } from "react-dom/server";+ import { createInstance } from "i18next";+ import { I18nextProvider } from "react-i18next";+ import { ModeRunStatusPanel } from "./src/features/modes/ModeRunStatusBar";+ import { GoalBudgetSettingsRow } from "./src/features/modes/GoalBudgetSettingsRow";+ export { modeRunElapsedMs, formatModeRunElapsed } from "./src/features/modes/mode-run-elapsed";+ export { default as EN_TRANSLATION } from "../../packages/i18n/src/locales/en/index";+ export { default as ZH_TRANSLATION } from "../../packages/i18n/src/locales/zh-CN/index";+ export async function renderPanel(run, language, translation) {+ const i18n = createInstance();+ await i18n.init({ lng: language, resources: { [language]: { translation } } });+ return renderToStaticMarkup(createElement(I18nextProvider, { i18n },+ createElement(ModeRunStatusPanel, { run })));+ }+ export async function renderBudget(translation) {+ const i18n = createInstance();+ await i18n.init({ lng: "zh-CN", resources: { "zh-CN": { translation } } });+ return renderToStaticMarkup(createElement(I18nextProvider, { i18n },+ createElement(GoalBudgetSettingsRow, { settings: {}, saveSettings: async () => {} })));+ }+ `,+ resolveDir: join(root, "apps/desktop"),+ loader: "tsx",+ },+ outfile: entry,+ bundle: true,+ platform: "node",+ format: "cjs",+ jsx: "automatic",+ define: { "import.meta.env": "{}" },+ loader: { ".css": "empty" },+ alias: { "@pi-desktop/shared": join(root, "packages/shared/src/index.ts") },+ logLevel: "silent",+});+const require = createRequire(import.meta.url);+const { modeRunElapsedMs, formatModeRunElapsed, renderPanel, renderBudget, EN_TRANSLATION, ZH_TRANSLATION } = require(entry);+const EN_UNITS = { day: "d", hour: "h", minute: "m", second: "s" };+const ZH_UNITS = { day: "天", hour: "小时", minute: "分", second: "秒" };+const translation = (units) => ({+ settings: { modeGoal: "Goal", goalBudgetTurns: "轮数", goalBudgetTokens: "令牌" },+ modes: { run: {+ rounds: "Rounds {{completed}}/{{max}}",+ elapsed: EN_TRANSLATION.modes.run.elapsed,+ elapsedDayUnit: units.day,+ elapsedHourUnit: units.hour,+ elapsedMinuteUnit: units.minute,+ elapsedSecondUnit: units.second,+ } },+});+const RUN = {+ id: "run-1", sessionId: "session-1", modeId: "goal", snapshotHash: "hash",+ input: "finish", stageId: "work", state: "paused", revision: 2,+ roundsCompleted: 2, tokensUsed: 0, maxTurns: 20, maxTokens: null, artifactPaths: {},+ createdAt: "2000-01-01T00:00:00Z", updatedAt: "2000-01-01T00:00:00Z",+};++test("elapsed formatting uses exactly one ASCII space between each number and unit", () => {+ const cases = [+ [0, "0 s"], [999, "0 s"], [1000, "1 s"], [59_999, "59 s"],+ [60_000, "1 m"], [61_000, "1 m 1 s"], [3_600_000, "1 h"],+ [3_601_000, "1 h 1 s"], [3_660_000, "1 h 1 m"], [86_400_000, "1 d"],+ [90_061_000, "1 d 1 h 1 m 1 s"], [172_801_000, "2 d 1 s"],+ [1000 * (1234 * 86_400 + 5 * 3600 + 6), "1234 d 5 h 6 s"],+ ];+ for (const [ms, expected] of cases) {+ const actual = formatModeRunElapsed(ms, EN_UNITS);+ assert.equal(actual, expected);+ assert.match(actual, /^\d+ [dhms](?: \d+ [dhms])*$/);+ }+});++test("formatting rejects negative and nonfinite durations", () => {+ for (const invalid of [-1, NaN, Infinity, -Infinity]) {+ assert.equal(formatModeRunElapsed(invalid, EN_UNITS), "0 s");+ }+});++test("only running time accumulates across pause, resume, revisions and a replacement run", () => {+ const active = { ...RUN, state: "running", elapsedMs: 12_000, activeSinceMs: 10_000 };+ assert.equal(modeRunElapsedMs(active, 15_000), 17_000);+ assert.equal(modeRunElapsedMs(active, 16_000), 18_000);+ for (const state of ["paused", "waiting", "budget_exhausted", "finished", "stopped"]) {+ assert.equal(modeRunElapsedMs({ ...active, state, elapsedMs: 18_000 }, 60_000), 18_000, state);+ }+ const resumed = { ...active, revision: 4, elapsedMs: 18_000, activeSinceMs: 70_000 };+ assert.equal(modeRunElapsedMs(resumed, 72_000), 20_000);+ assert.equal(modeRunElapsedMs({ ...RUN, id: "run-2", state: "running" }, 90_000), 0);+});++test("legacy runs ignore createdAt, and invalid or backward clocks cannot add time", () => {+ for (const state of ["running", "paused", "waiting"]) {+ assert.equal(modeRunElapsedMs({ ...RUN, state }, Date.UTC(2026, 10, 7)), 0);+ }+ const active = { state: "running", elapsedMs: 4000, activeSinceMs: 10_000 };+ assert.equal(modeRunElapsedMs(active, 9000), 4000);+ assert.equal(modeRunElapsedMs(active, 10_000), 4000);+ for (const invalid of [undefined, NaN, Infinity, -Infinity]) {+ assert.equal(modeRunElapsedMs({ ...active, activeSinceMs: invalid }, 15_000), 4000);+ }+ for (const invalid of [NaN, Infinity, -Infinity]) {+ assert.equal(modeRunElapsedMs(active, invalid), 4000);+ assert.equal(modeRunElapsedMs({ ...active, elapsedMs: invalid }, 15_000), 5000);+ }+ assert.equal(modeRunElapsedMs({ ...active, elapsedMs: -500 }, 15_000), 5000);+ assert.equal(modeRunElapsedMs({ state: "running", activeSinceMs: 0 }, 5000), 5000);+ assert.ok(Number.isFinite(modeRunElapsedMs({+ state: "running", elapsedMs: Number.MAX_VALUE, activeSinceMs: -Number.MAX_VALUE,+ }, Number.MAX_VALUE)));+});++test("the real status panel renders spaced Latin units in both languages immediately after rounds", async (t) => {+ t.mock.method(Date, "now", () => 90_061_000);+ const html = await renderPanel({ ...RUN, state: "running", elapsedMs: 0, activeSinceMs: 0 }, "en", translation(EN_UNITS));+ assert.match(html, /class="mode-run-rounds">Rounds 2\/20<\/span><span class="mode-run-elapsed"/);+ assert.match(html, /title="Elapsed 1 d 1 h 1 m 1 s" aria-label="Elapsed 1 d 1 h 1 m 1 s">1 d 1 h 1 m 1 s<\/span>/);+ assert.ok(html.indexOf("mode-run-elapsed") < html.indexOf("mode-run-actions"));+ const legacy = await renderPanel({ ...RUN, state: "running", revision: 3 }, "en", translation(EN_UNITS));+ assert.match(legacy, /class="mode-run-elapsed"[^>]*>0 s<\/span>/);+ const chinese = await renderPanel({ ...RUN, revision: 4, elapsedMs: 86_401_000 }, "zh-CN", ZH_TRANSLATION);+ assert.match(chinese, /class="mode-run-elapsed"[^>]*>1 d 1 s<\/span>/);+ assert.ok(chinese.includes(ZH_TRANSLATION.modes.run.elapsed.replace("{{duration}}", "1 d 1 s")));+});++test("Resume, Pause, Edit and Remove are icon-only with localized accessible names; Stop stays text", async () => {+ for (const [language, catalog] of [["en", EN_TRANSLATION], ["zh-CN", ZH_TRANSLATION]]) {+ for (const state of ["paused", "running"]) {+ const html = await renderPanel({ ...RUN, state }, language, catalog);+ const buttons = [...html.matchAll(/<button\b([^>]*)>([\s\S]*?)<\/button>/g)];+ for (const action of [state === "running" ? "pause" : "resume", "edit", "remove"]) {+ const button = buttons.find(([, attrs]) => attrs.includes(`aria-label="${catalog.modes.run[action]}"`));+ assert.ok(button, `${language}/${state}: ${action} accessible name missing`);+ assert.match(button[2], /<svg\b[^>]*aria-hidden="true"/);+ assert.equal(button[2].replace(/<[^>]*>/g, "").trim(), "", `${action} must not show text`);+ assert.doesNotMatch(button[1], /\bdisabled/);+ }+ assert.ok(buttons.some(([, , body]) => body === catalog.modes.run.stop), "Stop remains a text action");+ }+ }+});++test("a reported blocker renders the existing Resume icon without Pause or approval actions", async () => {+ const html = await renderPanel({ ...RUN, state: "waiting", waitReason: "blocked", lastError: "Approval is required" }, "en", EN_TRANSLATION);+ assert.match(html, /data-state="blocked"/);+ const buttons = [...html.matchAll(/<button\b([^>]*)>([\s\S]*?)<\/button>/g)];+ const resume = buttons.find(([, attrs]) => attrs.includes(`aria-label="${EN_TRANSLATION.modes.run.resume}"`));+ assert.ok(resume);+ assert.match(resume[2], /<svg\b/);+ assert.ok(!buttons.some(([, attrs]) => attrs.includes(`aria-label="${EN_TRANSLATION.modes.run.pause}"`)));+});++test("Goal budget keeps two labeled shared inputs in the same control", async () => {+ const html = await renderBudget(translation(ZH_UNITS));+ assert.match(html, /class="settings-goal-budget"/);+ assert.equal((html.match(/class="settings-goal-budget-field"/g) ?? []).length, 2);+ assert.equal((html.match(/class="field-input settings-goal-budget-input"/g) ?? []).length, 2);+ assert.match(html, /class="settings-goal-budget-label">轮数<\/span><input/);+ assert.match(html, /class="settings-goal-budget-label">令牌<\/span><input/);+});++test("Goal layout rules beat generic input widths and constrain wrapping metadata", async () => {+ const css = await readFile(join(root, "apps/desktop/src/styles/modes.css"), "utf8");+ const rules = new Map([...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].map((match) => [match[1].trim(), match[2]]));+ const input = rules.get(".settings-goal-budget .settings-goal-budget-input.field-input");+ assert.ok(input, "Goal input specificity must exceed .settings-row-control .field-input");+ assert.match(input, /width:\s*96px/);+ assert.match(input, /min-width:\s*0/);+ assert.match(rules.get(".settings-goal-budget"), /flex-wrap:\s*nowrap/);+ assert.match(rules.get(".settings-goal-budget-label"), /white-space:\s*nowrap/);+ assert.match(rules.get(".settings-row-control:has(> .settings-goal-budget)"), /max-width:\s*100%/);+ assert.match(rules.get(".mode-run-actions"), /max-width:\s*100%/);+ assert.match(rules.get(".mode-run-elapsed"), /overflow-wrap:\s*anywhere/);+});diff --git a/apps/desktop/test/mode-runs-main.test.mjs b/apps/desktop/test/mode-runs-main.test.mjsindex 9da8c053e..7e3d517ba 100644--- a/apps/desktop/test/mode-runs-main.test.mjs+++ b/apps/desktop/test/mode-runs-main.test.mjs@@ -62,6 +62,8 @@ function fixture({ open = null, claim, settle = { run: null, continue: false },if (method === "modes.start" || method === "modes.claimTurn") {return claim ?? { claimed: true, run: run({ activeTurnId: params.turnId }), enteredStage: method === "modes.start", definition: staged };}+ if (method === "modes.startGoal") return { claimed: true, run: run({ modeId: "goal", activeTurnId: params.turnId }), enteredStage: true, definition: params.modeSnapshot };+ if (method === "modes.resetGoalInput") return { ok: true };if (method === "modes.settleTurn") return settle;if (method === "modes.control" || method === "modes.resolve" || method === "modes.update") return settle;if (method === "modes.settleReturn") {@@ -75,6 +77,7 @@ function fixture({ open = null, claim, settle = { run: null, continue: false },async definition(id) {if (catalogModes && !catalogModes.includes(id)) return undefined;if (id === "feature") return { ...staged, returnTo: featureReturnTo };+ if (id === "goal") return { ...staged, id: "goal", source: "builtin" };if (id === "review") return { ...staged, id: "review", stages: [] };return undefined;},@@ -212,7 +215,7 @@ test("settling a claimed turn reports tokens and starts the Host continuation",test("an unclaimed turn settles nothing", async () => {const { coordinator, calls } = fixture({ settle: { run: null, continue: true } });await coordinator.settleTurn("s1", "unknown", { reason: "completed" });- assert.equal(calls.length, 0);+ assert.equal(calls.some(call => call.method === "modes.settleTurn"), false);});test("stop aborts the claimed turn; approval continues with the approval origin", async () => {@@ -422,3 +425,35 @@ test("the catalog channel rescans the directory and announces the change (#2203)await rm(dir, { recursive: true, force: true });}});++test("a Host Goal continuation claims its snapshot after the input mode returns to Agent", async () => {+ const goal = run({ modeId: "goal" });+ const f = fixture({ open: goal, claim: { claimed: true, run: goal, enteredStage: false, definition: { ...staged, id: "goal" } } });+ const prepared = await f.coordinator.prepareTurn({ sessionId: "s1", turnId: "t2", sessionMode: "agent", content: "continue", origin: "host" });+ assert.equal(prepared.definition.id, "goal");+ assert.equal(prepared.modeTurn.runId, "run1");+ assert.equal(f.calls.at(-1).method, "modes.claimTurn");+});++test("an explicit second Goal starts a new run instead of claiming the previous one", async () => {+ const f = fixture({ open: run({ modeId: "goal" }) });+ await f.coordinator.prepareTurn({ sessionId: "s1", turnId: "new", sessionMode: "agent", content: "second goal", origin: "user", startGoal: true });+ assert.ok(f.calls.some(call => call.method === "modes.control" && call.params.action === "stop"));+ assert.ok(f.calls.some(call => call.method === "modes.startGoal" && call.params.input === "second goal"));+ assert.equal(f.calls.some(call => call.method === "modes.claimTurn"), false);+});++test("ordinary queued input cannot acquire Goal identity from a later input selection", async () => {+ const f = fixture({ open: run({ modeId: "goal" }) });+ assert.equal(await f.coordinator.prepareTurn({ sessionId: "s1", turnId: "plain", sessionMode: "goal", content: "ordinary", origin: "user", startGoal: false }), undefined);+ assert.equal(f.calls.length, 0);+});++test("Goal startup validates user intent without granting runtime origin", async () => {+ const { goalStartRequested } = await import("../electron/main/runtime/goal-start.ts");+ assert.equal(goalStartRequested({ content: "normal" }), false);+ assert.equal(goalStartRequested({ content: "objective", startGoal: true }), true);+ for (const input of [{ content: "x", startGoal: "true" }, { content: " ", startGoal: true }, { content: "中".repeat(40_000), startGoal: true }, { content: "x", startGoal: true, sessionMessageId: "delegated" }]) {+ assert.throws(() => goalStartRequested(input), { errorCode: "INVALID_ARGUMENT" });+ }+});diff --git a/apps/desktop/test/queue-pending-actions.test.mjs b/apps/desktop/test/queue-pending-actions.test.mjsindex 80a284004..c1ad9c9e5 100644--- a/apps/desktop/test/queue-pending-actions.test.mjs+++ b/apps/desktop/test/queue-pending-actions.test.mjs@@ -41,6 +41,7 @@ test("sending the first prompt derives a replaceable title instead of renaming",};const runtime = {submittedComposerDrafts: new Map(),+ sessionModeSelections: new Map(),sessionTranscriptCache: new Map(),insertOptimisticUserMessage() {},retractOptimisticUserMessage() {},@@ -110,6 +111,7 @@ test("Send now promotes queued input without stopping the running session", asynpendingPlans: {}, runningSessions: { "session-a": true }, queuedPrompts: {}, showToast: assert.fail,};const slice = createQueueSlice({+ runtime: { sessionModeSelections: new Map() },get: () => state,set: (patch) => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; },promptAttachmentsFromDraft: () => [],@@ -166,6 +168,7 @@ test("pending queue actions stay locked until admission succeeds", async (t) =>} } };let state = { activeSessionId: "session-a", sessions: [{ id: "session-a", source: "desktop" }], queuedPrompts: {}, showToast: assert.fail };const slice = createQueueSlice({+ runtime: { sessionModeSelections: new Map() },get: () => state,set: (patch) => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; },promptAttachmentsFromDraft: () => [],@@ -223,6 +226,7 @@ test("pending queue actions stay locked until admission succeeds", async (t) =>} } };let state = { activeSessionId: "session-a", sessions: [{ id: "session-a", source: "desktop" }], queuedPrompts: {}, showToast: (message) => errors.push(message) };const slice = createQueueSlice({+ runtime: { sessionModeSelections: new Map() },get: () => state,set: (patch) => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; },promptAttachmentsFromDraft: () => [],@@ -282,6 +286,7 @@ test("editing a restored queue preserves attachments when resubmitted", async (t} } };let state = { activeSessionId: "session-a", sessions: [{ id: "session-a", source: "desktop" }], queuedPrompts: {}, showToast: assert.fail };const slice = createQueueSlice({+ runtime: { sessionModeSelections: new Map() },get: () => state,set: (patch) => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; },promptAttachmentsFromDraft: (references) => references.map(({ path, name, kind, mimeType }) => ({ path, name, kind, mimeType })),diff --git a/apps/desktop/test/queued-turn-finalization.test.mjs b/apps/desktop/test/queued-turn-finalization.test.mjsindex a4bb6164a..b445e8037 100644--- a/apps/desktop/test/queued-turn-finalization.test.mjs+++ b/apps/desktop/test/queued-turn-finalization.test.mjs@@ -34,7 +34,7 @@ function deferred() {const SESSION = "s1";const FIRST_TURN = "initial";-function fixture() {+function fixture({ onTurnEnded } = {}) {const activeTurns = new Map([[SESSION, FIRST_TURN]]);const persistedQueue = new Map();const prompts = [];@@ -131,6 +131,7 @@ function fixture() {throw new Error("not used by this fixture");},isQuitting: () => quitting,+ onTurnEnded,});bridge.ingest({@@ -399,3 +400,32 @@ test("a stalled turn that main finalized never blocks the queue after a restartassert.equal(f.coordination.isActiveTurn(SESSION, FIRST_TURN), false);assert.deepEqual(f.prompts.map((prompt) => prompt.content), ["waiting follow-up"]);});++test("queued Goal waits for mode settlement and retains its explicit startup identity", async () => {+ const settled = deferred();+ let settling = false;+ const f = fixture({ onTurnEnded: async () => { settling = true; await settled.promise; } });+ await f.bridge.queue.push({ sessionId: SESSION, content: "replacement goal", startGoal: true });+ const pending = f.finish("aborted");+ await setImmediate();+ f.writes[0].resolve({ ok: true });+ await setImmediate();+ assert.equal(settling, true);+ assert.equal(f.prompts.length, 0, "mode accounting still holds the queue");+ settled.resolve();+ await pending;+ await setImmediate();+ assert.equal(f.prompts[0].startGoal, true);+});++test("an idempotent Goal retry never repeats the accepted replacement callback", async () => {+ const f = fixture();+ let replacements = 0;+ const request = { sessionId: SESSION, content: "replacement goal", startGoal: true, idempotencyKey: "same-goal" };+ const accepted = async () => { replacements++; };+ const first = await f.bridge.queue.push(request, accepted);+ const retry = await f.bridge.queue.push(request, accepted);+ assert.equal(retry.id, first.id);+ assert.equal(replacements, 1);+ assert.equal(f.persistedQueue.size, 1);+});diff --git a/apps/desktop/test/session-draft-materialization.test.mjs b/apps/desktop/test/session-draft-materialization.test.mjsindex 801e55c0c..d101e26e3 100644--- a/apps/desktop/test/session-draft-materialization.test.mjs+++ b/apps/desktop/test/session-draft-materialization.test.mjs@@ -46,6 +46,7 @@ function fixture(t) {}));Object.assign(state, createQueueSlice({get, set, runtime, materializeDraftSession: coordination.materializeDraftSession,+ flushPendingSessionConfiguration: coordination.flushPendingSessionConfiguration,recordSubmittedInput: async () => {}, insertOptimisticUserMessage: runtime.insertOptimisticUserMessage,retractOptimisticUserMessage: runtime.retractOptimisticUserMessage,promptAttachmentsFromDraft: () => [], withoutRecordKey,@@ -110,3 +111,43 @@ test("failed creation rejects all waiters and releases the slot for retry", asyn} }));assert.equal(await f.coordination.materializeDraftSession(), "retry");});++test("sending a Goal returns only its input mode to Agent and keeps newer model settings", async t => {+ const f = fixture(t);+ f.set({ activeSessionId: "goal", sessions: [{ id: "goal", title: "Task", mode: "goal", permissionMode: "auto", providerId: "p", modelId: "old", thinkingLevel: "high" }] });+ const accepted = Promise.withResolvers();+ const requests = [];+ t.mock.method(api, "prompt", async request => { requests.push(request); await accepted.promise; return { accepted: true }; });+ const sending = f.get().sendPrompt("first objective");+ await f.get().configureActiveSession({ mode: "goal", modelId: "new", thinkingLevel: "high", permissionMode: "auto" });+ accepted.resolve();+ assert.equal(await sending, true);+ assert.equal(requests[0].startGoal, true);+ assert.equal(f.get().sessions[0].mode, "agent");+ assert.equal(f.get().sessions[0].modelId, "new");+ assert.equal(f.get().runningSessions.goal, true);+ assert.equal(f.runtime.pendingSessionConfigurations.get("goal").permissionMode, "auto");+});++test("a queued second Goal is explicit and resets the input, while rejected and newer selections remain", async t => {+ const f = fixture(t);+ f.set({ activeSessionId: "goal", sessions: [{ id: "goal", title: "Task", mode: "goal", thinkingLevel: "high" }], runningSessions: { goal: true } });+ const requests = [];+ t.mock.method(api, "queuePrompt", async request => { requests.push(request); return { id: "queued", ...request }; });+ t.mock.method(api, "listQueuedPrompts", async () => ({ entries: [] }));+ assert.equal(await f.get().sendPrompt("replacement"), true);+ assert.equal(requests[0].startGoal, true);+ assert.equal(f.get().sessions[0].mode, "agent");+ await f.get().configureActiveSession({ mode: "goal", thinkingLevel: "high" });+ const gate = Promise.withResolvers();+ t.mock.method(api, "queuePrompt", async () => gate.promise);+ const sending = f.get().sendPrompt("later goal");+ await f.get().configureActiveSession({ mode: "plan", thinkingLevel: "high" });+ gate.resolve({ id: "later", content: "later goal", sessionId: "goal" });+ assert.equal(await sending, true);+ assert.equal(f.get().sessions[0].mode, "plan");+ await f.get().configureActiveSession({ mode: "goal", thinkingLevel: "high" });+ t.mock.method(api, "queuePrompt", async () => { throw new Error("queue full"); });+ assert.equal(await f.get().sendPrompt("rejected"), false);+ assert.equal(f.get().sessions[0].mode, "goal");+});diff --git a/apps/desktop/test/session-runtime-updates.test.mjs b/apps/desktop/test/session-runtime-updates.test.mjsindex ba0770bae..ad6b65565 100644--- a/apps/desktop/test/session-runtime-updates.test.mjs+++ b/apps/desktop/test/session-runtime-updates.test.mjs@@ -229,3 +229,23 @@ test("background tool partials stay cache-only and update the first running matcassert.equal(h.get().retainedTranscripts, retained);assert.equal(h.writes(), 0);}));++test("root turn attribution survives live messages, tool rows and background caches", () => withFrames((flush) => {+ const h = harness([], []);+ h.set({ pendingPermissions: {}, pendingAsks: {}, askDrafts: {} });+ for (const sessionId of ["active", "background"]) {+ for (const type of ["message_start", "message_update", "message_end"]) {+ h.get().handleAgentEvent({+ sessionId, turnId: "round-one", ts: 1,+ event: { type, message: message("answer", { content: type }) },+ });+ flush();+ const rows = sessionId === "active" ? h.get().messages : h.runtime.sessionTranscriptCache.get(sessionId);+ assert.equal(rows[0].turnId, "round-one", `${sessionId} ${type}`);+ }+ h.get().handleAgentEvent({ sessionId, turnId: "round-two", ts: 2, event: { type: "tool_start", toolCallId: "tool", toolName: "Read", args: {} } });+ h.get().handleAgentEvent({ sessionId, turnId: "round-two", ts: 3, event: { type: "tool_end", toolCallId: "tool", result: "done", isError: false } });+ const rows = sessionId === "active" ? h.get().messages : h.runtime.sessionTranscriptCache.get(sessionId);+ assert.equal(rows.at(-1).turnId, "round-two");+ }+}));diff --git a/apps/pi-host/package.json b/apps/pi-host/package.jsonindex 764cf7bbc..c8c44427e 100644--- a/apps/pi-host/package.json+++ b/apps/pi-host/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/pi-host",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","description": "Headless PI Agent Host: RACP-WS server over the Agent Host module, the pi sidecar, and host-core",diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rsindex 11a2dc898..d482556c2 100644--- a/crates/host-core/src/db.rs+++ b/crates/host-core/src/db.rs@@ -7,7 +7,7 @@ pub(crate) use serde_json::Value;pub(crate) use std::path::{Path, PathBuf};/// Current SQLite schema version.-pub const SCHEMA_VERSION: i64 = 29;+pub const SCHEMA_VERSION: i64 = 31;/// Absolute approval deadline for a newly submitted Plan or Goal proposal.pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;@@ -15,7 +15,9 @@ pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;/// Durable notification rows kept globally.pub const NOTIFICATION_KEEP: i64 = 200;+mod completion_report_migration;mod migrations;+mod mode_run_elapsed_migration;mod mode_runs_migration;mod model;mod model_discovery_migration;@@ -77,3 +79,7 @@ mod tests;#[cfg(test)]#[path = "db/project_path_tests.rs"]mod project_path_tests;++#[cfg(test)]+#[path = "db/completion_report_migration_tests.rs"]+mod completion_report_migration_tests;diff --git a/crates/host-core/src/db/completion_report_migration.rs b/crates/host-core/src/db/completion_report_migration.rsnew file mode 100644index 000000000..b96f9011b--- /dev/null+++ b/crates/host-core/src/db/completion_report_migration.rs@@ -0,0 +1,76 @@+use super::{anyhow, create_migration_backup, Connection, Context, Path, Result};+use rusqlite::Transaction;++/// Add model evidence without changing any legacy value or immutable snapshot.+/// SQLite cannot ALTER a CHECK: widening wait_reason requires a lossless table+/// rebuild. Fresh initialization shares this exact schema transformation.+pub(super) fn initialize(tx: &Transaction<'_>) -> Result<()> {+ let has_report: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info('mode_runs') WHERE name='completion_report_json')",+ [],+ |row| row.get(0),+ )?;+ if !has_report {+ tx.execute_batch("ALTER TABLE mode_runs ADD COLUMN completion_report_json TEXT;")?;+ }+ let sql: String = tx.query_row(+ "SELECT sql FROM sqlite_master WHERE type='table' AND name='mode_runs'",+ [],+ |row| row.get(0),+ )?;+ if sql.contains("'blocked'") {+ return Ok(());+ }+ let old = "wait_reason IN ('approval', 'retries', 'turn_end', 'error')";+ if !sql.contains(old) {+ return Err(anyhow!("unrecognized mode_runs wait_reason constraint"));+ }+ // Keep all existing columns/checks (including elapsed accounting) and+ // optional pre-existing report data, rather than reconstructing run rows.+ let widened = sql+ .replace(+ old,+ "wait_reason IN ('approval', 'retries', 'turn_end', 'error', 'blocked')",+ )+ .replacen("mode_runs", "mode_runs_v31", 1);+ let objects = tx.prepare(+ "SELECT sql FROM sqlite_master WHERE tbl_name='mode_runs' AND type IN ('index','trigger') AND sql IS NOT NULL ORDER BY type,name",+ )?.query_map([], |row| row.get::<_, String>(0))?.collect::<rusqlite::Result<Vec<_>>>()?;+ tx.execute_batch(&widened)?;+ tx.execute_batch(+ "INSERT INTO mode_runs_v31 SELECT * FROM mode_runs;+ DROP TABLE mode_runs;+ ALTER TABLE mode_runs_v31 RENAME TO mode_runs;",+ )?;+ for object in objects {+ tx.execute_batch(&object)?;+ }+ if tx.prepare("PRAGMA foreign_key_check")?.exists([])? {+ return Err(anyhow!(+ "foreign key check failed during completion report migration"+ ));+ }+ Ok(())+}++pub(super) fn migrate(conn: &Connection, path: &Path) -> Result<()> {+ let backup = create_migration_backup(conn, path, 30)?;+ // Disable cascades only during the transactional table replacement. Child+ // gate rows keep their original ids, evidence and foreign-key definition.+ let foreign_keys: bool = conn.pragma_query_value(None, "foreign_keys", |row| row.get(0))?;+ conn.pragma_update(None, "foreign_keys", false)?;+ let result = (|| {+ let tx = conn.unchecked_transaction()?;+ initialize(&tx)?;+ tx.pragma_update(None, "user_version", 31i64)?;+ tx.commit().with_context(|| {+ format!(+ "commit schema v30 to v31 completion report migration; backup {} remains",+ backup.display()+ )+ })+ })();+ conn.pragma_update(None, "foreign_keys", foreign_keys)+ .context("restore foreign keys after completion report migration")?;+ result+}diff --git a/crates/host-core/src/db/completion_report_migration_tests.rs b/crates/host-core/src/db/completion_report_migration_tests.rsnew file mode 100644index 000000000..cbf9d854e--- /dev/null+++ b/crates/host-core/src/db/completion_report_migration_tests.rs@@ -0,0 +1,210 @@+//! Schema 31 is additive: legacy runs, gate evidence, snapshots and queues survive.++use super::*;++fn version(conn: &Connection) -> i64 {+ conn.query_row("PRAGMA user_version", [], |row| row.get(0))+ .unwrap()+}++fn has_report(conn: &Connection) -> bool {+ conn.query_row("SELECT EXISTS(SELECT 1 FROM pragma_table_info('mode_runs') WHERE name='completion_report_json')", [], |row| row.get(0)).unwrap()+}++fn rows(conn: &Connection, sql: &str) -> Vec<Vec<rusqlite::types::Value>> {+ let mut statement = conn.prepare(sql).unwrap();+ let columns = statement.column_count();+ statement+ .query_map([], |row| (0..columns).map(|i| row.get(i)).collect())+ .unwrap()+ .collect::<rusqlite::Result<_>>()+ .unwrap()+}++fn populated_v30(path: &Path, preexisting_report: bool) {+ let db = Database::open(path).unwrap();+ // Recreate the exact original CHECK even when this helper runs on v31.+ db.conn()+ .execute_batch(+ "DROP TABLE mode_gate_results; DROP TABLE mode_runs; DROP TABLE mode_snapshots;",+ )+ .unwrap();+ db.conn().execute_batch(MODE_RUNS_SCHEMA).unwrap();+ let tx = db.conn().unchecked_transaction().unwrap();+ super::mode_run_elapsed_migration::initialize(&tx).unwrap();+ tx.execute_batch("INSERT INTO sessions(id,title,mode,created_at,updated_at) VALUES ('s','legacy goal','goal',1,2);+ INSERT INTO mode_snapshots(hash,json,created_at) VALUES ('legacy','{\"version\":1}','t');+ INSERT INTO mode_runs(id,session_id,mode_id,snapshot_hash,input,stage_id,state,wait_reason,last_error,+ active_turn_id,active_origin,pending_gate,retry_counts,rounds_completed,tokens_used,max_turns,max_tokens,+ artifact_paths,settled_turns,created_at,updated_at,elapsed_ms,active_since_ms)+ VALUES ('r','s','goal','legacy','objective','work','waiting','error','old error','t','host',2,'{\"work:0\":1}',3,400,20,10000,'{\"goal\":\".pi/goal.md\"}','[\"previous\"]',1,2,1234,NULL);+ INSERT INTO mode_gate_results(id,run_id,stage_id,gate_index,action,passed,evidence,tool_call_id,created_at)+ VALUES (7,'r','work',0,'run',1,'kept evidence','call',2);+ INSERT INTO turn_queue(id,session_id,principal,input_hash,content,permission_mode,position,created_at,start_goal)+ VALUES ('queued','s','desktop','hash','next','auto',1,2,1);+ INSERT INTO turns(id,session_id,status,started_at,ended_at) VALUES ('old-turn','s','completed',1,2);+ PRAGMA user_version=30;").unwrap();+ if preexisting_report {+ tx.execute_batch(+ "ALTER TABLE mode_runs ADD COLUMN completion_report_json TEXT;+ UPDATE mode_runs SET completion_report_json='{\"legacyEvidence\":true}';",+ )+ .unwrap();+ }+ tx.commit().unwrap();+}++const LEGACY_RUN: &str = "SELECT id,session_id,mode_id,snapshot_hash,input,stage_id,state,wait_reason,last_error,+ revision,active_turn_id,active_origin,stage_entered,advanced_in_turn,pending_gate,retry_counts,+ rounds_completed,tokens_used,max_turns,max_tokens,artifact_paths,settled_turns,created_at,updated_at,+ finished_at,elapsed_ms,active_since_ms FROM mode_runs";++#[test]+fn completion_report_migration_populated_30_preserves_all_data_and_pre_migration_backup() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ populated_v30(&path, false);+ let before = Connection::open(&path).unwrap();+ let old_run = rows(&before, LEGACY_RUN);+ let gates = rows(&before, "SELECT * FROM mode_gate_results");+ let snapshots = rows(&before, "SELECT * FROM mode_snapshots");+ let sessions = rows(&before, "SELECT * FROM sessions");+ let queue = rows(&before, "SELECT * FROM turn_queue");+ let turns = rows(&before, "SELECT * FROM turns");+ drop(before);+ let db = Database::open(&path).unwrap();+ assert_eq!(version(db.conn()), 31);+ assert_eq!(SCHEMA_VERSION, 31);+ assert!(has_report(db.conn()));+ assert_eq!(rows(db.conn(), LEGACY_RUN), old_run);+ assert_eq!(rows(db.conn(), "SELECT * FROM mode_gate_results"), gates);+ assert_eq!(rows(db.conn(), "SELECT * FROM mode_snapshots"), snapshots);+ assert_eq!(rows(db.conn(), "SELECT * FROM sessions"), sessions);+ assert_eq!(rows(db.conn(), "SELECT * FROM turn_queue"), queue);+ assert_eq!(rows(db.conn(), "SELECT * FROM turns"), turns);+ assert_eq!(+ rows(db.conn(), "SELECT completion_report_json FROM mode_runs"),+ vec![vec![rusqlite::types::Value::Null]]+ );+ assert!(rows(db.conn(), "PRAGMA foreign_key_check").is_empty());+ let backup = Connection::open(migration_backup_path(&path, 30)).unwrap();+ assert_eq!(version(&backup), 30);+ assert!(!has_report(&backup));+ assert_eq!(rows(&backup, LEGACY_RUN), old_run);+ assert_eq!(rows(&backup, "SELECT * FROM mode_gate_results"), gates);+ assert_eq!(rows(&backup, "SELECT * FROM turn_queue"), queue);+ // The old CHECK still rejects blocked; the upgraded one permits it only while waiting.+ assert!(backup+ .execute("UPDATE mode_runs SET wait_reason='blocked'", [])+ .is_err());+ db.conn()+ .execute("UPDATE mode_runs SET wait_reason='blocked'", [])+ .unwrap();+ assert!(db+ .conn()+ .execute("UPDATE mode_runs SET state='running'", [])+ .is_err());+ assert!(db+ .conn()+ .execute("UPDATE mode_runs SET wait_reason='unknown'", [])+ .is_err());+ db.conn()+ .execute("DELETE FROM sessions WHERE id='s'", [])+ .unwrap();+ assert!(rows(db.conn(), "SELECT * FROM mode_runs").is_empty());+ assert!(rows(db.conn(), "SELECT * FROM mode_gate_results").is_empty());+}++#[test]+fn completion_report_migration_is_idempotent_with_a_preexisting_column() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ populated_v30(&path, true);+ for _ in 0..2 {+ let db = Database::open(&path).unwrap();+ assert_eq!(version(db.conn()), 31);+ assert_eq!(+ rows(db.conn(), "SELECT completion_report_json FROM mode_runs"),+ vec![vec![rusqlite::types::Value::Text(+ "{\"legacyEvidence\":true}".into()+ )]]+ );+ assert_eq!(+ rows(db.conn(), "SELECT id FROM mode_gate_results"),+ vec![vec![rusqlite::types::Value::Integer(7)]]+ );+ }+ let backup = Connection::open(migration_backup_path(&path, 30)).unwrap();+ assert_eq!(version(&backup), 30);+ assert!(has_report(&backup));+}++fn schema(conn: &Connection) -> Vec<Vec<rusqlite::types::Value>> {+ rows(conn, "SELECT type,name,sql FROM sqlite_master WHERE tbl_name IN ('mode_runs','mode_gate_results') ORDER BY type,name")+}++#[test]+fn completion_report_migration_fresh_and_older_chain_have_identical_schema_31() {+ let dir = tempfile::tempdir().unwrap();+ let fresh = Database::open(&dir.path().join("fresh.sqlite")).unwrap();+ assert_eq!(version(fresh.conn()), 31);+ assert!(has_report(fresh.conn()));+ let path = dir.path().join("older.sqlite");+ populated_v30(&path, false);+ let conn = Connection::open(&path).unwrap();+ conn.execute_batch(+ "ALTER TABLE mode_runs DROP COLUMN active_since_ms;+ ALTER TABLE mode_runs DROP COLUMN elapsed_ms;+ ALTER TABLE turn_queue DROP COLUMN start_goal;+ PRAGMA user_version=29;",+ )+ .unwrap();+ drop(conn);+ let upgraded = Database::open(&path).unwrap();+ assert_eq!(version(upgraded.conn()), 31);+ assert_eq!(schema(upgraded.conn()), schema(fresh.conn()));+ for v in [29, 30] {+ let backup = Connection::open(migration_backup_path(&path, v)).unwrap();+ assert_eq!(version(&backup), v);+ assert!(!has_report(&backup));+ }+}++#[test]+fn completion_report_migration_failure_rolls_back_schema_rows_and_restores_foreign_keys() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ populated_v30(&path, false);+ let conn = Connection::open(&path).unwrap();+ conn.execute_batch(+ "PRAGMA foreign_keys=OFF;+ INSERT INTO mode_gate_results(run_id,stage_id,gate_index,action,passed,created_at)+ VALUES ('missing','work',0,'run',0,2);+ PRAGMA foreign_keys=ON;",+ )+ .unwrap();+ let before = rows(&conn, LEGACY_RUN);+ let gates = rows(&conn, "SELECT * FROM mode_gate_results ORDER BY id");+ let before_schema = schema(&conn);+ assert!(super::completion_report_migration::migrate(&conn, &path).is_err());+ assert_eq!(version(&conn), 30);+ assert!(!has_report(&conn));+ assert_eq!(schema(&conn), before_schema);+ assert_eq!(rows(&conn, LEGACY_RUN), before);+ assert_eq!(+ rows(&conn, "SELECT * FROM mode_gate_results ORDER BY id"),+ gates+ );+ let foreign_keys: bool = conn+ .pragma_query_value(None, "foreign_keys", |row| row.get(0))+ .unwrap();+ assert!(foreign_keys);+ assert!(rows(+ &conn,+ "SELECT name FROM sqlite_master WHERE name='mode_runs_v31'"+ )+ .is_empty());+ let backup = Connection::open(migration_backup_path(&path, 30)).unwrap();+ assert_eq!(version(&backup), 30);+ assert!(!has_report(&backup));+}diff --git a/crates/host-core/src/db/mode_run_elapsed_migration.rs b/crates/host-core/src/db/mode_run_elapsed_migration.rsnew file mode 100644index 000000000..593578a22--- /dev/null+++ b/crates/host-core/src/db/mode_run_elapsed_migration.rs@@ -0,0 +1,52 @@+use super::{create_migration_backup, Connection, Context, Path, Result};+use rusqlite::Transaction;++/// Shared by fresh initialization and the additive v29 -> v30 migration.+/// Legacy runs start at zero, never at a duration inferred from created_at.+/// Legacy queued turns do not explicitly request a new Goal run.+pub(super) fn initialize(tx: &Transaction<'_>) -> Result<()> {+ for (table, column, ddl) in [+ (+ "mode_runs",+ "elapsed_ms",+ "ALTER TABLE mode_runs ADD COLUMN elapsed_ms INTEGER NOT NULL DEFAULT 0+ CHECK (elapsed_ms BETWEEN 0 AND 9007199254740991);",+ ),+ (+ "mode_runs",+ "active_since_ms",+ "ALTER TABLE mode_runs ADD COLUMN active_since_ms INTEGER+ CHECK (active_since_ms BETWEEN 0 AND 9007199254740991);",+ ),+ (+ "turn_queue",+ "start_goal",+ "ALTER TABLE turn_queue ADD COLUMN start_goal INTEGER NOT NULL DEFAULT 0+ CHECK (start_goal IN (0, 1));",+ ),+ ] {+ let exists: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = ?2)",+ [table, column],+ |row| row.get(0),+ )?;+ if !exists {+ tx.execute_batch(ddl)?;+ }+ }+ Ok(())+}++pub(super) fn migrate(conn: &Connection, path: &Path) -> Result<()> {+ let backup = create_migration_backup(conn, path, 29)?;+ let tx = conn.unchecked_transaction()?;+ initialize(&tx)?;+ tx.pragma_update(None, "user_version", 30i64)?;+ tx.commit().with_context(|| {+ format!(+ "commit schema v29 to v30 mode run elapsed migration; backup {} remains",+ backup.display()+ )+ })?;+ Ok(())+}diff --git a/crates/host-core/src/db/mode_runs_migration.rs b/crates/host-core/src/db/mode_runs_migration.rsindex a65008ccd..7a2923afc 100644--- a/crates/host-core/src/db/mode_runs_migration.rs+++ b/crates/host-core/src/db/mode_runs_migration.rs@@ -157,7 +157,7 @@ mod tests {let db = Database::open(&path).unwrap();assert_eq!(version(db.conn()), SCHEMA_VERSION);- assert_eq!(SCHEMA_VERSION, 29);+ assert_eq!(SCHEMA_VERSION, 31);assert!(has_column(db.conn(), "sessions", "mode_snapshot_hash"));for table in ["mode_snapshots", "mode_runs", "mode_gate_results"] {assert!(has_table(db.conn(), table), "{table}");diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rsindex 9bcc5bd7e..b8b1ced0e 100644--- a/crates/host-core/src/db/repositories.rs+++ b/crates/host-core/src/db/repositories.rs@@ -148,6 +148,8 @@ impl Database {tx.execute_batch(crate::session_collaboration::SCHEMA)?;tx.execute_batch(WORKTREE_DDL)?;tx.execute_batch(super::MODE_RUNS_SCHEMA)?;+ super::mode_run_elapsed_migration::initialize(&tx)?;+ super::completion_report_migration::initialize(&tx)?;tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;tx.commit()?;}@@ -219,6 +221,8 @@ impl Database {}27 => {}28 => {}+ 29 => {}+ 30 => {}legacy @ 1..=6 => {let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");drop(conn);@@ -290,6 +294,14 @@ impl Database {if version == 28 {super::mode_runs_migration::migrate(&conn, path)?;}+ let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;+ if version == 29 {+ super::mode_run_elapsed_migration::migrate(&conn, path)?;+ }+ let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;+ if version == 30 {+ super::completion_report_migration::migrate(&conn, path)?;+ }let db = Self { conn, data_dir };db.boot_maintenance()?;crate::session_collaboration::recover(&db)?;diff --git a/crates/host-core/src/mode_runs.rs b/crates/host-core/src/mode_runs.rsindex 3813485c5..b4a5d72cc 100644--- a/crates/host-core/src/mode_runs.rs+++ b/crates/host-core/src/mode_runs.rs@@ -12,6 +12,7 @@mod artifacts;mod budget;+mod completion_report;mod engine;mod gates;mod model;@@ -22,8 +23,9 @@ mod snapshot;pub use budget::validate_goal_budget_setting;pub use engine::{- claim_turn, configure_session_mode, control, open_run, prepare_session_mode, recover, resolve,- settle_turn, start, store_session_snapshot, update, verify_gate_command, PreparedMode,+ claim_turn, configure_session_mode, control, open_run, prepare_session_mode, recover,+ reset_goal_input, resolve, settle_turn, start, start_goal, store_session_snapshot, update,+ verify_gate_command, PreparedMode,};pub use gates::{complete_stage, gate_result, GateExecution, GateExecutions};pub use model::{CompleteStageParams, GateResultParams, ModeRun, SessionParams, StartParams};@@ -60,3 +62,9 @@ mod edit_tests;#[cfg(test)]mod return_mode_tests;++#[cfg(test)]+mod elapsed_tests;++#[cfg(test)]+mod completion_report_tests;diff --git a/crates/host-core/src/mode_runs/completion_report.rs b/crates/host-core/src/mode_runs/completion_report.rsnew file mode 100644index 000000000..63d5ac5ab--- /dev/null+++ b/crates/host-core/src/mode_runs/completion_report.rs@@ -0,0 +1,127 @@+//! Bounded model-supplied completion evidence. This never proves a Host gate.++use std::collections::HashSet;++use anyhow::Result;+use serde::{Deserialize, Deserializer, Serialize};+use serde_json::Value;++use super::mode_error_detail;++const MAX_REPORT_BYTES: usize = 262_144;+const MAX_ITEMS: usize = 64;+const MAX_CRITERION_BYTES: usize = 4_096;+const MAX_EVIDENCE_BYTES: usize = 16_384;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum CompletionStatus {+ Completed,+ Blocked,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum CriterionOutcome {+ Met,+ Unmet,+ Unverified,+}++#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct CompletionOutcome {+ pub criterion: String,+ pub outcome: CriterionOutcome,+ pub evidence: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct CompletionReport {+ pub status: CompletionStatus,+ pub outcomes: Vec<CompletionOutcome>,+ pub remaining_work: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub blocker_reason: Option<String>,+}++fn invalid(detail: impl std::fmt::Display) -> anyhow::Error {+ mode_error_detail("MODE_INVALID_ARGUMENT", detail)+}++fn text(value: &str, limit: usize, field: &str) -> Result<()> {+ if value.trim().is_empty() || value.len() > limit {+ return Err(invalid(format!(+ "report {field} must be nonblank and at most {limit} UTF-8 bytes"+ )));+ }+ Ok(())+}++impl CompletionReport {+ /// Validate again at the Host boundary, independently of the runtime schema.+ pub(super) fn parse(value: Value) -> Result<Self> {+ if serde_json::to_vec(&value)?.len() > MAX_REPORT_BYTES {+ return Err(invalid("report exceeds 262144 serialized bytes"));+ }+ // Optional means absent, not an explicitly null blocker reason.+ if value.get("blockerReason").is_some_and(Value::is_null) {+ return Err(invalid(+ "report blockerReason must be a string when provided",+ ));+ }+ let report: Self = serde_json::from_value(value).map_err(invalid)?;+ if report.outcomes.is_empty() || report.outcomes.len() > MAX_ITEMS {+ return Err(invalid("report outcomes must contain 1..64 items"));+ }+ if report.remaining_work.len() > MAX_ITEMS {+ return Err(invalid(+ "report remainingWork must contain at most 64 items",+ ));+ }+ let mut criteria = HashSet::new();+ for outcome in &report.outcomes {+ text(&outcome.criterion, MAX_CRITERION_BYTES, "criterion")?;+ text(&outcome.evidence, MAX_EVIDENCE_BYTES, "evidence")?;+ if !criteria.insert(outcome.criterion.trim()) {+ return Err(invalid("report criteria must be unique after trimming"));+ }+ }+ for remaining in &report.remaining_work {+ text(remaining, MAX_CRITERION_BYTES, "remainingWork item")?;+ }+ if let Some(reason) = &report.blocker_reason {+ text(reason, MAX_EVIDENCE_BYTES, "blockerReason")?;+ }+ let all_met = report+ .outcomes+ .iter()+ .all(|item| item.outcome == CriterionOutcome::Met);+ match report.status {+ CompletionStatus::Completed+ if !all_met+ || !report.remaining_work.is_empty()+ || report.blocker_reason.is_some() =>+ {+ return Err(invalid("completed report requires all outcomes met, no remaining work and no blockerReason"));+ }+ CompletionStatus::Blocked+ if report.blocker_reason.is_none()+ || (all_met && report.remaining_work.is_empty()) =>+ {+ return Err(invalid("blocked report requires blockerReason and unmet/unverified outcomes or remaining work"));+ }+ _ => {}+ }+ Ok(report)+ }+}++/// Preserve explicit null so invalid reports receive MODE_INVALID_ARGUMENT in+/// the engine instead of being silently treated as a legacy absent report.+pub(super) fn deserialize_report<'de, D: Deserializer<'de>>(+ deserializer: D,+) -> std::result::Result<Option<Value>, D::Error> {+ Value::deserialize(deserializer).map(Some)+}diff --git a/crates/host-core/src/mode_runs/completion_report_tests.rs b/crates/host-core/src/mode_runs/completion_report_tests.rsnew file mode 100644index 000000000..395ae81fa--- /dev/null+++ b/crates/host-core/src/mode_runs/completion_report_tests.rs@@ -0,0 +1,493 @@+//! Completion reports are model evidence, never a replacement for Host gates.++use serde_json::{json, Value};++use super::model::*;+use super::repository;+use super::snapshot_tests::goal_snapshot;+use super::tests::{+ claim, configure, control_run, fixture, mode_row, session, settle, start_run, Fixture,+};+use super::*;+use crate::db::Database;++const ARTIFACT: &str = "# Objective\nship it\n# Acceptance criteria\nworks\n# Evidence\ntests\n";++fn completed() -> Value {+ json!({"status":"completed", "outcomes":[{"criterion":"works", "outcome":"met", "evidence":"tests passed"}], "remainingWork":[]})+}++fn blocked() -> Value {+ json!({"status":"blocked", "outcomes":[{"criterion":"works", "outcome":"unverified", "evidence":"service unavailable"}], "remainingWork":["run integration tests"], "blockerReason":"service unavailable"})+}++fn setup() -> (Fixture, ModeRun) {+ let fx = fixture();+ let sid = session(&fx, "agent");+ configure(&fx.db, &sid, "goal", Some(&goal_snapshot())).unwrap();+ let run = start_run(&fx, &sid, "t1").run;+ (fx, run)+}++fn params(run: &ModeRun, report: Value) -> Value {+ json!({"sessionId":run.session_id, "runId":run.id, "turnId":"t1", "input":run.input,+ "report":report, "artifacts":{"goal":ARTIFACT}})+}++fn submit(fx: &Fixture, value: Value) -> anyhow::Result<StageOutcome> {+ complete_stage(&fx.db, &fx.workspace, serde_json::from_value(value)?)+}++fn gate_count(db: &Database, run: &ModeRun) -> i64 {+ db.conn()+ .query_row(+ "SELECT COUNT(*) FROM mode_gate_results WHERE run_id=?1",+ [&run.id],+ |row| row.get(0),+ )+ .unwrap()+}++fn invalid_reports() -> Vec<Value> {+ let mut cases = vec![Value::Null, json!({}), json!("completed")];+ let base = completed();+ for (key, value) in [+ ("status", json!("success")),+ ("extra", json!(true)),+ ("outcomes", json!([])),+ ("outcomes", json!(vec![base["outcomes"][0].clone(); 65])),+ (+ "outcomes",+ json!([base["outcomes"][0].clone(), {"criterion":" works ", "outcome":"met", "evidence":"ok"}]),+ ),+ ("remainingWork", json!(["later"])),+ ("blockerReason", json!("not complete")),+ ("blockerReason", Value::Null),+ ] {+ let mut report = base.clone();+ report[key] = value;+ cases.push(report);+ }+ let mut missing = base.clone();+ missing.as_object_mut().unwrap().remove("remainingWork");+ cases.push(missing);+ for (key, value) in [+ ("criterion", json!(" \n ")),+ ("criterion", json!("界".repeat(1366))),+ ("evidence", json!("\t")),+ ("evidence", json!("x".repeat(16385))),+ ("outcome", json!("unmet")),+ ("outcome", json!("unverified")),+ ("outcome", json!("passed")),+ ("extra", json!(1)),+ ] {+ let mut report = base.clone();+ report["outcomes"][0][key] = value;+ cases.push(report);+ }+ for (key, value) in [+ ("blockerReason", json!("")),+ ("blockerReason", json!(" \n")),+ ("blockerReason", json!("x".repeat(16385))),+ ("remainingWork", json!([" "])),+ ("remainingWork", json!(["界".repeat(1366)])),+ ("remainingWork", json!(vec!["work"; 65])),+ ] {+ let mut report = blocked();+ report[key] = value;+ cases.push(report);+ }+ let mut missing = blocked();+ missing.as_object_mut().unwrap().remove("blockerReason");+ cases.push(missing);+ let mut no_work = blocked();+ no_work["outcomes"][0]["outcome"] = json!("met");+ no_work["remainingWork"] = json!([]);+ cases.push(no_work);+ let mut large = base.clone();+ large["outcomes"] = json!((0..64).map(|i| json!({"criterion":format!("criterion {i}"), "outcome":"met", "evidence":"x".repeat(4096)})).collect::<Vec<_>>());+ assert!(serde_json::to_vec(&large).unwrap().len() > 262144);+ cases.push(large);+ cases+}++#[test]+fn completion_report_validation_is_independent_and_precedes_artifact_writes() {+ let (fx, run) = setup();+ let path = fx.workspace.join(&run.artifact_paths["goal"]);+ for (i, report) in invalid_reports().into_iter().enumerate() {+ let error = submit(&fx, params(&run, report)).unwrap_err().to_string();+ assert!(+ error.starts_with("MODE_INVALID_ARGUMENT"),+ "case {i}: {error}"+ );+ assert!(!path.exists(), "case {i} wrote an artifact");+ assert_eq!(+ repository::owned(fx.db.conn(), &run.session_id, &run.id).unwrap(),+ run+ );+ assert_eq!(gate_count(&fx.db, &run), 0);+ }+}++#[test]+fn completion_report_completed_finishes_only_after_existing_gates_and_round_trips() {+ let (fx, run) = setup();+ assert!(run.wire().get("completionReport").is_none());+ let mut no_artifact = params(&run, completed());+ no_artifact.as_object_mut().unwrap().remove("artifacts");+ let failed = submit(&fx, no_artifact).unwrap();+ assert!(matches!(failed.status, StageStatus::Failed { .. }));+ assert_eq!(failed.run.state, RunState::Running);+ assert_eq!(failed.run.wire()["completionReport"], completed());+ let finished = submit(&fx, params(&failed.run, completed())).unwrap();+ assert_eq!(finished.status, StageStatus::Finished);+ assert_eq!(finished.run.wire()["completionReport"], completed());+ assert!(finished.run.active_since_ms.is_none());+ assert_eq!(mode_row(&fx.db, &run.session_id), ("agent".into(), None));+ let settled = settle(&fx, &finished.run, "t1", TurnOutcome::Completed);+ assert!(!settled.continue_run);+ assert_eq!(+ (settled.run.rounds_completed, settled.run.tokens_used),+ (1, 100)+ );+ let db = Database::open(&fx.db.data_dir().join("pi.sqlite")).unwrap();+ assert_eq!(+ repository::owned(db.conn(), &run.session_id, &run.id).unwrap(),+ settled.run+ );+ let stored: String = db+ .conn()+ .query_row(+ "SELECT completion_report_json FROM mode_runs WHERE id=?1",+ [&run.id],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(serde_json::from_str::<Value>(&stored).unwrap(), completed());+}++#[test]+fn completion_report_blocked_waits_settles_once_reloads_and_requires_user_resume() {+ let (fx, mut run) = setup();+ // A blocked report cancels even a previously pending command, without evaluating it.+ run.pending_gate = Some(0);+ repository::save(fx.db.conn(), &mut run).unwrap();+ let outcome = submit(&fx, params(&run, blocked())).unwrap();+ assert_eq!(+ outcome.status,+ StageStatus::Blocked {+ message: "service unavailable".into()+ }+ );+ assert_eq!(outcome.run.state, RunState::Waiting);+ assert_eq!(outcome.run.wire()["waitReason"], "blocked");+ assert_eq!(outcome.run.wire()["completionReport"], blocked());+ assert_eq!(+ outcome.run.last_error.as_deref(),+ Some("service unavailable")+ );+ assert!(outcome.run.pending_gate.is_none() && outcome.run.finished_at.is_none());+ assert_eq!(outcome.run.active_turn_id.as_deref(), Some("t1"));+ assert!(outcome.run.active_since_ms.is_none());+ assert_eq!(+ (outcome.run.max_turns, outcome.run.max_tokens),+ (run.max_turns, run.max_tokens)+ );+ assert_eq!(mode_row(&fx.db, &run.session_id).0, "goal");+ assert_eq!(gate_count(&fx.db, &run), 0);+ let settled = settle(&fx, &outcome.run, "t1", TurnOutcome::Completed);+ assert!(!settled.continue_run && settled.changed);+ assert!(settled.run.active_turn_id.is_none());+ assert_eq!(+ (settled.run.rounds_completed, settled.run.tokens_used),+ (1, 100)+ );+ let duplicate = settle(&fx, &settled.run, "t1", TurnOutcome::Completed);+ assert!(!duplicate.changed && !duplicate.continue_run);+ assert_eq!(duplicate.run, settled.run);+ assert!(!claim(&fx, &settled.run, "host", Origin::Host).claimed);+ assert!(!claim(&fx, &settled.run, "approval", Origin::Approval).claimed);+ assert!(!claim(&fx, &settled.run, "user", Origin::User).claimed);+ let db = Database::open(&fx.db.data_dir().join("pi.sqlite")).unwrap();+ recover(&db).unwrap();+ assert_eq!(+ open_run(&db, &run.session_id).unwrap().unwrap(),+ settled.run+ );+ let resumed = control_run(&fx, &settled.run, ControlAction::Resume).unwrap();+ assert!(resumed.continue_run);+ assert_eq!(resumed.run.state, RunState::Running);+ assert!(claim(&fx, &resumed.run, "next", Origin::Host).claimed);+}++#[test]+fn completion_report_blocked_survives_recovery_before_settlement_and_error_settlement() {+ for outcome in [+ TurnOutcome::Completed,+ TurnOutcome::Error,+ TurnOutcome::Aborted,+ ] {+ let (fx, run) = setup();+ let blocked = submit(&fx, params(&run, blocked())).unwrap().run;+ let settled = settle(&fx, &blocked, "t1", outcome);+ assert!(!settled.continue_run);+ assert_eq!(settled.run.wire()["waitReason"], "blocked");+ assert_eq!(settled.run.last_error, blocked.last_error);+ assert!(settled.run.active_turn_id.is_none());+ }+ let (fx, run) = setup();+ let blocked = submit(&fx, params(&run, blocked())).unwrap().run;+ assert_eq!(recover(&fx.db).unwrap(), 1);+ let recovered = open_run(&fx.db, &run.session_id).unwrap().unwrap();+ assert_eq!(recovered.wire()["waitReason"], "blocked");+ assert_eq!(+ recovered.wire()["completionReport"],+ blocked.wire()["completionReport"]+ );+ assert!(recovered.active_turn_id.is_none());+ assert_eq!(recovered.elapsed_ms, blocked.elapsed_ms);+ assert_eq!(recover(&fx.db).unwrap(), 0);+ let late = settle(&fx, &recovered, "t1", TurnOutcome::Completed);+ assert!(!late.continue_run);+ assert_eq!((late.run.rounds_completed, late.run.tokens_used), (1, 100));+ assert_eq!(late.run.wire()["waitReason"], "blocked");+ assert!(!settle(&fx, &late.run, "t1", TurnOutcome::Completed).changed);+}++#[test]+fn completion_report_cannot_override_control_claim_session_or_frozen_input() {+ for report in [completed(), blocked()] {+ for action in [+ ControlAction::Pause,+ ControlAction::Stop,+ ControlAction::Remove,+ ] {+ let (fx, run) = setup();+ let controlled = control_run(&fx, &run, action).unwrap().run;+ assert_eq!(+ submit(&fx, params(&run, report.clone()))+ .unwrap_err()+ .to_string(),+ "MODE_CLAIM_MISMATCH"+ );+ assert_eq!(+ repository::owned(fx.db.conn(), &run.session_id, &run.id).unwrap(),+ controlled+ );+ }+ for field in [+ "turnId",+ "sessionId",+ "input",+ "missing-input",+ "unclaimed",+ "deleted",+ ] {+ let (fx, run) = setup();+ let mut p = params(&run, report.clone());+ let code = match field {+ "turnId" => {+ p["turnId"] = json!("stale");+ "MODE_CLAIM_MISMATCH"+ }+ "sessionId" => {+ p["sessionId"] = json!(session(&fx, "agent"));+ "MODE_RUN_NOT_FOUND"+ }+ "input" => {+ update(+ &fx.db,+ UpdateParams {+ session_id: run.session_id.clone(),+ run_id: run.id.clone(),+ expected_revision: run.revision,+ input: Some("new objective".into()),+ budget: None,+ },+ )+ .unwrap();+ "MODE_INPUT_CHANGED"+ }+ "missing-input" => {+ p.as_object_mut().unwrap().remove("input");+ "MODE_INPUT_CHANGED"+ }+ "unclaimed" => {+ settle(&fx, &run, "t1", TurnOutcome::Completed);+ "MODE_CLAIM_MISMATCH"+ }+ "deleted" => {+ fx.db+ .conn()+ .execute(+ "UPDATE sessions SET deleted_at=1 WHERE id=?1",+ [&run.session_id],+ )+ .unwrap();+ "MODE_SESSION_NOT_FOUND"+ }+ _ => unreachable!(),+ };+ let before = repository::owned(fx.db.conn(), &run.session_id, &run.id).unwrap();+ assert_eq!(submit(&fx, p).unwrap_err().to_string(), code, "{field}");+ assert_eq!(+ repository::owned(fx.db.conn(), &run.session_id, &run.id).unwrap(),+ before+ );+ assert!(!fx.workspace.join(&run.artifact_paths["goal"]).exists());+ }+ }+}++#[test]+fn completion_report_preserves_artifact_sandbox_and_atomic_gate_persistence() {+ let (fx, run) = setup();+ for report in [completed(), blocked()] {+ let mut p = params(&run, report);+ p["artifacts"] = json!({"undeclared":"not allowed"});+ assert!(submit(&fx, p).is_err());+ assert_eq!(+ repository::owned(fx.db.conn(), &run.session_id, &run.id).unwrap(),+ run+ );+ }+ fx.db.conn().execute_batch("CREATE TRIGGER reject_report BEFORE UPDATE ON mode_runs BEGIN SELECT RAISE(ABORT, 'write rejected'); END;").unwrap();+ assert!(submit(&fx, params(&run, completed())).is_err());+ assert_eq!(gate_count(&fx.db, &run), 0);+ assert_eq!(+ repository::owned(fx.db.conn(), &run.session_id, &run.id).unwrap(),+ run+ );+}++#[test]+fn completion_report_accepts_byte_limits_and_each_valid_blocked_shape() {+ for met_with_work in [false, true] {+ let (fx, run) = setup();+ let mut report = blocked();+ report["outcomes"][0]["criterion"] = json!("界".repeat(1365) + "a");+ report["outcomes"][0]["evidence"] = json!("x".repeat(16384));+ report["blockerReason"] = json!("x".repeat(16384));+ report["remainingWork"] = if met_with_work {+ json!(["x".repeat(4096)])+ } else {+ json!([])+ };+ if met_with_work {+ report["outcomes"][0]["outcome"] = json!("met");+ }+ let result = submit(&fx, params(&run, report.clone())).unwrap();+ assert_eq!(result.run.wire()["completionReport"], report);+ assert!(result.run.last_error.unwrap().len() <= 16384);+ }+ let (fx, run) = setup();+ let mut report = completed();+ report["outcomes"] = json!((0..64)+ .map(|i| json!({"criterion":format!("c{i}"), "outcome":"met", "evidence":"ok"}))+ .collect::<Vec<_>>());+ assert_eq!(+ submit(&fx, params(&run, report)).unwrap().status,+ StageStatus::Finished+ );+}++#[test]+fn completion_report_serialized_size_limit_is_inclusive() {+ let (fx, run) = setup();+ let mut report = completed();+ report["outcomes"] = json!((0..16).map(|i| json!({"criterion":format!("c{i}"), "outcome":"met", "evidence":if i < 15 { "x".repeat(16384) } else { "x".into() }})).collect::<Vec<_>>());+ let size = serde_json::to_vec(&report).unwrap().len();+ report["outcomes"][15]["evidence"] = json!("x".repeat(262144 - size + 1));+ assert_eq!(serde_json::to_vec(&report).unwrap().len(), 262144);+ assert_eq!(+ submit(&fx, params(&run, report.clone())).unwrap().status,+ StageStatus::Finished+ );+ let evidence = report["outcomes"][15]["evidence"]+ .as_str()+ .unwrap()+ .to_string()+ + "x";+ report["outcomes"][15]["evidence"] = json!(evidence);+ assert!(submit(&fx, params(&run, report))+ .unwrap_err()+ .to_string()+ .starts_with("MODE_INVALID_ARGUMENT"));+}++#[test]+fn completion_report_completed_preserves_explicit_user_approval() {+ let fx = fixture();+ let sid = session(&fx, "agent");+ let snapshot = super::tests::definition(+ "asks",+ "contract",+ json!([{"id":"review", "permission":"contract", "exit":[{"kind":"ask"}]}]),+ );+ configure(&fx.db, &sid, "asks", Some(&snapshot)).unwrap();+ let run = start_run(&fx, &sid, "t1").run;+ let mut p = params(&run, completed());+ p.as_object_mut().unwrap().remove("artifacts");+ let waiting = submit(&fx, p).unwrap();+ assert_eq!(waiting.status, StageStatus::AwaitingApproval);+ assert_eq!(waiting.run.wire()["completionReport"], completed());+ assert_eq!(waiting.run.wait_reason, Some(WaitReason::Approval));+ assert_eq!(mode_row(&fx.db, &sid).0, "asks");+ let settled = settle(&fx, &waiting.run, "t1", TurnOutcome::Completed);+ assert!(!settled.continue_run);+ let approved = resolve(+ &fx.db,+ ResolveParams {+ session_id: sid.clone(),+ run_id: run.id,+ expected_revision: settled.run.revision,+ action: ResolveAction::Approve,+ },+ )+ .unwrap();+ assert_eq!(approved.run.state, RunState::Finished);+ assert_eq!(approved.run.wire()["completionReport"], completed());+ assert_eq!(mode_row(&fx.db, &sid).0, "agent");+}++#[test]+fn completion_report_blocked_cannot_reset_budget_or_replace_snapshot_authority() {+ let (fx, run) = setup();+ let limited = update(+ &fx.db,+ UpdateParams {+ session_id: run.session_id.clone(),+ run_id: run.id.clone(),+ expected_revision: run.revision,+ input: None,+ budget: Some(super::budget::RunBudget {+ max_turns: Some(1),+ max_tokens: Some(1_000),+ }),+ },+ )+ .unwrap()+ .run;+ let blocked = submit(&fx, params(&limited, blocked())).unwrap().run;+ let settled = settle(&fx, &blocked, "t1", TurnOutcome::Completed);+ assert_eq!(+ (settled.run.max_turns, settled.run.max_tokens),+ (Some(1), Some(1_000))+ );+ let resumed = control_run(&fx, &settled.run, ControlAction::Resume)+ .unwrap()+ .run;+ assert!(!claim(&fx, &resumed, "host", Origin::Host).claimed);+ assert_eq!(resumed.snapshot_hash, run.snapshot_hash);+ assert_eq!(+ tool_policy(&fx.db, &run.session_id).unwrap(),+ Some(ToolPolicy::Agent)+ );+ // Even a blocked result must refer to a real stage in the frozen snapshot.+ fx.db.conn().execute("UPDATE mode_runs SET stage_id='missing', active_turn_id='t1', active_origin='user' WHERE id=?1", [&run.id]).unwrap();+ assert!(submit(&fx, params(&resumed, self::blocked()))+ .unwrap_err()+ .to_string()+ .starts_with("MODE_SNAPSHOT_INVALID"));+}diff --git a/crates/host-core/src/mode_runs/edit_tests.rs b/crates/host-core/src/mode_runs/edit_tests.rsindex c00c8a2bd..43f5d99d0 100644--- a/crates/host-core/src/mode_runs/edit_tests.rs+++ b/crates/host-core/src/mode_runs/edit_tests.rs@@ -46,6 +46,7 @@ fn complete_with_input(summary: "done".into(),artifacts: Some(BTreeMap::from([("goal".to_string(), artifact.to_string())])),input: Some(input.into()),+ report: None,},)}diff --git a/crates/host-core/src/mode_runs/elapsed_tests.rs b/crates/host-core/src/mode_runs/elapsed_tests.rsnew file mode 100644index 000000000..5274566af--- /dev/null+++ b/crates/host-core/src/mode_runs/elapsed_tests.rs@@ -0,0 +1,445 @@+//! Host-owned elapsed checkpoints, frozen states, recovery and schema v30.++use std::collections::BTreeMap;+use std::path::Path;++use rusqlite::{params, Connection};+use serde_json::json;++use super::model::{+ ControlAction, ModeRun, Origin, RunState, TurnOutcome, WaitReason, MAX_SAFE_INTEGER,+};+use super::repository;+use super::tests::{+ claim, configure, control_run, definition, fixture, session, settle, start_run,+};+use crate::db::{migration_backup_path, Database, SCHEMA_VERSION};++fn clock_run(db: &Database, id: &str, state: RunState) -> ModeRun {+ db.conn()+ .execute(+ "INSERT INTO sessions(id,mode,created_at,updated_at) VALUES (?1,'agent',1,1)",+ [id],+ )+ .unwrap();+ db.conn()+ .execute(+ "INSERT OR IGNORE INTO mode_snapshots(hash,json,created_at) VALUES ('clock','{}','t')",+ [],+ )+ .unwrap();+ let run = ModeRun {+ id: id.into(),+ session_id: id.into(),+ mode_id: "goal".into(),+ snapshot_hash: "clock".into(),+ input: "work".into(),+ stage_id: "work".into(),+ state,+ wait_reason: (state == RunState::Waiting).then_some(WaitReason::Approval),+ last_error: None,+ revision: 1,+ active_turn_id: (state == RunState::Running).then(|| format!("{id}-turn")),+ active_origin: (state == RunState::Running).then_some(Origin::User),+ stage_entered: false,+ advanced_in_turn: false,+ pending_gate: None,+ retry_counts: BTreeMap::new(),+ rounds_completed: 0,+ tokens_used: 0,+ max_turns: Some(20),+ max_tokens: None,+ artifact_paths: BTreeMap::new(),+ settled_turns: Vec::new(),+ completion_report: None,+ elapsed_ms: 0,+ active_since_ms: (state == RunState::Running).then_some(1_000),+ created_at: 1,+ updated_at: 1_000,+ finished_at: None,+ };+ repository::insert(db.conn(), &run).unwrap();+ run+}++fn assert_clock(db: &Database, run: &ModeRun, elapsed: i64, since: Option<i64>) {+ let stored = repository::owned(db.conn(), &run.session_id, &run.id).unwrap();+ assert_eq!(stored, *run);+ assert_eq!((run.elapsed_ms, run.active_since_ms), (elapsed, since));+ let wire = run.wire();+ assert_eq!(wire["elapsedMs"], json!(elapsed));+ assert_eq!(+ wire.get("activeSinceMs"),+ since.map(|ms| json!(ms)).as_ref()+ );+}++#[test]+fn elapsed_checkpoints_round_trip_and_ignore_caller_timing_fields() {+ let fx = fixture();+ let mut run = clock_run(&fx.db, "r", RunState::Running);+ assert_clock(&fx.db, &run, 0, Some(1_000));+ let mut stale = run.clone();+ run.elapsed_ms = MAX_SAFE_INTEGER;+ run.active_since_ms = Some(0);+ repository::save_at(fx.db.conn(), &mut run, 2_000).unwrap();+ assert_clock(&fx.db, &run, 1_000, Some(2_000));+ stale.set_state(RunState::Paused);+ assert_eq!(+ repository::save_at(fx.db.conn(), &mut stale, 3_000)+ .unwrap_err()+ .to_string(),+ "MODE_REVISION_CONFLICT"+ );+ assert_clock(&fx.db, &run, 1_000, Some(2_000));+ repository::save_at(fx.db.conn(), &mut run, 2_500).unwrap();+ assert_clock(&fx.db, &run, 1_500, Some(2_500));+ run.set_state(RunState::Paused);+ repository::save_at(fx.db.conn(), &mut run, 3_000).unwrap();+ assert_clock(&fx.db, &run, 2_000, None);+ repository::save_at(fx.db.conn(), &mut run, 9_000).unwrap();+ assert_clock(&fx.db, &run, 2_000, None);+ run.clear_claim();+ run.set_state(RunState::Running);+ repository::save_at(fx.db.conn(), &mut run, 10_000).unwrap();+ assert_clock(&fx.db, &run, 2_000, Some(10_000));+ run.set_state(RunState::Stopped);+ repository::save_at(fx.db.conn(), &mut run, 10_500).unwrap();+ assert_clock(&fx.db, &run, 2_500, None);+}++#[test]+fn elapsed_freezes_in_every_non_running_state_even_with_a_claim() {+ for (state, reason) in [+ (RunState::Paused, None),+ (RunState::Waiting, Some(WaitReason::Approval)),+ (RunState::Waiting, Some(WaitReason::Retries)),+ (RunState::Waiting, Some(WaitReason::TurnEnd)),+ (RunState::Waiting, Some(WaitReason::Error)),+ (RunState::BudgetExhausted, None),+ (RunState::Finished, None),+ (RunState::Stopped, None),+ ] {+ let fx = fixture();+ let mut run = clock_run(&fx.db, "r", RunState::Running);+ run.set_state(state);+ run.wait_reason = reason;+ repository::save_at(fx.db.conn(), &mut run, 2_000).unwrap();+ assert_clock(&fx.db, &run, 1_000, None);+ repository::save_at(fx.db.conn(), &mut run, 9_000).unwrap();+ assert_clock(&fx.db, &run, 1_000, None);+ if state.is_open() {+ run.set_state(RunState::Running);+ repository::save_at(fx.db.conn(), &mut run, 10_000).unwrap();+ assert_clock(&fx.db, &run, 1_000, Some(10_000));+ repository::save_at(fx.db.conn(), &mut run, 10_500).unwrap();+ assert_clock(&fx.db, &run, 1_500, Some(10_500));+ }+ }+}++#[test]+fn elapsed_is_bounded_and_a_backwards_clock_never_recounts_an_interval() {+ let fx = fixture();+ let mut run = clock_run(&fx.db, "r", RunState::Running);+ for (now, elapsed, since) in [+ (2_000, 1_000, 2_000),+ (1_500, 1_000, 2_000),+ (2_100, 1_100, 2_100),+ ] {+ repository::save_at(fx.db.conn(), &mut run, now).unwrap();+ assert_clock(&fx.db, &run, elapsed, Some(since));+ }+ fx.db+ .conn()+ .execute(+ "UPDATE mode_runs SET elapsed_ms = ?1 WHERE id = 'r'",+ [MAX_SAFE_INTEGER - 1],+ )+ .unwrap();+ repository::save_at(fx.db.conn(), &mut run, i64::MAX).unwrap();+ assert_clock(&fx.db, &run, MAX_SAFE_INTEGER, Some(MAX_SAFE_INTEGER));+ run.set_state(RunState::Paused);+ repository::save_at(fx.db.conn(), &mut run, i64::MAX).unwrap();+ assert_clock(&fx.db, &run, MAX_SAFE_INTEGER, None);+ run.set_state(RunState::Running);+ repository::save_at(fx.db.conn(), &mut run, i64::MIN).unwrap();+ assert_clock(&fx.db, &run, MAX_SAFE_INTEGER, Some(0));+}++#[test]+fn elapsed_user_path_pause_settle_duplicate_resume_and_stop() {+ let fx = fixture();+ let sid = session(&fx, "agent");+ let snapshot = definition(+ "clock-flow",+ "agent",+ json!([{ "id": "work", "permission": "agent", "loop": true, "exit": [] }]),+ );+ configure(&fx.db, &sid, "clock-flow", Some(&snapshot)).unwrap();+ let run = start_run(&fx, &sid, "t1").run;+ assert_clock(&fx.db, &run, 0, Some(run.created_at));+ let paused = control_run(&fx, &run, ControlAction::Pause).unwrap();+ let elapsed = paused.run.updated_at.saturating_sub(run.created_at).max(0);+ assert_clock(&fx.db, &paused.run, elapsed, None);+ let duplicate_pause = control_run(&fx, &paused.run, ControlAction::Pause).unwrap();+ assert!(!duplicate_pause.changed);+ assert_eq!(duplicate_pause.run, paused.run);+ let settled = settle(&fx, &paused.run, "t1", TurnOutcome::Completed);+ assert_clock(&fx.db, &settled.run, elapsed, None);+ let duplicate = settle(&fx, &settled.run, "t1", TurnOutcome::Completed);+ assert!(!duplicate.changed);+ assert_eq!(duplicate.run, settled.run);+ let resumed = control_run(&fx, &settled.run, ControlAction::Resume).unwrap();+ assert_clock(&fx.db, &resumed.run, elapsed, Some(resumed.run.updated_at));+ let claimed = claim(&fx, &resumed.run, "t2", Origin::Host);+ assert!(claimed.claimed);+ let stopped = control_run(&fx, &claimed.run, ControlAction::Stop).unwrap();+ let elapsed = claimed.run.elapsed_ms+ + stopped+ .run+ .updated_at+ .saturating_sub(claimed.run.active_since_ms.unwrap())+ .max(0);+ assert_clock(&fx.db, &stopped.run, elapsed, None);+ let late_settlement = settle(&fx, &stopped.run, "t2", TurnOutcome::Completed);+ assert_clock(&fx.db, &late_settlement.run, elapsed, None);+}++#[test]+fn elapsed_recovery_discards_offline_time_with_and_without_a_claim() {+ let fx = fixture();+ let path = fx.db.data_dir().join("pi.sqlite");+ let mut claimed = clock_run(&fx.db, "claimed", RunState::Running);+ repository::save_at(fx.db.conn(), &mut claimed, 2_000).unwrap();+ let mut between = clock_run(&fx.db, "between", RunState::Running);+ between.clear_claim();+ repository::save_at(fx.db.conn(), &mut between, 1_500).unwrap();+ let waiting = clock_run(&fx.db, "waiting", RunState::Waiting);+ let stopped = clock_run(&fx.db, "stopped", RunState::Stopped);+ drop(fx.db);+ let db = Database::open(&path).unwrap();+ let mut ids = repository::release_stale_claims_at(db.conn(), 9_000_000).unwrap();+ ids.sort();+ assert_eq!(ids, ["between", "claimed"]);+ for (id, elapsed) in [("claimed", 1_000), ("between", 500)] {+ let run = repository::owned(db.conn(), id, id).unwrap();+ assert_eq!(run.state, RunState::Paused);+ assert!(run.active_turn_id.is_none() && run.active_origin.is_none());+ assert_clock(&db, &run, elapsed, None);+ }+ assert_clock(&db, &waiting, 0, None);+ assert_clock(&db, &stopped, 0, None);+ assert!(repository::release_stale_claims_at(db.conn(), 10_000_000)+ .unwrap()+ .is_empty());+ let mut run = repository::owned(db.conn(), "claimed", "claimed").unwrap();+ run.set_state(RunState::Running);+ repository::save_at(db.conn(), &mut run, 10_000_000).unwrap();+ assert_clock(&db, &run, 1_000, Some(10_000_000));+ run.set_state(RunState::Paused);+ repository::save_at(db.conn(), &mut run, 10_000_500).unwrap();+ assert_clock(&db, &run, 1_500, None);+}++fn has_column(conn: &Connection, table: &str, column: &str) -> bool {+ conn.query_row(+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = ?2)",+ [table, column],+ |row| row.get(0),+ )+ .unwrap()+}++const LEGACY_STATES: [&str; 6] = [+ "running",+ "waiting",+ "paused",+ "budget_exhausted",+ "finished",+ "stopped",+];++fn populated_v29(path: &Path) {+ let db = Database::open(path).unwrap();+ db.conn()+ .execute_batch(+ "ALTER TABLE mode_runs DROP COLUMN active_since_ms;+ ALTER TABLE mode_runs DROP COLUMN elapsed_ms;+ ALTER TABLE turn_queue DROP COLUMN start_goal;+ INSERT INTO mode_snapshots(hash,json,created_at) VALUES ('legacy','{}','t');+ PRAGMA user_version = 29;",+ )+ .unwrap();+ for state in LEGACY_STATES {+ db.conn()+ .execute(+ "INSERT INTO sessions(id,mode,created_at,updated_at) VALUES (?1,'goal',1,2)",+ [state],+ )+ .unwrap();+ db.conn()+ .execute(+ "INSERT INTO mode_runs(id,session_id,mode_id,snapshot_hash,input,stage_id,+ state,wait_reason,revision,artifact_paths,tokens_used,created_at,updated_at)+ VALUES (?1,?1,'goal','legacy','saved objective','work',?1,?2,7,'{}',321,1,2)",+ params![state, (state == "waiting").then_some("approval")],+ )+ .unwrap();+ }+ db.conn()+ .execute_batch(+ "INSERT INTO mode_gate_results(run_id,stage_id,gate_index,action,passed,evidence,created_at)+ VALUES ('finished','work',0,'require',1,'saved evidence',2);+ INSERT INTO turn_queue(id,session_id,principal,input_hash,content,permission_mode,+ position,created_at) VALUES ('queued','running','user','hash','keep queued','ask',1,2);",+ )+ .unwrap();+}++#[test]+fn elapsed_schema_29_upgrade_preserves_populated_runs_queue_and_backup() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ populated_v29(&path);+ let db = Database::open(&path).unwrap();+ let version: i64 = db+ .conn()+ .query_row("PRAGMA user_version", [], |r| r.get(0))+ .unwrap();+ assert_eq!(version, 31);+ assert_eq!(version, SCHEMA_VERSION);+ for state in LEGACY_STATES {+ let run = repository::owned(db.conn(), state, state).unwrap();+ assert_eq!(run.state.as_str(), state);+ assert_eq!(+ (+ run.revision,+ run.tokens_used,+ run.created_at,+ run.updated_at+ ),+ (7, 321, 1, 2)+ );+ assert_eq!(run.input, "saved objective");+ assert_clock(&db, &run, 0, None);+ }+ let queued: (String, i64) = db+ .conn()+ .query_row(+ "SELECT content, start_goal FROM turn_queue WHERE id = 'queued'",+ [],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .unwrap();+ assert_eq!(queued, ("keep queued".into(), 0));+ let evidence: String = db+ .conn()+ .query_row(+ "SELECT evidence FROM mode_gate_results WHERE run_id = 'finished'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(evidence, "saved evidence");+ let backup = Connection::open(migration_backup_path(&path, 29)).unwrap();+ let version: i64 = backup+ .query_row("PRAGMA user_version", [], |r| r.get(0))+ .unwrap();+ assert_eq!(version, 29);+ assert!(!has_column(&backup, "mode_runs", "elapsed_ms"));+ assert!(!has_column(&backup, "mode_runs", "active_since_ms"));+ assert!(!has_column(&backup, "turn_queue", "start_goal"));+ let count: i64 = backup+ .query_row("SELECT COUNT(*) FROM mode_runs", [], |r| r.get(0))+ .unwrap();+ assert_eq!(count, 6);+ let mut legacy = repository::owned(db.conn(), "running", "running").unwrap();+ repository::save_at(db.conn(), &mut legacy, 50_000).unwrap();+ assert_clock(&db, &legacy, 0, Some(50_000));+ legacy.set_state(RunState::Paused);+ repository::save_at(db.conn(), &mut legacy, 50_500).unwrap();+ assert_clock(&db, &legacy, 500, None);+ drop(db);+ let reopened = Database::open(&path).unwrap();+ assert_clock(&reopened, &legacy, 500, None);+}++#[test]+fn elapsed_schema_fresh_and_upgraded_have_identical_defaults_and_bounds() {+ let fresh = fixture();+ clock_run(&fresh.db, "fresh", RunState::Paused);+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ populated_v29(&path);+ let upgraded = Database::open(&path).unwrap();+ for (table, column, expected) in [+ (+ "mode_runs",+ "elapsed_ms",+ ("INTEGER".to_string(), 1, Some("0".to_string())),+ ),+ (+ "mode_runs",+ "active_since_ms",+ ("INTEGER".to_string(), 0, None),+ ),+ (+ "turn_queue",+ "start_goal",+ ("INTEGER".to_string(), 1, Some("0".to_string())),+ ),+ ] {+ for db in [&fresh.db, &upgraded] {+ let stored: (String, i64, Option<String>) = db.conn().query_row(+ "SELECT type, \"notnull\", dflt_value FROM pragma_table_info(?1) WHERE name = ?2",+ [table, column], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ ).unwrap();+ assert_eq!(stored, expected);+ }+ }+ for db in [&fresh.db, &upgraded] {+ for invalid in [-1, MAX_SAFE_INTEGER + 1] {+ assert!(db+ .conn()+ .execute("UPDATE mode_runs SET elapsed_ms = ?1", [invalid])+ .is_err());+ assert!(db+ .conn()+ .execute("UPDATE mode_runs SET active_since_ms = ?1", [invalid])+ .is_err());+ }+ }+ upgraded+ .conn()+ .execute("UPDATE turn_queue SET start_goal = 1", [])+ .unwrap();+ assert!(upgraded+ .conn()+ .execute("UPDATE turn_queue SET start_goal = 2", [])+ .is_err());+ assert!(upgraded+ .conn()+ .execute("UPDATE turn_queue SET start_goal = NULL", [])+ .is_err());+}++#[test]+fn elapsed_schema_30_failure_rolls_back_all_additions_and_version() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ populated_v29(&path);+ let conn = Connection::open(&path).unwrap();+ // Force the last additive DDL to fail after both clock columns were added.+ conn.execute_batch("DROP TABLE turn_queue;").unwrap();+ drop(conn);+ assert!(Database::open(&path).is_err());+ let conn = Connection::open(&path).unwrap();+ let version: i64 = conn+ .query_row("PRAGMA user_version", [], |r| r.get(0))+ .unwrap();+ assert_eq!(version, 29);+ assert!(!has_column(&conn, "mode_runs", "elapsed_ms"));+ assert!(!has_column(&conn, "mode_runs", "active_since_ms"));+ assert!(migration_backup_path(&path, 29).is_file());+}diff --git a/crates/host-core/src/mode_runs/engine.rs b/crates/host-core/src/mode_runs/engine.rsindex bcd13de33..2fef3c4dc 100644--- a/crates/host-core/src/mode_runs/engine.rs+++ b/crates/host-core/src/mode_runs/engine.rs@@ -98,6 +98,30 @@ pub fn open_run(db: &Database, session_id: &str) -> Result<Option<ModeRun>> {/// `modes.start`: open a run of the session's staged mode for the user turn/// that started it. `workspace` receives template artifacts.pub fn start(db: &Database, workspace: &Path, params: StartParams) -> Result<ClaimResult> {+ start_with_snapshot(db, workspace, params, None)+}++/// An explicit queued Goal starts independently from the input preference.+pub fn start_goal(+ db: &Database,+ workspace: &Path,+ params: StartParams,+ value: &Value,+) -> Result<ClaimResult> {+ start_with_snapshot(+ db,+ workspace,+ params,+ Some(snapshot::validate(value, GOAL_MODE_ID)?),+ )+}++fn start_with_snapshot(+ db: &Database,+ workspace: &Path,+ params: StartParams,+ explicit: Option<Snapshot>,+) -> Result<ClaimResult> {require_text(¶ms.turn_id, "turnId")?;if params.input.len() > MAX_TEXT_BYTES {return Err(invalid_argument("input is too long"));@@ -105,12 +129,18 @@ pub fn start(db: &Database, workspace: &Path, params: StartParams) -> Result<Clalet conn = db.conn();let (mode, hash) = repository::session_mode_row(conn, ¶ms.session_id)?.ok_or_else(|| mode_error("MODE_SESSION_NOT_FOUND"))?;- let snapshot = match hash {- Some(hash) => snapshot::load(conn, &hash)?,- None => None,+ let snapshot = match explicit {+ Some(snapshot) => snapshot,+ None => match hash {+ Some(hash) => snapshot::load(conn, &hash)?,+ None => None,+ }+ .filter(|snapshot| snapshot.definition.id == mode && snapshot.definition.is_staged())+ .ok_or_else(|| mode_error("MODE_NOT_STAGED"))?,+ };+ if !snapshot.definition.is_staged() {+ return Err(mode_error("MODE_NOT_STAGED"));}- .filter(|snapshot| snapshot.definition.id == mode && snapshot.definition.is_staged())- .ok_or_else(|| mode_error("MODE_NOT_STAGED"))?;if repository::open_run(conn, ¶ms.session_id)?.is_some() {return Err(mode_error("MODE_RUN_ACTIVE"));}@@ -145,7 +175,7 @@ pub fn start(db: &Database, workspace: &Path, params: StartParams) -> Result<Clalet run = ModeRun {id,session_id: params.session_id,- mode_id: mode,+ mode_id: definition.id.clone(),snapshot_hash: snapshot.hash.clone(),input: params.input,stage_id: first.id.clone(),@@ -162,15 +192,21 @@ pub fn start(db: &Database, workspace: &Path, params: StartParams) -> Result<Claretry_counts: BTreeMap::new(),rounds_completed: 0,tokens_used: 0,+ elapsed_ms: 0,+ active_since_ms: Some(now),max_turns: budget.max_turns,max_tokens: budget.max_tokens,artifact_paths,settled_turns: Vec::new(),+ completion_report: None,created_at: now,updated_at: now,finished_at: None,};- repository::insert(conn, &run)?;+ let tx = conn.unchecked_transaction()?;+ snapshot::store(&tx, &snapshot)?;+ repository::insert(&tx, &run)?;+ tx.commit()?;if let Err(error) = artifacts::seed_templates(workspace, definition, &run.artifact_paths) {// The run is valid without its templates; the agent writes the file.tracing::warn!(run_id = %run.id, %error, "mode run template seeding failed");@@ -212,6 +248,7 @@ pub fn claim_turn(db: &Database, params: ClaimParams) -> Result<ClaimResult> {if !run.state.is_open()|| run.active_turn_id.is_some()|| run.revision != params.expected_revision+ || run.wait_reason == Some(WaitReason::Blocked){return Ok(not_claimed(run));}@@ -313,6 +350,8 @@ pub fn settle_turn(db: &Database, params: SettleParams) -> Result<ContinueResultif held && run.state.is_open() {run.clear_claim();match params.outcome {+ // A model blocker is durable even if closing its turn aborts or errors.+ _ if run.wait_reason == Some(WaitReason::Blocked) => {}TurnOutcome::Aborted => run.set_state(RunState::Paused),TurnOutcome::Error => {run.set_waiting(WaitReason::Error);@@ -385,8 +424,9 @@ pub fn control(db: &Database, params: ControlParams) -> Result<ContinueResult> {}_ => return Ok(unchanged(run)),},- ControlAction::Resume => match run.state {- RunState::Paused | RunState::BudgetExhausted => {+ ControlAction::Resume => match (run.state, run.wait_reason) {+ (RunState::Paused | RunState::BudgetExhausted, _)+ | (RunState::Waiting, Some(WaitReason::Blocked)) => {run.set_state(RunState::Running);continue_run = run.active_turn_id.is_none();}@@ -495,8 +535,8 @@ pub fn resolve(db: &Database, params: ResolveParams) -> Result<ContinueResult> {})}-/// Startup recovery: claims die with the process that held them. Their runs-/// pause; nothing is replayed.+/// Startup recovery: claims die with the process that held them. Runs pause+/// unless already blocked waiting for the user; nothing is replayed.pub fn recover(db: &Database) -> Result<usize> {Ok(repository::release_stale_claims(db.conn())?.len())}@@ -564,7 +604,7 @@ pub fn prepare_session_mode(};let mut pause = None;if let Some(run) = repository::open_run(db.conn(), session_id)? {- if run.mode_id != mode {+ if run.mode_id != mode && !(run.mode_id == GOAL_MODE_ID && mode == "agent") {if snapshot.as_ref().is_some_and(|snapshot| snapshot.definition.is_staged())@@ -597,3 +637,8 @@ pub fn configure_session_mode(db: &Database, prepared: PreparedMode) -> Result<Orepository::save(db.conn(), &mut run)?;Ok(Some(run))}++/// Compare-and-reset only the builtin Goal input preference, never model or permission.+pub fn reset_goal_input(db: &Database, session_id: &str) -> Result<()> {+ repository::return_session_mode(db.conn(), session_id, GOAL_MODE_ID, "agent")+}diff --git a/crates/host-core/src/mode_runs/gates.rs b/crates/host-core/src/mode_runs/gates.rsindex 064e45a63..2ba2b2925 100644--- a/crates/host-core/src/mode_runs/gates.rs+++ b/crates/host-core/src/mode_runs/gates.rs@@ -9,6 +9,7 @@ use std::time::Instant;use anyhow::Result;use super::artifacts;+use super::completion_report::{CompletionReport, CompletionStatus};use super::engine::{apply_finish, pass_transition, Transition};use super::model::{tail, CompleteStageParams, GateResultParams, ModeRun, RunState, StageOutcome, StageStatus,@@ -241,7 +242,16 @@ fn claimed_run(if run.state != RunState::Running || !run.claimed_by(turn_id) {return Err(mode_error("MODE_CLAIM_MISMATCH"));}+ if repository::session_mode_row(db.conn(), session_id)?.is_none() {+ return Err(mode_error("MODE_SESSION_NOT_FOUND"));+ }let definition = snapshot::require(db.conn(), &run.snapshot_hash)?.definition;+ if definition.id != run.mode_id || definition.stage(&run.stage_id).is_none() {+ return Err(mode_error_detail(+ "MODE_SNAPSHOT_INVALID",+ "run stage is missing or mismatched",+ ));+ }Ok((run, definition))}@@ -258,14 +268,17 @@ pub fn complete_stage("summary is too long",));}+ let report = params.report.map(CompletionReport::parse).transpose()?;let (mut run, definition) =claimed_run(db, ¶ms.session_id, ¶ms.run_id, ¶ms.turn_id)?;// The user edited the objective while this turn ran: its evidence is for- // the old objective. The next claim carries the new one.- if params- .input- .as_ref()- .is_some_and(|input| *input != run.input)+ // the old objective. The next claim carries the new one. Reports must+ // include that frozen input; legacy calls without reports remain valid.+ if (report.is_some() && params.input.is_none())+ || params+ .input+ .as_ref()+ .is_some_and(|input| *input != run.input){return Err(mode_error("MODE_INPUT_CHANGED"));}@@ -273,6 +286,24 @@ pub fn complete_stage(artifacts::write_declared(workspace, &run.artifact_paths, artifacts)?;}run.pending_gate = None;+ let blocked_reason = report+ .as_ref()+ .filter(|report| report.status == CompletionStatus::Blocked)+ .and_then(|report| report.blocker_reason.clone());+ if let Some(report) = report {+ run.completion_report = Some(report);+ }+ if let Some(message) = blocked_reason {+ run.set_waiting(WaitReason::Blocked);+ run.last_error = Some(message.clone());+ run.advanced_in_turn = false;+ let stage_id = run.stage_id.clone();+ persist(db, &mut run, &definition, &stage_id, &[])?;+ return Ok(StageOutcome {+ status: StageStatus::Blocked { message },+ run,+ });+ }let stage_id = run.stage_id.clone();let evaluation = evaluate_from(workspace, &mut run, &definition, 0, Vec::new())?;persist(db, &mut run, &definition, &stage_id, &evaluation.records)?;diff --git a/crates/host-core/src/mode_runs/model.rs b/crates/host-core/src/mode_runs/model.rsindex a1e4bc50f..cbf52f465 100644--- a/crates/host-core/src/mode_runs/model.rs+++ b/crates/host-core/src/mode_runs/model.rs@@ -61,6 +61,7 @@ pub enum WaitReason {Retries,TurnEnd,Error,+ Blocked,}impl WaitReason {@@ -70,6 +71,7 @@ impl WaitReason {Self::Retries => "retries",Self::TurnEnd => "turn_end",Self::Error => "error",+ Self::Blocked => "blocked",}}@@ -79,13 +81,14 @@ impl WaitReason {"retries" => Self::Retries,"turn_end" => Self::TurnEnd,"error" => Self::Error,+ "blocked" => Self::Blocked,_ => return None,})}}-/// Who started the turn holding the claim. Host-started turns are capped at-/// `accept-edits`.+/// Who started the turn holding the claim. Custom Host-started modes are capped+/// at `accept-edits`; builtin Goal keeps the selected session permission.#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]#[serde(rename_all = "lowercase")]pub enum Origin {@@ -137,6 +140,12 @@ pub struct ModeRun {pub max_tokens: Option<i64>,pub artifact_paths: BTreeMap<String, String>,pub settled_turns: Vec<String>,+ /// Model evidence only; never an independent Host gate verdict.+ pub completion_report: Option<super::completion_report::CompletionReport>,+ /// Checkpointed running time, bounded to a JavaScript-safe integer.+ pub elapsed_ms: i64,+ /// Epoch ms at the latest running checkpoint; absent while frozen.+ pub active_since_ms: Option<i64>,pub created_at: i64,pub updated_at: i64,pub finished_at: Option<i64>,@@ -168,9 +177,16 @@ impl ModeRun {}out.insert("roundsCompleted".into(), json!(self.rounds_completed));out.insert("tokensUsed".into(), json!(self.tokens_used));+ out.insert("elapsedMs".into(), json!(self.elapsed_ms));+ if let Some(since) = self.active_since_ms {+ out.insert("activeSinceMs".into(), json!(since));+ }out.insert("maxTurns".into(), json!(self.max_turns));out.insert("maxTokens".into(), json!(self.max_tokens));out.insert("artifactPaths".into(), json!(self.artifact_paths));+ if let Some(report) = &self.completion_report {+ out.insert("completionReport".into(), json!(report));+ }out.insert("createdAt".into(), json!(ms_to_ts(self.created_at)));out.insert("updatedAt".into(), json!(ms_to_ts(self.updated_at)));if let Some(finished) = self.finished_at {@@ -260,6 +276,12 @@ pub struct CompleteStageParams {/// user edited the objective during the turn (`MODE_INPUT_CHANGED`).#[serde(default)]pub input: Option<String>,+ /// Kept raw until independent Host validation, including explicit null.+ #[serde(+ default,+ deserialize_with = "super::completion_report::deserialize_report"+ )]+ pub report: Option<Value>,}#[derive(Debug, Deserialize)]diff --git a/crates/host-core/src/mode_runs/policy.rs b/crates/host-core/src/mode_runs/policy.rsindex 22f3dac39..15495458b 100644--- a/crates/host-core/src/mode_runs/policy.rs+++ b/crates/host-core/src/mode_runs/policy.rs@@ -38,7 +38,7 @@ impl ToolPolicy {/// Everything `tools.execute` needs to authorize one call.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Authorization {- /// The persisted session mode (audit only).+ /// Host-resolved execution mode; the input preference may already be Agent.pub mode: String,pub policy: ToolPolicy,/// A Host-started continuation turn holds the session's run claim.@@ -60,10 +60,10 @@ impl Authorization {}}- /// Host-started turns run at most `accept-edits`: nobody is watching a- /// continuation the user did not send.+ /// A builtin Goal keeps the user's session permission across its turns.+ /// Other unattended staged modes retain their existing permission ceiling.pub fn cap_permission_mode(&self, effective: String) -> String {- if self.host_turn && effective == "auto" {+ if self.host_turn && self.mode != "goal" && effective == "auto" {"accept-edits".into()} else {effective@@ -111,6 +111,19 @@ fn resolve(})}+/// A claimed builtin Goal remains the execution identity after input reset.+/// An explicit Plan selection still applies its contract hard deny.+fn execution_mode(conn: &Connection, session_id: &str, mode: String) -> Result<String> {+ if mode == "agent" {+ if let Some(run) = repository::open_run(conn, session_id)? {+ if run.mode_id == "goal" && run.active_turn_id.is_some() {+ return Ok(run.mode_id);+ }+ }+ }+ Ok(mode)+}+/// Tool policy of a session, or `None` for an unknown session.pub fn tool_policy(db: &Database, session_id: &str) -> Result<Option<ToolPolicy>> {tool_policy_conn(db.conn(), session_id)@@ -121,7 +134,11 @@ pub fn tool_policy_conn(conn: &Connection, session_id: &str) -> Result<Option<Tolet Some((mode, hash)) = session_row(conn, session_id)? else {return Ok(None);};- let mode = crate::sessions::normalize_mode(Some(&mode));+ let mode = execution_mode(+ conn,+ session_id,+ crate::sessions::normalize_mode(Some(&mode)),+ )?;resolve(conn, session_id, &mode, hash.as_deref()).map(Some)}@@ -131,7 +148,11 @@ pub fn authorization(db: &Database, session_id: &str) -> Result<Option<Authorizalet Some((mode, hash)) = session_row(conn, session_id)? else {return Ok(None);};- let mode = crate::sessions::normalize_mode(Some(&mode));+ let mode = execution_mode(+ conn,+ session_id,+ crate::sessions::normalize_mode(Some(&mode)),+ )?;let policy = resolve(conn, session_id, &mode, hash.as_deref())?;let host_turn = repository::host_turn_active(conn, session_id)?;Ok(Some(Authorization {diff --git a/crates/host-core/src/mode_runs/repository.rs b/crates/host-core/src/mode_runs/repository.rsindex 58ca597ea..92cf59c49 100644--- a/crates/host-core/src/mode_runs/repository.rs+++ b/crates/host-core/src/mode_runs/repository.rs@@ -13,7 +13,8 @@ pub const MAX_EVIDENCE_BYTES: usize = 8 * 1024;const COLUMNS: &str = "id, session_id, mode_id, snapshot_hash, input, stage_id, state, \wait_reason, last_error, revision, active_turn_id, active_origin, stage_entered, \advanced_in_turn, pending_gate, retry_counts, rounds_completed, tokens_used, max_turns, \- max_tokens, artifact_paths, settled_turns, created_at, updated_at, finished_at";+ max_tokens, artifact_paths, settled_turns, created_at, updated_at, finished_at, \+ elapsed_ms, active_since_ms, completion_report_json";const OPEN_STATES: &str = "('running', 'waiting', 'paused', 'budget_exhausted')";@@ -47,6 +48,7 @@ fn parsed<T>(index: usize, raw: String, parse: impl Fn(&str) -> Option<T>) -> rufn from_row(row: &Row<'_>) -> rusqlite::Result<ModeRun> {let wait_reason: Option<String> = row.get(7)?;let active_origin: Option<String> = row.get(11)?;+ let completion_report: Option<String> = row.get(27)?;Ok(ModeRun {id: row.get(0)?,session_id: row.get(1)?,@@ -77,6 +79,11 @@ fn from_row(row: &Row<'_>) -> rusqlite::Result<ModeRun> {created_at: row.get(22)?,updated_at: row.get(23)?,finished_at: row.get(24)?,+ elapsed_ms: row.get(25)?,+ active_since_ms: row.get(26)?,+ completion_report: completion_report+ .map(|raw| serde_json::from_str(&raw).map_err(|error| conversion(27, error)))+ .transpose()?,})}@@ -104,7 +111,8 @@ pub fn insert(conn: &Connection, run: &ModeRun) -> Result<()> {let inserted = conn.prepare_cached(&format!("INSERT INTO mode_runs ({COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10,- ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24, ?25)"+ ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24, ?25,+ ?26, ?27, ?28)"))?.execute(params![run.id,@@ -132,6 +140,12 @@ pub fn insert(conn: &Connection, run: &ModeRun) -> Result<()> {run.created_at,run.updated_at,run.finished_at,+ run.elapsed_ms,+ run.active_since_ms,+ run.completion_report+ .as_ref()+ .map(serde_json::to_string)+ .transpose()?,]);match inserted {Ok(_) => Ok(()),@@ -148,12 +162,42 @@ pub fn insert(conn: &Connection, run: &ModeRun) -> Result<()> {/// Persist `run` if nobody changed it since it was read, then bump its/// revision. A lost race surfaces as `MODE_REVISION_CONFLICT`.pub fn save(conn: &Connection, run: &mut ModeRun) -> Result<()> {+ save_at(conn, run, now_ms())+}++/// Checkpoint the persisted clock, not caller-supplied timing fields. Keeping+/// the clock under the same revision CAS prevents stale or duplicate writers+/// from charging an interval twice. No periodic writes are needed.+pub(super) fn save_at(conn: &Connection, run: &mut ModeRun, now: i64) -> Result<()> {let previous = run.revision;let next = previous.checked_add(1).filter(|next| *next <= MAX_SAFE_INTEGER).ok_or_else(|| mode_error("MODE_REVISION_CONFLICT"))?;- let now = now_ms();+ let (state, elapsed_ms, active_since_ms) = conn+ .prepare_cached(+ "SELECT state, elapsed_ms, active_since_ms FROM mode_runs+ WHERE id = ?1 AND revision = ?2",+ )?+ .query_row(params![run.id, previous], |row| {+ Ok((+ parsed(0, row.get(0)?, RunState::parse)?,+ row.get::<_, i64>(1)?,+ row.get::<_, Option<i64>>(2)?,+ ))+ })+ .optional()?+ .ok_or_else(|| mode_error("MODE_REVISION_CONFLICT"))?;+ let now = now.clamp(0, MAX_SAFE_INTEGER);+ let running_since = active_since_ms.filter(|_| state == RunState::Running);+ let elapsed_ms = elapsed_ms+ .clamp(0, MAX_SAFE_INTEGER)+ .saturating_add(running_since.map_or(0, |since| now.saturating_sub(since).max(0)))+ .min(MAX_SAFE_INTEGER);+ // Retain a future checkpoint if the wall clock moved backwards, rather+ // than charging that already-covered interval again when it catches up.+ let active_since_ms = (run.state == RunState::Running)+ .then_some(running_since.map_or(now, |since| since.max(now)));let changed = conn.prepare_cached("UPDATE mode_runs SET stage_id = ?3, state = ?4, wait_reason = ?5, last_error = ?6,@@ -161,7 +205,8 @@ pub fn save(conn: &Connection, run: &mut ModeRun) -> Result<()> {advanced_in_turn = ?11, pending_gate = ?12, retry_counts = ?13,rounds_completed = ?14, tokens_used = ?15, settled_turns = ?16,updated_at = ?17, finished_at = ?18, input = ?19, max_turns = ?20,- max_tokens = ?21+ max_tokens = ?21, elapsed_ms = ?22, active_since_ms = ?23,+ completion_report_json = ?24WHERE id = ?1 AND revision = ?2",)?.execute(params![@@ -186,12 +231,20 @@ pub fn save(conn: &Connection, run: &mut ModeRun) -> Result<()> {run.input,run.max_turns,run.max_tokens,+ elapsed_ms,+ active_since_ms,+ run.completion_report+ .as_ref()+ .map(serde_json::to_string)+ .transpose()?,])?;if changed != 1 {return Err(mode_error("MODE_REVISION_CONFLICT"));}run.revision = next;run.updated_at = now;+ run.elapsed_ms = elapsed_ms;+ run.active_since_ms = active_since_ms;Ok(())}@@ -263,21 +316,30 @@ pub fn host_turn_active(conn: &Connection, session_id: &str) -> Result<bool> {.query_row(params![session_id], |row| row.get(0))?)}-/// Startup recovery: a claim cannot survive the process that dispatched its-/// turn. The run pauses and nothing is replayed.+/// Startup recovery: neither claims nor an uncheckpointed running interval+/// survive their process. Keep only durable elapsed time, discard the active+/// anchor and pause even between turns, excluding all offline time. A blocked+/// run keeps its durable user-only waiting state when its claim is released.pub fn release_stale_claims(conn: &Connection) -> Result<Vec<String>> {- let now = now_ms();+ release_stale_claims_at(conn, now_ms())+}++pub(super) fn release_stale_claims_at(conn: &Connection, now: i64) -> Result<Vec<String>> {let ids = conn.prepare(&format!(- "SELECT id FROM mode_runs WHERE active_turn_id IS NOT NULL AND state IN {OPEN_STATES}"+ "SELECT id FROM mode_runs WHERE state IN {OPEN_STATES}+ AND (active_turn_id IS NOT NULL OR state = 'running' OR active_since_ms IS NOT NULL)"))?.query_map([], |row| row.get::<_, String>(0))?.collect::<rusqlite::Result<Vec<_>>>()?;for id in &ids {conn.execute("UPDATE mode_runs SET active_turn_id = NULL, active_origin = NULL,- pending_gate = NULL, state = 'paused', wait_reason = NULL,- advanced_in_turn = 0, revision = revision + 1, updated_at = ?2+ pending_gate = NULL,+ state = CASE WHEN wait_reason = 'blocked' THEN 'waiting' ELSE 'paused' END,+ wait_reason = CASE WHEN wait_reason = 'blocked' THEN 'blocked' ELSE NULL END,+ advanced_in_turn = 0, active_since_ms = NULL,+ revision = revision + 1, updated_at = ?2WHERE id = ?1",params![id, now],)diff --git a/crates/host-core/src/mode_runs/tests.rs b/crates/host-core/src/mode_runs/tests.rsindex b4cbc475e..fb059790d 100644--- a/crates/host-core/src/mode_runs/tests.rs+++ b/crates/host-core/src/mode_runs/tests.rs@@ -159,6 +159,7 @@ pub(super) fn complete(summary: "done".into(),artifacts,input: None,+ report: None,},)}diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 95df2e74f..503bf2c7d 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -10,6 +10,7 @@ mod review_actions_rpc;mod scheduled_rpc;mod scheduled_settings;mod scheduled_tools;+mod session_display;mod todos;mod window_corner_rpc;mod window_owner;@@ -2942,8 +2943,7 @@ async fn handle_request(.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;let session = remote_tools::decorate_session(&st.db,- serde_json::to_value(session)- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,+ session_display::serialize(&st.db, session)?,)?;Ok(json!({ "session": session }))}diff --git a/crates/host-core/src/rpc/modes_rpc.rs b/crates/host-core/src/rpc/modes_rpc.rsindex 1254fc56e..4137d5175 100644--- a/crates/host-core/src/rpc/modes_rpc.rs+++ b/crates/host-core/src/rpc/modes_rpc.rs@@ -82,12 +82,25 @@ pub(super) async fn handle(let run = mode_runs::open_run(&st.db, &p.session_id).map_err(error)?;return Ok(json!({ "run": run_value(run.as_ref()) }));}- "modes.start" => {- let p: mode_runs::StartParams = parse(params)?;+ "modes.start" | "modes.startGoal" => {+ let p: mode_runs::StartParams = parse(params.clone())?;let workspace = local_workspace(st, &p.session_id)?;- let result = mode_runs::start(&st.db, &workspace, p).map_err(error)?;+ let result = if method == "modes.startGoal" {+ let value = params+ .get("modeSnapshot")+ .ok_or_else(|| error(crate::mode_runs::mode_error("MODE_SNAPSHOT_REQUIRED")))?;+ mode_runs::start_goal(&st.db, &workspace, p, value)+ } else {+ mode_runs::start(&st.db, &workspace, p)+ }+ .map_err(error)?;(result.wire(), result.changed.then_some(result.run))}+ "modes.resetGoalInput" => {+ let p: SessionParams = parse(params)?;+ mode_runs::reset_goal_input(&st.db, &p.session_id).map_err(error)?;+ return Ok(json!({ "ok": true }));+ }"modes.claimTurn" => {let result = mode_runs::claim_turn(&st.db, parse(params)?).map_err(error)?;(result.wire(), result.changed.then_some(result.run))diff --git a/crates/host-core/src/rpc/modes_rpc_tests.rs b/crates/host-core/src/rpc/modes_rpc_tests.rsindex 67f5f1c35..d8c9430a3 100644--- a/crates/host-core/src/rpc/modes_rpc_tests.rs+++ b/crates/host-core/src/rpc/modes_rpc_tests.rs@@ -418,3 +418,208 @@ async fn reopening_the_host_pauses_claimed_runs() {assert_eq!(wire["state"], "paused");assert!(wire.get("activeTurnId").is_none() && wire.get("activeOrigin").is_none());}++#[tokio::test]+async fn builtin_goal_continuations_inherit_the_session_permission() {+ for permission in ["auto", "ask", "accept-edits"] {+ let h = Harness::new("agent");+ let definition = goal_definition();+ h.call("session.configure", json!({+ "id": h.session_id, "mode": "goal", "modeSnapshot": definition, "permissionMode": permission+ })).await.unwrap();+ let first = h.start("first-goal-turn").await;+ let run_id = first["run"]["id"].as_str().unwrap();+ let evaluate = || {+ h.call("permissions.evaluate", json!({+ "sessionId": h.session_id, "toolName": "Bash", "args": { "command": "echo goal" }+ }))+ };+ let expected = if permission == "auto" {+ json!("allow-once")+ } else {+ Value::Null+ };+ assert_eq!(evaluate().await.unwrap()["decision"], expected);+ h.call("modes.resetGoalInput", json!({ "sessionId": h.session_id }))+ .await+ .unwrap();+ assert_eq!(+ h.call(+ "session.get",+ json!({ "id": h.session_id, "messageLimit": 1 })+ )+ .await+ .unwrap()["session"]["mode"],+ "agent"+ );+ let settled = h.call("modes.settleTurn", json!({+ "sessionId": h.session_id, "runId": run_id, "turnId": "first-goal-turn", "tokens": 0, "outcome": "completed"+ })).await.unwrap();+ assert_eq!(settled["continue"], true);+ let second = h+ .call(+ "modes.claimTurn",+ json!({+ "sessionId": h.session_id, "runId": run_id, "turnId": "second-goal-turn",+ "expectedRevision": settled["run"]["revision"], "origin": "host"+ }),+ )+ .await+ .unwrap();+ assert_eq!(second["claimed"], true);+ assert_eq!(+ evaluate().await.unwrap()["decision"],+ expected,+ "Goal + {permission}"+ );+ assert_eq!(+ h.call(+ "session.get",+ json!({"id": h.session_id, "messageLimit": 1})+ )+ .await+ .unwrap()["session"]["permissionMode"],+ permission+ );+ }+}++fn goal_definition() -> Value {+ json!({+ "version": 1, "id": "goal", "label": "Goal", "description": "", "permission": "agent",+ "prompt": "", "source": "builtin", "artifacts": [],+ "budget": { "maxTurns": 20, "maxTokens": null }, "returnTo": "agent",+ "stages": [{ "id": "work", "permission": "agent", "loop": true, "exit": [] }]+ })+}++#[tokio::test]+async fn goal_input_reset_and_replacement_keep_claims_accounting_and_plan_policy_separate() {+ let h = Harness::new("agent");+ h.configure("goal", Some(goal_definition())).await.unwrap();+ let first = h.start("old-turn").await;+ let old = first["run"]["id"].as_str().unwrap();+ h.call("modes.resetGoalInput", json!({ "sessionId": h.session_id }))+ .await+ .unwrap();+ h.configure("agent", None).await.unwrap();+ assert_eq!(+ h.call("modes.get", json!({"sessionId": h.session_id}))+ .await+ .unwrap()["run"]["state"],+ "running"+ );+ h.configure("plan", None).await.unwrap();+ let paused = h+ .call("modes.get", json!({"sessionId": h.session_id}))+ .await+ .unwrap();+ assert_eq!(paused["run"]["state"], "paused");+ {+ let st = h.state.lock().await;+ assert_eq!(+ crate::mode_runs::tool_policy(&st.db, &h.session_id).unwrap(),+ Some(crate::mode_runs::ToolPolicy::Contract)+ );+ }+ h.call("modes.control", json!({"sessionId": h.session_id, "runId": old, "expectedRevision": paused["run"]["revision"], "action": "stop"})).await.unwrap();+ let second = h.call("modes.startGoal", json!({"sessionId": h.session_id, "turnId": "new-turn", "input": "replacement", "modeSnapshot": goal_definition()})).await.unwrap();+ let new = second["run"]["id"].as_str().unwrap();+ assert_ne!(new, old);+ h.call("modes.resetGoalInput", json!({"sessionId": h.session_id}))+ .await+ .unwrap();+ assert_eq!(+ h.call(+ "session.get",+ json!({"id": h.session_id, "messageLimit": 1})+ )+ .await+ .unwrap()["session"]["mode"],+ "plan",+ "newer Plan selection wins"+ );+ let settlement = json!({"sessionId": h.session_id, "runId": old, "turnId": "old-turn", "tokens": 7, "outcome": "aborted"});+ let ended = h+ .call("modes.settleTurn", settlement.clone())+ .await+ .unwrap();+ assert_eq!(ended["run"]["state"], "stopped");+ assert_eq!(ended["run"]["tokensUsed"], 7);+ assert_eq!(ended["continue"], false);+ assert_eq!(+ h.call("modes.settleTurn", settlement).await.unwrap()["run"]["tokensUsed"],+ 7+ );+ let current = h+ .call("modes.get", json!({"sessionId": h.session_id}))+ .await+ .unwrap();+ assert_eq!(current["run"]["id"], new);+ assert_eq!(current["run"]["input"], "replacement");+ assert_eq!(current["run"]["tokensUsed"], 0);+ assert_eq!(current["run"]["roundsCompleted"], 0);+}++#[tokio::test]+async fn completion_report_rpc_rejects_invalid_content_without_state_or_notifications() {+ let mut h = Harness::new("agent");+ h.configure("checks", Some(checks())).await.unwrap();+ let started = h.start("report-invalid").await;+ h.mode_events();+ for report in [+ json!({}),+ Value::Null,+ json!({+ "status":"completed", "outcomes":[{"criterion":"works", "outcome":"met", "evidence":"ok", "unknown":true}], "remainingWork":[]+ }),+ ] {+ let error = h.call("modes.completeStage", json!({+ "sessionId":h.session_id, "runId":started["run"]["id"], "turnId":"report-invalid", "input":"go", "report":report+ })).await.unwrap_err();+ assert_eq!(error_code(&error), "MODE_INVALID_ARGUMENT");+ assert!(h.mode_events().is_empty());+ let current = h+ .call("modes.get", json!({"sessionId":h.session_id}))+ .await+ .unwrap();+ assert_eq!(current["run"], started["run"]);+ }+}++#[tokio::test]+async fn completion_report_rpc_completed_keeps_command_gate_and_blocked_settles_without_continue() {+ let mut h = Harness::new("agent");+ h.configure("checks", Some(checks())).await.unwrap();+ let started = h.start("report-turn").await;+ let run_id = started["run"]["id"].clone();+ let report = json!({"status":"completed", "outcomes":[{"criterion":"build", "outcome":"met", "evidence":"model claim"}], "remainingWork":[]});+ let completed = h.call("modes.completeStage", json!({+ "sessionId":h.session_id, "runId":run_id, "turnId":"report-turn", "input":"go", "report":report+ })).await.unwrap();+ assert_eq!(completed["status"], "run");+ assert_eq!(completed["command"], PASS);+ assert_eq!(completed["run"]["completionReport"], report);+ let report = json!({"status":"blocked", "outcomes":[{"criterion":"build", "outcome":"unmet", "evidence":"missing service"}], "remainingWork":[], "blockerReason":"missing service"});+ let blocked = h.call("modes.completeStage", json!({+ "sessionId":h.session_id, "runId":run_id, "turnId":"report-turn", "input":"go", "report":report+ })).await.unwrap();+ assert_eq!(blocked["status"], "blocked");+ assert_eq!(blocked["message"], "missing service");+ assert_eq!(blocked["run"]["waitReason"], "blocked");+ assert_eq!(blocked["run"]["completionReport"], report);+ let events = h.mode_events();+ assert_eq!(events.last().unwrap()["run"], blocked["run"]);+ let settled = h.call("modes.settleTurn", json!({+ "sessionId":h.session_id, "runId":run_id, "turnId":"report-turn", "tokens":42, "outcome":"completed"+ })).await.unwrap();+ assert_eq!(settled["continue"], false);+ assert_eq!(settled["run"]["tokensUsed"], 42);+ assert_eq!(settled["run"]["roundsCompleted"], 1);+ assert!(settled["run"].get("activeTurnId").is_none());+ let reopened = AppState::open(&h.data_dir).unwrap();+ let run = crate::mode_runs::open_run(&reopened.db, &h.session_id)+ .unwrap()+ .unwrap();+ assert_eq!(run.wire(), settled["run"]);+}diff --git a/crates/host-core/src/rpc/session_display.rs b/crates/host-core/src/rpc/session_display.rsnew file mode 100644index 000000000..26d684d4b--- /dev/null+++ b/crates/host-core/src/rpc/session_display.rs@@ -0,0 +1,103 @@+//! Display-only turn attribution from the authoritative message index.+use super::{rpc_err, JsonRpcError};+use crate::{db::Database, sessions::SessionDetail};+use rusqlite::{params, OptionalExtension};+use serde_json::Value;++pub fn serialize(db: &Database, detail: Option<SessionDetail>) -> Result<Value, JsonRpcError> {+ let Some(detail) = detail else {+ return Ok(Value::Null);+ };+ let session_id = detail.summary.id.clone();+ let mut value = serde_json::to_value(detail)+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;+ let mut query = db+ .conn()+ .prepare_cached(+ "SELECT m.turn_id FROM messages m JOIN turns t ON t.id=m.turn_id+ WHERE m.session_id=?1 AND m.id=?2 AND t.session_id=?1",+ )+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;+ let mut stamp = |message: &mut Value| -> Result<(), JsonRpcError> {+ let Some(id) = message.get("id").and_then(Value::as_str) else {+ return Ok(());+ };+ let turn_id: Option<String> = query+ .query_row(params![session_id, id], |row| row.get(0))+ .optional()+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;+ if let Some(turn_id) = turn_id {+ message["turnId"] = Value::String(turn_id);+ }+ Ok(())+ };+ if let Some(messages) = value.get_mut("messages").and_then(Value::as_array_mut) {+ for message in messages {+ stamp(message)?;+ }+ }+ if let Some(parent) = value.get_mut("navigationParent") {+ stamp(parent)?;+ }+ Ok(value)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::sessions::{self, UiMessage};+ use serde_json::json;++ #[test]+ fn turn_ids_survive_restart_and_bounded_history_without_user_rows() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("app.sqlite");+ let db = Database::open(&path).unwrap();+ let session = sessions::create_session(&db, None, None, None, None, None).unwrap();+ let message = |id: &str| {+ serde_json::from_value::<UiMessage>(json!({+ "id": id, "role": "assistant", "content": id,+ "createdAt": "2026-11-01T00:00:00Z", "status": "complete"+ }))+ .unwrap()+ };+ let first = sessions::begin_turn(&db, &session.id, None, None).unwrap();+ sessions::append_message(&db, &session.id, &message("first"), Some(&first)).unwrap();+ db.conn()+ .execute(+ "UPDATE turns SET status='completed' WHERE id=?1",+ params![first],+ )+ .unwrap();+ let second = sessions::begin_turn(&db, &session.id, None, None).unwrap();+ sessions::append_message(&db, &session.id, &message("second"), Some(&second)).unwrap();+ drop(db);+ let db = Database::open(&path).unwrap();+ let full = serialize(+ &db,+ sessions::get_session_with_options(&db, &session.id, Default::default()).unwrap(),+ )+ .unwrap();+ assert_eq!(full["messages"][0]["turnId"], first);+ assert_eq!(full["messages"][1]["turnId"], second);+ assert!(full["messages"]+ .as_array()+ .unwrap()+ .iter()+ .all(|row| row["role"] == "assistant"));+ let page = serialize(+ &db,+ sessions::get_session_with_options(+ &db,+ &session.id,+ sessions::SessionReadOptions {+ message_limit: Some(1),+ ..Default::default()+ },+ )+ .unwrap(),+ )+ .unwrap();+ assert_eq!(page["messages"][0]["turnId"], second);+ }+}diff --git a/crates/host-core/src/turn_queue.rs b/crates/host-core/src/turn_queue.rsindex 9ad2a8012..9b392fbf9 100644--- a/crates/host-core/src/turn_queue.rs+++ b/crates/host-core/src/turn_queue.rs@@ -34,6 +34,8 @@ pub struct QueuedTurnInput {pub idempotency_key: Option<String>,pub input_hash: String,pub content: String,+ #[serde(default)]+ pub start_goal: bool,pub session_message_id: Option<String>,pub user_message_id: Option<String>,pub voice_origin: Option<VoiceOrigin>,@@ -51,6 +53,7 @@ pub struct QueuedTurn {pub idempotency_key: Option<String>,pub input_hash: String,pub content: String,+ pub start_goal: bool,#[serde(skip_serializing_if = "Option::is_none")]pub session_message_id: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]@@ -90,6 +93,7 @@ fn row_to_entry(row: &rusqlite::Row<'_>) -> rusqlite::Result<QueuedTurn> {idempotency_key: row.get(3)?,input_hash: row.get(4)?,content: row.get(5)?,+ start_goal: row.get(14)?,session_message_id: row.get(10)?,attachments: attachments.and_then(|text| serde_json::from_str(&text).ok()),permission_mode: row.get(7)?,@@ -103,7 +107,7 @@ fn row_to_entry(row: &rusqlite::Row<'_>) -> rusqlite::Result<QueuedTurn> {const SELECT: &str = "SELECT id, session_id, principal, idempotency_key, input_hash, content,attachments_json, permission_mode, position, created_at, session_message_id, priority,- user_message_id, voice_origin_json+ user_message_id, voice_origin_json, start_goalFROM turn_queue";/// Delivery order: promoted entries first in click order (ascending@@ -149,7 +153,7 @@ pub fn push(db: &Database, input: QueuedTurnInput) -> Result<QueuedTurn> {).optional()?;if let Some(existing) = existing {- if existing.input_hash == input.input_hash {+ if existing.input_hash == input.input_hash && existing.start_goal == input.start_goal {return Ok(existing);}return Err(anyhow!("IDEMPOTENCY_CONFLICT"));@@ -183,8 +187,8 @@ pub fn push(db: &Database, input: QueuedTurnInput) -> Result<QueuedTurn> {"INSERT INTO turn_queue (id, session_id, principal, idempotency_key, input_hash, content,attachments_json, permission_mode, position, created_at, session_message_id,- user_message_id, voice_origin_json- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",+ user_message_id, voice_origin_json, start_goal+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",params![id,input.session_id,@@ -198,7 +202,8 @@ pub fn push(db: &Database, input: QueuedTurnInput) -> Result<QueuedTurn> {created_at,input.session_message_id,input.user_message_id,- voice_origin_json+ voice_origin_json,+ input.start_goal],)?;tx.commit()?;@@ -209,6 +214,7 @@ pub fn push(db: &Database, input: QueuedTurnInput) -> Result<QueuedTurn> {idempotency_key: input.idempotency_key,input_hash: input.input_hash,content: input.content,+ start_goal: input.start_goal,session_message_id: input.session_message_id,user_message_id: input.user_message_id,voice_origin: input.voice_origin,@@ -387,9 +393,30 @@ mod tests {voice_origin: None,attachments: None,permission_mode: "ask".into(),+ start_goal: false,}}+ #[test]+ fn explicit_goal_identity_survives_restart_and_idempotency() {+ let (dir, db, session) = open_with_session();+ let mut goal = input(&session, "new objective", Some("goal-key"));+ goal.start_goal = true;+ let accepted = push(&db, goal.clone()).unwrap();+ assert!(accepted.start_goal);+ assert_eq!(push(&db, goal.clone()).unwrap().id, accepted.id);+ goal.start_goal = false;+ assert!(push(&db, goal)+ .unwrap_err()+ .to_string()+ .contains("IDEMPOTENCY_CONFLICT"));+ drop(db);+ let db = Database::open_in_dir(dir.path()).unwrap();+ let restored = list(&db, Some(&session)).unwrap();+ assert_eq!(restored, vec![accepted]);+ assert!(restored[0].start_goal);+ }+#[test]fn push_keeps_order_positions_and_the_bound() {let (_dir, db, session_id) = open_with_session();diff --git a/docs/adr/mode-definitions.md b/docs/adr/mode-definitions.mdindex 85ed072dc..f51b95e09 100644--- a/docs/adr/mode-definitions.md+++ b/docs/adr/mode-definitions.md@@ -119,11 +119,26 @@ and `{{artifacts.<id>.path}}`. Substitution is text-only.author writes only the intent.- **Templates.** When a stage is first entered, the Host writes the templateof each missing artifact, with variables substituted.-- **Finishing a stage.** The model calls `CompleteStage { summary, artifacts? }`.+- **Finishing a stage.** The model calls `CompleteStage { summary, artifacts?, report? }`.`artifacts` maps an artifact id to Markdown, and the Host writes that contentto the artifact path. A contract stage can produce its artifact withoutWrite permission this way. The Host then evaluates the gates in order.A stage without gates and without `loop` also finishes when its turn ends.+- **Blocked reports.** Optional structured reports preserve per-criterion+ `met` / `unmet` / `unverified` evidence, remaining work and a blocker reason.+ A valid `blocked` report moves a live claimed run to `waiting/blocked`,+ without success gates or a successful finish. It stops autonomous continuation+ and survives restart. An unfinished detail alone is not a blocker when other+ authorized work remains. A `completed` report requires all submitted outcomes+ met and no remaining work, but never bypasses the configured exit gates.+ Reports are model assertions, not independent verification of their truth.+- **Completion-channel failure.** The sidecar proxy admits only+ `modes.completeStage` and `modes.gateResult`, not user control methods.+ Host ownership, live claim and frozen-input checks still apply. A broken+ completion RPC or invalid Host outcome fails the current execution turn,+ so settlement waits with an error rather than automatically continuing.+ Transport failures have no blind autonomous retry; a user may retry after+ recovery. Argument and artifact-content errors remain correctable.- **Gate failure.** The failure goes back to the model as the `CompleteStage`tool result, for example the missing heading or the command exit code withthe output tail. The model continues in the same turn. `onFail.retries`@@ -133,8 +148,9 @@ and `{{artifacts.<id>.path}}`. Substitution is text-only.- **Transition.** When all gates pass, the run moves to `next` and the Hoststarts that stage's first turn. When the final stage passes its gates, therun ends and the session switches to `returnTo`.-- **Turns.** A loop stage continues until `CompleteStage` passes or the budget- is exhausted. A non-loop stage whose turn ends without finishing waits for+- **Turns.** A loop stage continues until `CompleteStage` passes, a blocked+ report or execution error stops continuation, or the budget is exhausted.+ A non-loop stage whose turn ends without finishing waits forthe user. A user message during a run is input to the current stage andstarts no new run. Queued user messages run before any Host-started turn.- **Budget.** `maxTurns` and `maxTokens` limit only the turns the Host starts@@ -196,10 +212,11 @@ Completion handling is the final stage's `exit` gates. Compaction handling isthrough `CompleteStage` are limited to the declared paths.- `Computer` and scheduled-task tools are available only in the builtin`agent` mode.-- Turns that the user starts, or that follow a user approval in `ask: user`,- keep the session permission mode. Turns that the Host starts by itself- (loop continuation, `onFail.goto`) run at most `accept-edits`, even when the- session uses `auto`.+- Builtin Goal keeps the session's selected permission on every claimed turn,+ including Host continuation. This removes the second-turn Auto-to-Accept-edits+ downgrade; Ask and narrower per-turn ceilings still apply. Other unattended+ staged modes retain the `accept-edits` ceiling for `auto`. User and approval+ turns keep the session permission.- No action grants a permission, a session grant or an external path.### 7. Ownership@@ -236,6 +253,9 @@ One migration after the current schema:- `mode_runs`: generalized from #2141 `session_goals`. Each row stores the mode,snapshot hash, input, current stage, state, budget, usage, revision, activeclaim, retries and rounds completed.+ Schema 30 adds an active elapsed clock (`elapsed_ms`, `active_since_ms`):+ only Running time accumulates; all other states freeze it. Recovery retains+ checkpoints but discards uncheckpointed/offline time. Legacy rows start at zero.- `mode_gate_results`: run, stage, gate index, action, result, evidence andtimestamp.- Existing `plan_approvals` rows stay valid. The builtin `plan` reads them in@@ -262,6 +282,20 @@ One migration after the current schema:the Host rejects new Goal proposals with `PLAN_GOAL_ACTIVATION_DISABLED`.Old Goal approval rows stay readable, expire normally and never becomeautonomous authorization.+ Accepted Goal input returns the Composer preference to Agent without changing+ the run or its immutable snapshot/claim. Switching to Agent does not pause a+ builtin Goal; an explicit Plan selection still pauses it and keeps its hard+ deny. Goal continuations claim the run even while the input preference is Agent.+ A new explicit Goal is accepted into the existing durable queue before the+ old Goal is stopped. Old turn settlement precedes queue release, and the new+ turn starts a fresh run; ordinary input is not promoted into a new Goal by a+ later picker change. Queue restoration remains held until controller attachment.++The Goal input preference and execution identity are deliberately separate.+Relabeling the executing turn as Agent would lose the snapshot's authority;+keeping the picker on Goal would make ordinary follow-ups ambiguous. An additive+`startGoal` intent preserves user choice across admission and queue restoration+without granting continuation provenance or changing custom-mode semantics.- IPC / RACP `mode` stays a string. Old clients that send `plan`, `goal` or`agent` keep working. Builtin labels are localized; user labels are shown aswritten.diff --git a/docs/package.json b/docs/package.jsonindex 88815df3f..477e0627b 100644--- a/docs/package.json+++ b/docs/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/docs",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","scripts": {diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex a5d0502be..df1cf7a3a 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -891,9 +891,14 @@ an orphan snapshot. Legacy callers without a snapshot keep their existing behavithe UI must make that tradeoff visible.- `Computer` and scheduled-task tools are available only in the builtin Agentmode, never in a user-defined mode.-- A turn the Host starts by itself for a staged run (loop continuation,- `onFail.goto`) evaluates `auto` as `accept-edits`. Turns the user starts, and- the turn after an approval, keep the session permission mode.+- Builtin Goal retains the session permission on its first and subsequent+ claimed turns, including Host continuation; `auto` is not downgraded.+ Other Host-started staged turns (loop continuation, `onFail.goto`) continue+ to evaluate `auto` as `accept-edits`. User and approval turns retain the+ session permission. Narrower turn ceilings and external-path checks remain.+- After Goal input resets to Agent, its active Host-owned claim still selects+ the run snapshot and stage policy. Ordinary Agent work does not inherit an+ unclaimed Goal. An explicit Plan selection retains contract hard denies.- allow-session is remembered per toolName for the active session only- Session grants follow `sessionId` across project-tab switches and are neverinherited by another session or Temporary conversationdiff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex a3d5f4e9a..938dd5b25 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -2137,5 +2137,44 @@ Gate results record the stage, action, outcome and bounded evidence. At mostone open run exists per session. Restart clears in-flight claims and pausesthose runs without replaying work. Deleting a session cascades its run records.-Host-started turns evaluate Auto as Accept edits. A run's original snapshot-remains authoritative even when its source file changes.+Host-started custom modes evaluate Auto as Accept edits; builtin Goal retains+the selected session permission. A run's original snapshot remains authoritative+even when its source file changes or its input preference returns to Agent.++### Active elapsed time and queued Goal intent (schema 30)++The backed-up, transactional v29-to-v30 migration adds `mode_runs.elapsed_ms`+(nonnegative safe integer, default 0), `mode_runs.active_since_ms` (nullable epoch+milliseconds), and `turn_queue.start_goal` (boolean integer, default 0).+Fresh databases use the same column definitions. Existing rows and queue order+are preserved; old timestamps are never interpreted as active work.++Run saves checkpoint the persisted clock under the same revision CAS. Running+time accumulates; waiting, pause, budget exhaustion, completion and stop freeze+it. Repeated settlement cannot charge twice. Startup pauses Running rows even+between claims, clears active intervals, keeps only checkpointed elapsed time,+and does not count offline time or replay execution.++`start_goal` is explicit new-Goal input intent, not an execution permission.+It round-trips with the existing queue identity and participates in idempotency;+legacy queue rows remain ordinary input. Restored work is still held until a+controller attaches. Replacement preserves old run accounting independently.++### Structured completion reports (schema 31)++A backed-up transactional v30-to-v31 migration adds nullable+`mode_runs.completion_report_json`. Fresh databases and upgrades through earlier+mode migrations use the same structure; an already-present column is retained.+Existing elapsed time, Goal queue intent, accounting and immutable snapshots+are preserved. The migration backup precedes the column and version stamp.+The existing wait-reason CHECK is widened transactionally by a lossless table+replacement. All columns, indexes, triggers and child gate rows are retained;+foreign keys are checked and enforcement restored, including on rollback.++The optional wire `completionReport` retains the last bounded model-submitted+criterion outcomes, evidence, remaining work and blocker reason. It is not an+independent verification of their truth. Missing legacy reports remain absent.+The report is saved under the existing run revision CAS with its gate/state+transition. A blocked report stores `waiting/blocked`, not `finished`; settlement+releases the claim without autonomous continuation. Startup retains that wait+and report rather than replaying work. A completed report never bypasses gates.diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex d0bd41e8c..90b39de17 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -1630,8 +1630,10 @@ ADR `mode-definitions` adds the following Host methods. Parameters use camelCase| --- | --- | --- || `modes.get` | `sessionId` | `{ run }`, null when no open run exists || `modes.start` | `sessionId, input, turnId` | `{ claimed, run, enteredStage, definition }` |+| `modes.startGoal` | `sessionId, input, turnId, modeSnapshot` | claim result for an explicit builtin Goal, independent of the input mode; the Host validates the Goal snapshot and rejects a second open run |+| `modes.resetGoalInput` | `sessionId` | `{ ok: true }`; compare-and-reset only a Goal input preference to Agent, preserving the run, permission/model fields and any newer non-Goal mode || `modes.claimTurn` | `sessionId, runId, expectedRevision, turnId, origin` | claim result; origins: user, approval, host |-| `modes.completeStage` | `sessionId, runId, turnId, summary, artifacts?, input?` | failed, run, awaiting_approval, advanced, goto, blocked or finished outcome; `MODE_INPUT_CHANGED` when `input` (the input the turn was claimed with) differs from the run's current input |+| `modes.completeStage` | `sessionId, runId, turnId, summary, artifacts?, input?, report?` | failed, run, awaiting_approval, advanced, goto, blocked or finished outcome; `MODE_INPUT_CHANGED` when `input` (the input the turn was claimed with) differs from the run's current input || `modes.gateResult` | `sessionId, runId, turnId, gateIndex, toolCallId` | next stage outcome || `modes.settleTurn` | `sessionId, runId, turnId, tokens, outcome, error?` | `{ run, continue }` || `modes.control` | `sessionId, runId, expectedRevision, action` | `{ run, continue }`; pause, resume, stop or remove. Stop and remove both end the run; Electron main interrupts the active turn only for stop |@@ -1648,3 +1650,44 @@ uses the `pi-desktop/modes/*` IPC channels and never writes SQLite directly.pending Bash gate command. The Host records the exit code; a model-suppliedverdict cannot pass a command gate. Stage completion may write only declaredartifacts within the workspace. Staged runs reject remote workspaces.++Of the mode RPCs, only `modes.completeStage` and `modes.gateResult` traverse the+model-directed sidecar proxy. Start, settlement, controls and budget/input edits+remain host/user operations. Both completion methods retain Host ownership and+live-claim checks; a report never authorizes a paused or stopped claim.++Optional `report` is `{ status: "completed" | "blocked", outcomes:+[{ criterion, outcome: "met" | "unmet" | "unverified", evidence }],+remainingWork: string[], blockerReason?: string }`. Unknown report/outcome fields+are rejected. Outcomes number 1–64, with unique trimmed nonblank criteria (4 KiB+each) and nonblank evidence (16 KiB each). Remaining work has at most 64 nonblank+4 KiB items; a supplied blocker reason is nonblank and at most 16 KiB. Total+serialized report size is at most 256 KiB. All sizes count UTF-8 bytes.+`completed` requires all outcomes met, no remaining work and no blocker reason;+the existing exit gates must still pass. `blocked` requires a blocker reason and+unfinished/unverified work, persists `completionReport`, sets `waiting/blocked`+and returns a blocked outcome without evaluating success gates. Settlement does+not continue it. The report validates model evidence structure, not its truth.+Legacy calls without a report and saved definition snapshots remain valid.+A call with a report must include the claim's frozen `input`; a missing or+changed input is rejected with `MODE_INPUT_CHANGED` before artifact writes.++An unavailable completion RPC, broken transport or malformed Host outcome ends+the run turn with `MODE_COMPLETE_STAGE_FAILED`, not a normal completed turn.+There is no automatic transport retry; error settlement waits for user recovery.+Argument/artifact validation and ordinary failed exit checks remain correctable.++Run snapshots add `elapsedMs` (checkpointed active milliseconds) and optional+`activeSinceMs` (epoch milliseconds of the Running interval). Absent legacy+fields display zero, not `now - createdAt`. Other states and startup recovery+have no active interval.++Desktop prompt/queue requests accept optional boolean `startGoal`. Main validates+explicit input; the existing durable queue retains that choice through dispatch+and restoration. A replacement is accepted before stopping the old Goal; mode+settlement completes before queue release. This field never authorizes Host+continuation. Only the in-process trusted origin and Host claim can do so.++`session.get` adds display-only message `turnId` from the authoritative message+index, including bounded windows. Root turns remain separate without synthetic+user messages; this metadata is not an execution credential.diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.mdindex 6deeba0be..39c578833 100644--- a/docs/spec/04-ux/06-settings-ia.md+++ b/docs/spec/04-ux/06-settings-ia.md@@ -432,7 +432,8 @@ Card order is **Session defaults → Execution → Computer use**.Settings picker opens the same way. The closed trigger sizes to the currentlabel, capped by the settings control column.- The **Goal budget** row sits under the default mode in Session defaults: two- numeric fields (turns, tokens) persisted as optional+ horizontally aligned numeric fields (turns, tokens), each with a non-wrapping+ label and flexible input width, persisted as optional`AppSettings.goalBudget { maxTurns, maxTokens }`. A field saves on blur orEnter; empty is unlimited and an out-of-range value (turns 1–10000, tokensat least 1000) reverts to the saved one. Absent keeps the builtin Goaldiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 27d5479bd..665e85f98 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -3125,6 +3125,29 @@ reasoning-level control.The permission menu stays 120px wide; its Chinese Composer short label forAccept edits is `允许编辑` / `允許編輯` so the option remains single-linebeside its selection indicator.+- Accepted Goal input returns the mode chip to Agent, not the executing run.+ The run status bar remains visible and its controls target the Host run.+ A newer picker selection is not overwritten by a delayed send response;+ queued model/thinking/permission changes are retained.+- The mode-run status bar shows elapsed immediately after completed/max rounds.+ Show every nonzero day/hour/minute/second unit, or zero seconds; do not wrap+ days into a clock or pad unused units. Visible units are always `d`, `h`, `m`+ and `s`, with exactly one ASCII space between each number and its unit+ (for example, `1 d 2 h 3 m 4 s` or `0 s`), and a localized accessible elapsed+ label. Pause/wait/stop freeze the display; legacy rows start at zero.+ Metadata and actions may wrap as groups, never overlap or overflow.+- Resume, Pause, Edit and Remove use icon-only `TooltipButton` controls with+ Play, Pause, Pencil and Trash2 icons and localized tooltips/accessibility+ names. Existing availability, busy states and handlers remain unchanged;+ Stop, confirmations, approval and edit-form controls retain text labels.+- A model-reported `waiting/blocked` run uses the existing blocked badge and+ last-error text. It offers the same Resume icon instead of Pause; only that+ explicit user control resumes it. Success, infrastructure error and blocker+ reporting do not alter the elapsed format, layout or other state controls.+- Consecutive root `turnId` values create independent assistant conversation+ groups, including live streaming, background caches and restored history.+ Delegates stay under their Task; legacy messages without a turn id retain+ their existing grouping and autonomous turns add no synthetic user rows.- The right toolbar owns the remaining-capacity context inspector (when thenewest assistant turn has usage) immediately left of one combined model ×reasoning-level chip. Explicitly installed plugins may add user-invokeddiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 45ca80605..5de406860 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -20757,6 +20757,38 @@ recovery, CAS, budget and permission caps; desktop `mode-definitions-user-path`,run controls and Main dispatch. Runtime `modes/*` covers stage completion andcompaction injection.+### Goal input, replacement and elapsed repairs (offline)++- Run `scripts/e2e-goal-run-repairs.mjs` with `PI_DESKTOP_HOST_BIN` pointing at+ the candidate Host and `PI_SCRATCH_DIR` plus `PI_DESKTOP_AGENTS_DIR` pointing+ at isolated test state. Production Main prompt IPC, coordinator, finalization+ and persistent queue run against real host-core; only the model sidecar+ boundary is controlled. No provider request is made.+- Send a Goal and observe Agent input while its Goal claim remains running.+ Complete its first turn; automatic continuation retains the original run,+ snapshot and Auto permission. Send a second explicit Goal during that turn:+ acceptance is durable before the old Goal stops, old usage/rounds settle+ before queue release, and a distinct new run starts with the second input.+ Stop it, and verify no further continuation. Restored transcript assistant+ rows retain distinct turn ids and contain only the two actual user inputs.+- `scripts/e2e-goal-layout.mjs` renders production status/budget controls with+ the built stylesheet in isolated Electron. Check English/Chinese layouts at+ 320, 480, 720 and 1120 pixels, long objectives/day durations, metadata order,+ nonoverlap and horizontal budget inputs. Duration uses `d`, `h`, `m`, `s`+ with exactly one ASCII space after each number, including `0 s`, in both+ languages. Resume/Pause/Edit/Remove are icon-only with localized accessible+ names; native clicks still resume/pause, open/cancel editing and arm/cancel+ removal. Stop retains its text and confirmation. Timer lifecycle is unchanged.+ It never attaches to the user's app.+- Rust elapsed tests cover all frozen states, deterministic clock rollback,+ pause/resume, duplicate settlement, offline recovery and populated v29 upgrade.+ RPC permission tests cover Auto, Ask and Accept edits after input reset, plus+ Plan hard denies and separate accounting for a replaced run. Queue tests cover+ restart and idempotency. Renderer user-path tests cover accepted/rejected Goal,+ pending model settings, newer picker choices, live/background turn attribution,+ legacy grouping and fixed Latin duration symbols with localized elapsed labels. Paid live-model checks below+ remain opt-in and are not a prerequisite for this offline repair suite.+### Goal run controls with a live model (opt-in, paid)Command: `PI_LIVE_BASE_URL=<url> PI_LIVE_MODEL=<model> PI_LIVE_API_KEY=<key>@@ -20842,3 +20874,31 @@ does not qualify native Electron interaction or live-provider execution.#### E2E-ISSUE-1926-scratch-prefixBuild two actual runtimes with identical configuration and different scratch directories. Their leading runtime system sections match; each trailing context retains its own path. Check PowerShell/POSIX guidance and custom system prompt behavior. Coverage: runtime.test.ts. No paid provider requests or cache-hit claims.++### E2E-GOAL-completion-channel: Completion and blockers stop autonomous rounds++- **Environment**: Isolated Host data and `PI_DESKTOP_AGENTS_DIR`, production+ sidecar/proxy, production Main claim/settlement services, deterministic+ loopback-only model endpoint; no real provider or user Desktop instance.+- **Command**: After JS/runtime and Host builds, run+ `node scripts/e2e-goal-completion.mjs` with `PI_SCRATCH_DIR` and+ `PI_DESKTOP_HOST_BIN`. `PI_DESKTOP_SIDECAR_ENTRY` can select the sidecar+ extracted from the installer for payload validation.+- **Steps**: Submit a completed report with the Goal artifact, a legacy+ summary/artifact call, a blocked report with unfinished evidence, and a+ completion-channel failure. Also complete a stage with a real Bash exit gate.+ Repeat settlement and restart the isolated Host for each scenario.+- **Expected**: Success reaches `finished`; blocked remains non-success+ `waiting/blocked` with durable outcomes/reason; infrastructure failure emits+ `MODE_COMPLETE_STAGE_FAILED` and settles `waiting/error`. Each scenario uses+ exactly one model request, returns `continue: false`, releases its claim,+ and schedules no next autonomous round. Gate results traverse the production+ proxy and use Host-recorded execution, not a model verdict. Restart preserves+ terminal/waiting state; duplicate settlement cannot recharge accounting.+- **Companion negatives**: Runtime/Host tests cover invalid/oversized reports,+ original exit gates, stale/cross-session claims, paused/stopped runs and input+ edits. The stdio proxy tests retain denies for start/control/update/resolve/+ settlement and configuration methods. Saved snapshots gain reporting guidance+ without changing frozen objectives or gates.+- **Scope**: Host validates authorization, report structure and state; it does+ not independently prove model-reported acceptance evidence true.diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.mdindex 7abb217ce..379110dd1 100644--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md@@ -1196,8 +1196,10 @@ ADR `mode-definitions` adds the following Host methods. Parameters use camelCase| --- | --- | --- || `modes.get` | `sessionId` | `{ run }`, null when no open run exists || `modes.start` | `sessionId, input, turnId` | `{ claimed, run, enteredStage, definition }` |+| `modes.startGoal` | `sessionId, input, turnId, modeSnapshot` | claim result for an explicit builtin Goal, independent of the input mode; the Host validates the Goal snapshot and rejects a second open run |+| `modes.resetGoalInput` | `sessionId` | `{ ok: true }`; compare-and-reset only a Goal input preference to Agent, preserving the run, permission/model fields and any newer non-Goal mode || `modes.claimTurn` | `sessionId, runId, expectedRevision, turnId, origin` | claim result; origins: user, approval, host |-| `modes.completeStage` | `sessionId, runId, turnId, summary, artifacts?, input?` | failed, run, awaiting_approval, advanced, goto, blocked or finished outcome; `MODE_INPUT_CHANGED` when `input` (the input the turn was claimed with) differs from the run's current input |+| `modes.completeStage` | `sessionId, runId, turnId, summary, artifacts?, input?, report?` | failed, run, awaiting_approval, advanced, goto, blocked or finished outcome; `MODE_INPUT_CHANGED` when `input` (the input the turn was claimed with) differs from the run's current input || `modes.gateResult` | `sessionId, runId, turnId, gateIndex, toolCallId` | next stage outcome || `modes.settleTurn` | `sessionId, runId, turnId, tokens, outcome, error?` | `{ run, continue }` || `modes.control` | `sessionId, runId, expectedRevision, action` | `{ run, continue }`; pause, resume, stop or remove. Stop and remove both end the run; Electron main interrupts the active turn only for stop |@@ -1214,3 +1216,44 @@ uses the `pi-desktop/modes/*` IPC channels and never writes SQLite directly.pending Bash gate command. The Host records the exit code; a model-suppliedverdict cannot pass a command gate. Stage completion may write only declaredartifacts within the workspace. Staged runs reject remote workspaces.++Of the mode RPCs, only `modes.completeStage` and `modes.gateResult` traverse the+model-directed sidecar proxy. Start, settlement, controls and budget/input edits+remain host/user operations. Both completion methods retain Host ownership and+live-claim checks; a report never authorizes a paused or stopped claim.++Optional `report` is `{ status: "completed" | "blocked", outcomes:+[{ criterion, outcome: "met" | "unmet" | "unverified", evidence }],+remainingWork: string[], blockerReason?: string }`. Unknown report/outcome fields+are rejected. Outcomes number 1–64, with unique trimmed nonblank criteria (4 KiB+each) and nonblank evidence (16 KiB each). Remaining work has at most 64 nonblank+4 KiB items; a supplied blocker reason is nonblank and at most 16 KiB. Total+serialized report size is at most 256 KiB. All sizes count UTF-8 bytes.+`completed` requires all outcomes met, no remaining work and no blocker reason;+the existing exit gates must still pass. `blocked` requires a blocker reason and+unfinished/unverified work, persists `completionReport`, sets `waiting/blocked`+and returns a blocked outcome without evaluating success gates. Settlement does+not continue it. The report validates model evidence structure, not its truth.+Legacy calls without a report and saved definition snapshots remain valid.+A call with a report must include the claim's frozen `input`; a missing or+changed input is rejected with `MODE_INPUT_CHANGED` before artifact writes.++An unavailable completion RPC, broken transport or malformed Host outcome ends+the run turn with `MODE_COMPLETE_STAGE_FAILED`, not a normal completed turn.+There is no automatic transport retry; error settlement waits for user recovery.+Argument/artifact validation and ordinary failed exit checks remain correctable.++Run snapshots add `elapsedMs` (checkpointed active milliseconds) and optional+`activeSinceMs` (epoch milliseconds of the Running interval). Absent legacy+fields display zero, not `now - createdAt`. Other states and startup recovery+have no active interval.++Desktop prompt/queue requests accept optional boolean `startGoal`. Main validates+explicit input; the existing durable queue retains that choice through dispatch+and restoration. A replacement is accepted before stopping the old Goal; mode+settlement completes before queue release. This field never authorizes Host+continuation. Only the in-process trusted origin and Host claim can do so.++`session.get` adds display-only message `turnId` from the authoritative message+index, including bounded windows. Root turns remain separate without synthetic+user messages; this metadata is not an execution credential.diff --git a/package.json b/package.jsonindex 94022e642..e84f7bfc2 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "pi-desktop","private": true,- "version": "0.21.0",+ "version": "0.21.2","description": "Local-first AI coding agent desktop client","packageManager": "[email protected]+sha512.f64ba907507f5ceafe06c8d38e6052d0179444580ec1279ddd5bfc11cb48aa8a2644b66598e07e761da84872a9fc57d5f902b87fa49d024198d558612aabbe45","engines": {diff --git a/packages/agent-host/package.json b/packages/agent-host/package.jsonindex d33e95871..f2379d48c 100644--- a/packages/agent-host/package.json+++ b/packages/agent-host/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/agent-host",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","main": "./dist/index.js",diff --git a/packages/agent-host/src/agent-host.ts b/packages/agent-host/src/agent-host.tsindex 8d61a7ff7..8c9f37604 100644--- a/packages/agent-host/src/agent-host.ts+++ b/packages/agent-host/src/agent-host.ts@@ -102,6 +102,7 @@ export type StartTurnParams = {admission?: RacpTurnAdmission;input: {text: string;+ startGoal?: boolean;attachments?: AgentPromptAttachment[];sessionMessageId?: string;/** Client-chosen id for the durable user row (D288). */@@ -470,9 +471,10 @@ export class AgentHost {}/** Append to the shared Host queue even when no turn is currently running. */- async enqueueTurn(principal: Principal, params: StartTurnParams): Promise<StartTurnResult> {+ async enqueueTurn(principal: Principal, params: StartTurnParams, onAccepted?: () => Promise<void>): Promise<StartTurnResult> {this.requireRole(principal, "turn/start");- const result = await this.withAdmission(params.sessionId, () => this.startTurnAdmitted(principal, params, true));+ const result = await this.withAdmission(params.sessionId, () =>+ this.startTurnAdmitted(principal, params, true, onAccepted));await this.drain(params.sessionId);return {...result,@@ -485,6 +487,7 @@ export class AgentHost {principal: Principal,params: StartTurnParams,forceQueue = false,+ onQueued?: () => Promise<void>,): Promise<StartTurnResult> {const summary = await this.requireSession(params.sessionId);if (@@ -536,6 +539,7 @@ export class AgentHost {sessionId: state.id,principalSubject: principal.subject,content: params.input.text,+ startGoal: params.input.startGoal === true,...(params.input.sessionMessageId ? { sessionMessageId: params.input.sessionMessageId } : {}),...(params.input.userMessageId ? { userMessageId: params.input.userMessageId } : {}),...(params.input.voiceOrigin ? { voiceOrigin: params.input.voiceOrigin } : {}),@@ -555,11 +559,14 @@ export class AgentHost {turn.principalSubject = principal.subject;this.emit(state, "turn.queued", { turn: this.toRacpTurn(state, turn) }, { turnId: turn.id });this.notifyQueue(state.id);+ // Only a newly durable entry triggers acceptance side effects, never a retry.+ await onQueued?.();} else {const started = await this.runtime.prompt({...(modeOrigin ? { [TRUSTED_MODE_ORIGIN]: modeOrigin } : {}),sessionId: state.id,content: params.input.text,+ ...(params.input.startGoal === undefined ? {} : { startGoal: params.input.startGoal }),...(params.input.sessionMessageId ? { sessionMessageId: params.input.sessionMessageId } : {}),...(params.input.userMessageId ? { userMessageId: params.input.userMessageId } : {}),...(params.input.voiceOrigin ? { voiceOrigin: params.input.voiceOrigin } : {}),@@ -996,6 +1003,7 @@ export class AgentHost {const started = await this.runtime.prompt({sessionId,content: record.content,+ startGoal: record.startGoal === true,...(record.sessionMessageId ? { sessionMessageId: record.sessionMessageId } : {}),...(record.userMessageId ? { userMessageId: record.userMessageId } : {}),...(record.voiceOrigin ? { voiceOrigin: record.voiceOrigin } : {}),@@ -1068,7 +1076,7 @@ export class AgentHost {for (let attempt = 0; attempt < PROMOTED_DELIVERY_ATTEMPTS; attempt += 1) {const head = await this.withAdmission(state.id, async () => {const record = this.queue.peek(state.id);- if (!record || record.priority === undefined) return undefined;+ if (!record || record.priority === undefined || record.startGoal) return undefined;if (this.activeRuntimeTurnId(state) !== runtimeTurnId) return undefined;const active = state.turns.get(state.activeTurnId!);const externalDesktopTurn = active?.principalSubject === undefined && active?.runtimeTurnId === undefined;@@ -1541,6 +1549,7 @@ export function hashInput(input: StartTurnParams["input"]): string {const encoded = JSON.stringify({text: input.text,attachments: input.attachments ?? [],+ ...(input.startGoal ? { startGoal: true } : {}),...(input.sessionMessageId ? { sessionMessageId: input.sessionMessageId } : {}),});let hash = 5381;diff --git a/packages/agent-host/src/ports.ts b/packages/agent-host/src/ports.tsindex d4803e451..7971f659c 100644--- a/packages/agent-host/src/ports.ts+++ b/packages/agent-host/src/ports.ts@@ -44,6 +44,7 @@ export type TurnStartRequest = {[TRUSTED_MODE_ORIGIN]?: TrustedModeOrigin;sessionId: string;content: string;+ startGoal?: boolean;sessionMessageId?: string;/** Client-chosen id for the durable user row (D288); the runtime mints one otherwise. */userMessageId?: string;@@ -90,6 +91,7 @@ export type QueuedTurnRecord = {sessionId: string;principalSubject: string;content: string;+ startGoal?: boolean;sessionMessageId?: string;/** Client-chosen id for the durable user row (D288). */userMessageId?: string;diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.jsonindex d7c375358..d46c4125a 100644--- a/packages/agent-runtime/package.json+++ b/packages/agent-runtime/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/agent-runtime",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","main": "./dist/index.js",diff --git a/packages/agent-runtime/src/mode-completion-flow.test.ts b/packages/agent-runtime/src/mode-completion-flow.test.tsnew file mode 100644index 000000000..cb766cc18--- /dev/null+++ b/packages/agent-runtime/src/mode-completion-flow.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it, vi } from "vitest";+import { createAssistantMessageEventStream, type AssistantMessage } from "@earendil-works/pi-ai";+import type { AgentEventEnvelope, ModeCompletionReport, ModeTurnContext } from "@pi-desktop/shared";+import { DesktopAgentRuntime, type RuntimeProviderConfig } from "./runtime.js";+import { builtinModeDefinition } from "./mode-definitions.js";++const provider: RuntimeProviderConfig = {+ id: "local", name: "Local", baseUrl: "http://127.0.0.1:1/v1", modelId: "fixture", apiKey: "", authKind: "none",+ supportsReasoning: false, supportedThinkingLevels: ["off"],+ modelConfig: { source: "generic", name: "Local", baseUrl: "http://127.0.0.1:1/v1", reasoning: false,+ input: ["text"], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 128_000, maxTokens: 8192 },+};+const modeTurn: ModeTurnContext = {+ runId: "run-1", stageId: "work", origin: "host", enteredStage: false,+ input: "Build the authorized artifact", artifactPaths: { goal: ".pi/goals/run-1.md" },+};+const blocked: ModeCompletionReport = {+ status: "blocked", outcomes: [{ criterion: "Build", outcome: "unverified", evidence: "Approval is missing" }],+ remainingWork: ["Build after approval"], blockerReason: "The user must approve the build",+};++/** Only the external model stream and Host RPC are scripted; Agent and tool wiring are real. */+function fixture(answer: unknown, report?: ModeCompletionReport) {+ const events: AgentEventEnvelope[] = [];+ const call = vi.fn(async (method: string) => {+ if (method === "modes.completeStage") {+ if (answer instanceof Error) throw answer;+ return answer;+ }+ return {};+ });+ const runtime = new DesktopAgentRuntime({+ host: { call: async <T = unknown>(method: string): Promise<T> => await call(method) as T, onNotification: () => () => {} }, sessionId: "session-1", provider,+ mode: "goal", modeDefinition: builtinModeDefinition("goal"), thinkingLevel: "off",+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ onEvent: (event) => events.push(event),+ });+ let requests = 0;+ (runtime as unknown as { models: unknown }).models = {+ streamSimple: () => {+ requests += 1;+ const stop = requests >= 3;+ const message: AssistantMessage = {+ role: "assistant", api: "openai-completions", provider: "local", model: "fixture",+ usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },+ stopReason: stop ? "stop" : "toolUse", timestamp: 2,+ content: stop ? [{ type: "text", text: "Unexpected retry" }] : [{ type: "toolCall", id: `call-${requests}`,+ name: "CompleteStage", arguments: { summary: "Build status", ...(report ? { report } : {}) } }],+ };+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ stream.push({ type: "start", partial: message });+ stream.push({ type: "done", reason: stop ? "stop" : "toolUse", message });+ stream.end(message);+ });+ return stream;+ },+ };+ return { runtime, events, call, requests: () => requests };+}++describe("mode completion through the public Agent prompt", () => {+ it.each<[string, ModeCompletionReport | undefined]>([+ ["finished", undefined],+ ["blocked", blocked],+ ])("ends a %s report without another model request", async (status, report) => {+ const test = fixture({ status, message: "Waiting for approval", run: { id: "run-1" } }, report);+ try {+ await test.runtime.prompt({ text: "continue", modeTurn }, undefined, "turn-1");+ expect(test.requests()).toBe(1);+ expect(test.call.mock.calls.filter(([method]) => method === "modes.completeStage")).toHaveLength(1);+ expect(test.events.some(({ event }) => event.type === "error")).toBe(false);+ expect(test.runtime.getStatus().isRunning).toBe(false);+ } finally { await test.runtime.dispose(); }+ });++ it.each([+ Object.assign(new Error("host method not allowed from sidecar: modes.completeStage"), { code: -32601 }),+ new Error("completion transport closed"),+ { status: "unknown", run: {} },+ ])("emits a real turn error for completion infrastructure failure %o", async (failure) => {+ const test = fixture(failure);+ try {+ await test.runtime.prompt({ text: "continue", modeTurn }, undefined, "turn-1");+ expect(test.requests()).toBe(1);+ const errors = test.events.filter(({ event }) => event.type === "error");+ expect(errors).toHaveLength(1);+ expect(errors[0]?.event).toMatchObject({ type: "error", error: { code: "MODE_COMPLETE_STAGE_FAILED" } });+ const errorIndex = test.events.findIndex(({ event }) => event.type === "error");+ const endIndex = test.events.findIndex(({ event }) => event.type === "agent_end");+ expect(errorIndex).toBeLessThan(endIndex);+ expect(test.runtime.getStatus().isRunning).toBe(false);+ } finally { await test.runtime.dispose(); }+ });+});diff --git a/packages/agent-runtime/src/mode-prompts.ts b/packages/agent-runtime/src/mode-prompts.tsindex f34def42f..7cc830e35 100644--- a/packages/agent-runtime/src/mode-prompts.ts+++ b/packages/agent-runtime/src/mode-prompts.ts@@ -34,8 +34,8 @@ export const GOAL_WORK_STAGE_PROMPT = ["- `# Acceptance criteria`: objectively checkable criteria that together prove the objective is met, such as a command that must pass or a behavior you can observe.","- `# Evidence`: for each criterion, the concrete evidence you observed in the current workspace: the commands you ran and their results, the files and behaviors you checked.","Write the artifact by passing its complete Markdown as `artifacts.goal` when you call CompleteStage; the host saves it at that path. You may save drafts there with Write while you work, so the objective and criteria survive a context compaction.",- "Call CompleteStage only when every acceptance criterion is verified with fresh evidence. Intent, plans, earlier results, and a finished checklist are not evidence. Never call CompleteStage to report progress.",- "A turn may end normally with a short progress note; the host starts the next turn while the run is open and its budget allows. If a criterion cannot be met or a boundary blocks you, say which one and why instead of completing the stage.",+ "For successful completion, call CompleteStage only when every acceptance criterion is verified with fresh evidence. Intent, plans, earlier results, and a finished checklist are not evidence. Never call CompleteStage to report ordinary progress.",+ "A turn may end normally with a short progress note; the host starts the next turn while the run is open and its budget allows. If no further authorized work can proceed, call CompleteStage with report.status blocked, criterion outcomes and evidence, remainingWork, and blockerReason. This is a non-success blocker report, not completion; it stops continuation until the user intervenes. An unfinished criterion alone is not a blocker if other authorized work remains.",].join("\n");export const AGENT_MODE_SYSTEM_PROMPT = [diff --git a/packages/agent-runtime/src/modes/complete-stage-tool.test.ts b/packages/agent-runtime/src/modes/complete-stage-tool.test.tsindex a2b193491..669a3d386 100644--- a/packages/agent-runtime/src/modes/complete-stage-tool.test.ts+++ b/packages/agent-runtime/src/modes/complete-stage-tool.test.ts@@ -22,6 +22,7 @@ type Harness = {host: { call: ReturnType<typeof vi.fn> };gates: ModeGateCommand[];endTurn: ReturnType<typeof vi.fn>;+ failTurn: ReturnType<typeof vi.fn>;tool: ReturnType<typeof createCompleteStageTool>;};@@ -41,6 +42,7 @@ function harness(};const gates: ModeGateCommand[] = [];const endTurn = vi.fn();+ const failTurn = vi.fn();const tool = createCompleteStageTool({host: host as never,sessionId: "session-1",@@ -50,8 +52,9 @@ function harness(return options.gate ? options.gate(request) : { isError: false, text: "ok" };},endTurn,+ failTurn,});- return { host, gates, endTurn, tool };+ return { host, gates, endTurn, failTurn, tool };}function text(result: { content: Array<{ type: string; text?: string }> }): string {@@ -189,4 +192,85 @@ describe("CompleteStage", () => {expect(parseCompleteStageParams({ summary: "ok", artifacts: { Goal: "x" } })).toContain("invalid");expect(parseCompleteStageParams({ summary: "ok", artifacts: { goal: 3 } })).toContain("Markdown string");});++ it("fails the run turn on an unavailable completion RPC instead of silently allowing another round", async () => {+ const denied = Object.assign(new Error("host method not allowed from sidecar: modes.completeStage"), { code: -32601 });+ const { tool, endTurn, failTurn } = harness({ "modes.completeStage": [denied] });+ const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; terminate?: boolean };+ expect(result.isError).toBe(true);+ expect(result.terminate).toBe(true);+ expect(failTurn).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining("not allowed from sidecar") }));+ expect(endTurn).not.toHaveBeenCalled();+ });++ it("keeps a report-content rejection correctable without failing the run turn", async () => {+ const invalid = Object.assign(new Error("report evidence is missing"), { errorCode: "MODE_INVALID_ARGUMENT" });+ const { tool, endTurn, failTurn } = harness({ "modes.completeStage": [invalid] });+ const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean; terminate?: boolean };+ expect(result.isError).toBe(true);+ expect(result.terminate).toBeUndefined();+ expect(failTurn).not.toHaveBeenCalled();+ expect(endTurn).not.toHaveBeenCalled();+ });++ it("does not fail a newer turn when a stale completion reply arrives", async () => {+ const options = { claimed: true };+ const { host, tool, failTurn, endTurn } = harness({}, options);+ host.call.mockImplementation(async () => {+ options.claimed = false;+ throw new Error("transport closed after the claim changed");+ });+ await tool.execute("call-1", { summary: "Done" });+ expect(failTurn).not.toHaveBeenCalled();+ expect(endTurn).not.toHaveBeenCalled();+ });++ it.each([+ { status: "finished", run: RUN },+ { status: "run", gateIndex: 0, command: "npm test", timeoutMinutes: 1, run: RUN },+ { status: "failed", gateIndex: 0, message: "Not ready", retriesLeft: 1, run: RUN },+ ])("ignores a stale %s outcome without running gates or ending a newer turn", async (outcome) => {+ const options = { claimed: true };+ const { host, tool, gates, failTurn, endTurn } = harness({}, options);+ host.call.mockImplementation(async () => {+ options.claimed = false;+ return outcome;+ });+ const result = await tool.execute("call-1", { summary: "Done" }) as { isError?: boolean };+ expect(result.isError).toBe(true);+ expect(gates).toEqual([]);+ expect(failTurn).not.toHaveBeenCalled();+ expect(endTurn).not.toHaveBeenCalled();+ });++ it("submits an explicit blocked report with unfinished criteria and ends without running gates", async () => {+ const report = {+ status: "blocked", outcomes: [{ criterion: "Build", outcome: "unverified", evidence: "Required approval is missing" }],+ remainingWork: ["Run the approved build"], blockerReason: "User approval is required",+ };+ expect(parseCompleteStageParams({ summary: "Cannot proceed", report })).toEqual({ summary: "Cannot proceed", report });+ const { host, tool, endTurn, failTurn, gates } = harness({+ "modes.completeStage": [{ status: "blocked", message: report.blockerReason, run: RUN }],+ });+ const result = await tool.execute("call-1", { summary: "Cannot proceed", report }) as { terminate?: boolean };+ expect(host.call).toHaveBeenCalledWith("modes.completeStage", expect.objectContaining({ report }));+ expect(result.terminate).toBe(true);+ expect(endTurn).toHaveBeenCalledTimes(1);+ expect(failTurn).not.toHaveBeenCalled();+ expect(gates).toEqual([]);+ });++ it("accepts a verified completion report but rejects contradictory or unbounded reports locally", () => {+ const report = {+ status: "completed", outcomes: [{ criterion: "Build", outcome: "met", evidence: "Build exited 0" }], remainingWork: [],+ };+ expect(parseCompleteStageParams({ summary: "Verified", report })).toEqual({ summary: "Verified", report });+ for (const invalid of [+ { ...report, outcomes: [{ ...report.outcomes[0], outcome: "unmet" }] },+ { ...report, remainingWork: ["Build is still pending"] },+ { ...report, outcomes: [report.outcomes[0], report.outcomes[0]] },+ { ...report, status: "blocked" },+ { ...report, outcomes: [{ ...report.outcomes[0], evidence: "x".repeat(100_001) }] },+ ]) expect(typeof parseCompleteStageParams({ summary: "Invalid", report: invalid })).toBe("string");+ });});diff --git a/packages/agent-runtime/src/modes/complete-stage-tool.ts b/packages/agent-runtime/src/modes/complete-stage-tool.tsindex a68cd6a0b..ec6578698 100644--- a/packages/agent-runtime/src/modes/complete-stage-tool.ts+++ b/packages/agent-runtime/src/modes/complete-stage-tool.ts@@ -13,10 +13,12 @@ import { Type } from "typebox";import {MODE_ID_RE,MODE_LIMITS,+ type ModeCompletionReport,type ModeStageOutcome,type ModeTurnContext,} from "@pi-desktop/shared";import type { RuntimeHost } from "../host-client.js";+import { completionReportSchema, parseCompletionReport } from "./completion-report.js";export const COMPLETE_STAGE_TOOL_NAME = "CompleteStage";@@ -33,6 +35,11 @@ const TERMINAL_HOST_ERRORS = new Set(["MODE_INPUT_CHANGED",]);+/** The model can correct these without retrying a broken completion channel. */+const CORRECTABLE_HOST_ERRORS = new Set([+ "MODE_INVALID_ARGUMENT", "MODE_ARTIFACT_TOO_LARGE", "MODE_ARTIFACT_UNKNOWN", "MODE_ARTIFACT_PATH",+]);+const STATUSES = new Set<ModeStageOutcome["status"]>(["failed","run",@@ -67,9 +74,11 @@ export type CompleteStageToolDeps = {) => Promise<ModeGateRunResult>;/** Ask the agent loop to end the turn at the next boundary. */endTurn: () => void;+ /** Fail this run turn: Host settlement must not treat it as normal completion. */+ failTurn: (error: { code: string; message: string; retriable: boolean }) => void;};-type CompleteStageParams = { summary: string; artifacts?: Record<string, string> };+type CompleteStageParams = { summary: string; artifacts?: Record<string, string>; report?: ModeCompletionReport };type ToolResult = AgentToolResult<unknown> & { isError?: boolean; terminate?: boolean };@@ -83,27 +92,34 @@ function textResult(text: string, details: unknown, extra: { isError?: boolean;/** Why the model's arguments are unusable, or the parsed arguments. */export function parseCompleteStageParams(value: unknown): CompleteStageParams | string {- if (!isRecord(value)) return "expected { summary, artifacts? }";- const unknownKey = Object.keys(value).find((key) => key !== "summary" && key !== "artifacts");+ if (!isRecord(value)) return "expected { summary, artifacts?, report? }";+ const unknownKey = Object.keys(value).find((key) => key !== "summary" && key !== "artifacts" && key !== "report");if (unknownKey) return `unknown argument "${unknownKey}"`;if (typeof value.summary !== "string" || !value.summary.trim()) return "summary must be a non-empty string";if (Buffer.byteLength(value.summary) > COMPLETE_STAGE_SUMMARY_MAX_BYTES) {return `summary is larger than ${COMPLETE_STAGE_SUMMARY_MAX_BYTES / 1024} KiB`;}- if (value.artifacts === undefined) return { summary: value.summary.trim() };- if (!isRecord(value.artifacts)) return "artifacts must map artifact ids to Markdown strings";- const entries = Object.entries(value.artifacts);- if (entries.length > MODE_LIMITS.artifacts) return `at most ${MODE_LIMITS.artifacts} artifacts`;- const artifacts: Record<string, string> = {};- for (const [id, markdown] of entries) {- if (!MODE_ID_RE.test(id)) return `artifact id "${id}" is invalid`;- if (typeof markdown !== "string") return `artifact "${id}" must be a Markdown string`;- if (Buffer.byteLength(markdown) > COMPLETE_STAGE_ARTIFACT_MAX_BYTES) {- return `artifact "${id}" is larger than ${COMPLETE_STAGE_ARTIFACT_MAX_BYTES / 1024} KiB`;+ const params: CompleteStageParams = { summary: value.summary.trim() };+ if (value.report !== undefined) {+ const report = parseCompletionReport(value.report);+ if (typeof report === "string") return report;+ params.report = report;+ }+ if (value.artifacts !== undefined) {+ if (!isRecord(value.artifacts)) return "artifacts must map artifact ids to Markdown strings";+ const entries = Object.entries(value.artifacts);+ if (entries.length > MODE_LIMITS.artifacts) return `at most ${MODE_LIMITS.artifacts} artifacts`;+ params.artifacts = {};+ for (const [id, markdown] of entries) {+ if (!MODE_ID_RE.test(id)) return `artifact id "${id}" is invalid`;+ if (typeof markdown !== "string") return `artifact "${id}" must be a Markdown string`;+ if (Buffer.byteLength(markdown) > COMPLETE_STAGE_ARTIFACT_MAX_BYTES) {+ return `artifact "${id}" is larger than ${COMPLETE_STAGE_ARTIFACT_MAX_BYTES / 1024} KiB`;+ }+ params.artifacts[id] = markdown;}- artifacts[id] = markdown;}- return { summary: value.summary.trim(), artifacts };+ return params;}/** The Host answer, checked before the tool acts on it. */@@ -180,7 +196,7 @@ export function createCompleteStageTool(deps: CompleteStageToolDeps): AgentToolname: COMPLETE_STAGE_TOOL_NAME,label: "Complete stage",description:- "Complete the current stage of the active mode run. Pass a short summary of what the stage produced and, in `artifacts`, the complete Markdown of each run artifact you write, keyed by artifact id. The host saves the artifacts and evaluates the stage's exit checks. A failed check returns its message and the retries left; when the stage advances, finishes, is blocked, or awaits approval, the turn ends. Call it only when the stage's work is done.",+ "Complete the current stage of the active mode run, or report a genuine blocker. Pass a short summary and optionally complete artifact Markdown. For success, report status completed with fresh criterion evidence; all configured exit checks still apply. If no authorized work can proceed, report status blocked, criterion outcomes, remainingWork and blockerReason; the Host records a non-success and waits for the user without running success gates. An unmet detail alone is not a blocker if other authorized work remains. Never invent evidence, expand scope, resume a paused run, or change budgets or permissions. A failed exit check remains correctable; a settled outcome ends the turn.",parameters: Type.Object({summary: Type.String({ description: "Short summary of what this stage produced." }),artifacts: Type.Optional(@@ -188,6 +204,7 @@ export function createCompleteStageTool(deps: CompleteStageToolDeps): AgentTooldescription: "Complete Markdown of each artifact to write, keyed by artifact id.",}),),+ report: Type.Optional(completionReportSchema),}),executionMode: "sequential",execute: async (_toolCallId, rawParams, signal, onUpdate) => {@@ -202,18 +219,34 @@ export function createCompleteStageTool(deps: CompleteStageToolDeps): AgentToolconst { turnId, modeTurn } = context;const identity = { sessionId: deps.sessionId, runId: modeTurn.runId, turnId };const gates: Array<{ gateIndex: number; command: string; isError: boolean }> = [];+ const ownsContext = (): boolean => {+ const current = deps.context();+ return current?.turnId === turnId && current.modeTurn.runId === modeTurn.runId+ && current.modeTurn.stageId === modeTurn.stageId && current.modeTurn.input === modeTurn.input;+ };const hostFailure = (error: unknown, gateText?: string): ToolResult => {const errorCode = hostErrorCode(error) ?? "MODE_COMPLETE_STAGE_FAILED";const terminal = TERMINAL_HOST_ERRORS.has(errorCode);- if (terminal) deps.endTurn();- const lines = [`${COMPLETE_STAGE_TOOL_NAME} failed (${errorCode}): ${errorMessage(error)}`];+ const fatal = !terminal && !CORRECTABLE_HOST_ERRORS.has(errorCode);+ const message = `${COMPLETE_STAGE_TOOL_NAME} failed (${errorCode}): ${errorMessage(error)}`;+ if (ownsContext()) {+ if (terminal) deps.endTurn();+ else if (fatal) deps.failTurn({+ code: "MODE_COMPLETE_STAGE_FAILED",+ message,+ retriable: false,+ });+ }+ const lines = [message];if (gateText) lines.push(`Gate command output:\n${gateText}`);if (errorCode === "MODE_INPUT_CHANGED") {lines.push("The user edited the run's objective after this turn started. This turn ends now; the next turn of the run receives the new objective.");} else if (terminal) {lines.push("This turn no longer holds the run; it ends now.");+ } else if (fatal) {+ lines.push("The completion channel failed. This turn stops with an error; the run must not automatically retry. The user can resume after the cause is fixed.");}- return textResult(lines.join("\n"), { errorCode, gates }, { isError: true, ...(terminal ? { terminate: true } : {}) });+ return textResult(lines.join("\n"), { errorCode, gates }, { isError: true, ...((terminal || fatal) ? { terminate: true } : {}) });};let outcome: ModeStageOutcome;@@ -222,6 +255,7 @@ export function createCompleteStageTool(deps: CompleteStageToolDeps): AgentTool...identity,summary: params.summary,...(params.artifacts ? { artifacts: params.artifacts } : {}),+ ...(params.report ? { report: params.report } : {}),// The Host refuses the report when the user edited the objective// after this turn was claimed (MODE_INPUT_CHANGED).input: modeTurn.input,@@ -231,9 +265,11 @@ export function createCompleteStageTool(deps: CompleteStageToolDeps): AgentToolreturn hostFailure(error);}+ const staleResult = (): ToolResult => textResult("This completion reply belongs to an earlier run turn.", { errorCode: "MODE_CLAIM_MISMATCH" }, { isError: true, terminate: true });let previousGate = -1;while (outcome.status === "run") {if (signal?.aborted) throw abortedError();+ if (!ownsContext()) return staleResult();const { gateIndex, command, timeoutMinutes } = outcome;// The Host evaluates gates in order; a repeated or backwards index// would loop forever.@@ -254,6 +290,7 @@ export function createCompleteStageTool(deps: CompleteStageToolDeps): AgentToolif (signal?.aborted) throw abortedError();return hostFailure(error);}+ if (!ownsContext()) return staleResult();gates.push({ gateIndex, command, isError: gate.isError });try {outcome = parseModeStageOutcome(await deps.host.call("modes.gateResult", {@@ -268,6 +305,7 @@ export function createCompleteStageTool(deps: CompleteStageToolDeps): AgentToolreturn hostFailure(error, gate.text);}}+ if (!ownsContext()) return staleResult();const text = describeStageOutcome(outcome);// A failed check is a failed completion attempt; the turn goes on sodiff --git a/packages/agent-runtime/src/modes/completion-report.test.ts b/packages/agent-runtime/src/modes/completion-report.test.tsnew file mode 100644index 000000000..b54e813e5--- /dev/null+++ b/packages/agent-runtime/src/modes/completion-report.test.ts@@ -0,0 +1,39 @@+import { expect, it } from "vitest";+import { parseCompletionReport } from "./completion-report.js";++const completed = {+ status: "completed", outcomes: [{ criterion: "Build", outcome: "met", evidence: "Build exited 0" }], remainingWork: [],+};++it("accepts bounded completed and blocked reports without treating model evidence as a gate verdict", () => {+ expect(parseCompletionReport(completed)).toEqual(completed);+ const blocked = { ...completed, status: "blocked", remainingWork: ["Obtain user approval"], blockerReason: "Approval is missing" };+ expect(parseCompletionReport(blocked)).toEqual(blocked);+});++it.each([+ null,+ { ...completed, status: "active" },+ { ...completed, maxTurns: null },+ { ...completed, input: "Replace the objective" },+ { ...completed, outcomes: [] },+ { ...completed, outcomes: Array.from({ length: 65 }, (_, i) => ({ ...completed.outcomes[0], criterion: String(i) })) },+ { ...completed, outcomes: [completed.outcomes[0], { ...completed.outcomes[0], criterion: " Build " }] },+ { ...completed, outcomes: [{ ...completed.outcomes[0], criterion: " " }] },+ { ...completed, outcomes: [{ ...completed.outcomes[0], criterion: "中".repeat(1366) }] },+ { ...completed, outcomes: [{ ...completed.outcomes[0], evidence: " " }] },+ { ...completed, outcomes: [{ ...completed.outcomes[0], evidence: "中".repeat(5462) }] },+ { ...completed, outcomes: [{ ...completed.outcomes[0], approved: true }] },+ { ...completed, outcomes: [{ ...completed.outcomes[0], outcome: "unverified" }] },+ { ...completed, blockerReason: "Already blocked" },+ { ...completed, remainingWork: ["Pending check"] },+ { ...completed, status: "blocked", blockerReason: " ", remainingWork: ["Pending check"] },+ { ...completed, status: "blocked", blockerReason: "No remaining work" },+ { ...completed, status: "blocked", blockerReason: "x".repeat(16385), remainingWork: ["Pending"] },+ { ...completed, status: "blocked", blockerReason: "Approval", remainingWork: Array(65).fill("Pending") },+ { ...completed, status: "blocked", blockerReason: "Approval", remainingWork: [" "] },+ { ...completed, status: "blocked", blockerReason: "Approval", remainingWork: ["x".repeat(4097)] },+ { ...completed, outcomes: Array.from({ length: 32 }, (_, i) => ({ criterion: String(i), outcome: "met", evidence: "x".repeat(16384) })) },+])("rejects contradictory, oversized or authority-changing report %j", (report) => {+ expect(typeof parseCompletionReport(report)).toBe("string");+});diff --git a/packages/agent-runtime/src/modes/completion-report.ts b/packages/agent-runtime/src/modes/completion-report.tsnew file mode 100644index 000000000..38254ac54--- /dev/null+++ b/packages/agent-runtime/src/modes/completion-report.ts@@ -0,0 +1,61 @@+import { Type } from "typebox";+import type { ModeCompletionReport } from "@pi-desktop/shared";++/** Same bounds are independently enforced at the Host RPC boundary. */+const MAX_ITEMS = 64;+const MAX_CRITERION_BYTES = 4096;+const MAX_EVIDENCE_BYTES = 16 * 1024;+const MAX_REPORT_BYTES = 256 * 1024;++export const completionReportSchema = Type.Object({+ status: Type.Union([Type.Literal("completed"), Type.Literal("blocked")]),+ outcomes: Type.Array(Type.Object({+ criterion: Type.String({ description: "An acceptance criterion from the original authorized task." }),+ outcome: Type.Union([Type.Literal("met"), Type.Literal("unmet"), Type.Literal("unverified")]),+ evidence: Type.String({ description: "Fresh evidence, or what prevents verification; never invent a passing check." }),+ }, { additionalProperties: false }), { minItems: 1, maxItems: MAX_ITEMS }),+ remainingWork: Type.Array(Type.String(), { maxItems: MAX_ITEMS }),+ blockerReason: Type.Optional(Type.String({ description: "Required for blocked: why no authorized work can currently proceed." })),+}, { additionalProperties: false });++function record(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function text(value: unknown, limit: number): value is string {+ return typeof value === "string" && value.trim().length > 0 && Buffer.byteLength(value) <= limit;+}++/** Validate submitted evidence, not the truth of a model's assertions. */+export function parseCompletionReport(value: unknown): ModeCompletionReport | string {+ if (!record(value)) return "report must be an object";+ if (Object.keys(value).some((key) => !["status", "outcomes", "remainingWork", "blockerReason"].includes(key))) return "unknown report field";+ if (value.status !== "completed" && value.status !== "blocked") return "report status must be completed or blocked";+ if (!Array.isArray(value.outcomes) || value.outcomes.length < 1 || value.outcomes.length > MAX_ITEMS) return "report requires 1 to 64 criterion outcomes";+ const outcomes: ModeCompletionReport["outcomes"] = [];+ const criteria = new Set<string>();+ for (const item of value.outcomes) {+ if (!record(item) || Object.keys(item).some((key) => !["criterion", "outcome", "evidence"].includes(key))) return "invalid report outcome fields";+ if (!text(item.criterion, MAX_CRITERION_BYTES)) return "report criterion must be nonblank and at most 4 KiB";+ if (criteria.has(item.criterion.trim())) return "report criteria must be unique";+ criteria.add(item.criterion.trim());+ if (item.outcome !== "met" && item.outcome !== "unmet" && item.outcome !== "unverified") return "invalid criterion outcome";+ if (!text(item.evidence, MAX_EVIDENCE_BYTES)) return "report evidence must be nonblank and at most 16 KiB";+ outcomes.push({ criterion: item.criterion, outcome: item.outcome, evidence: item.evidence });+ }+ if (!Array.isArray(value.remainingWork) || value.remainingWork.length > MAX_ITEMS+ || !value.remainingWork.every((item) => text(item, MAX_CRITERION_BYTES))) return "remainingWork must contain at most 64 nonblank items of at most 4 KiB";+ if (value.blockerReason !== undefined && !text(value.blockerReason, MAX_EVIDENCE_BYTES)) return "blockerReason must be nonblank and at most 16 KiB";+ if (value.status === "completed" && (outcomes.some((item) => item.outcome !== "met") || value.remainingWork.length || value.blockerReason !== undefined)) {+ return "completed report requires all criteria met, no remaining work, and no blocker";+ }+ if (value.status === "blocked" && (!value.blockerReason || (outcomes.every((item) => item.outcome === "met") && !value.remainingWork.length))) {+ return "blocked report requires a blockerReason and unfinished or unverified work";+ }+ const report: ModeCompletionReport = {+ status: value.status, outcomes, remainingWork: value.remainingWork,+ ...(typeof value.blockerReason === "string" ? { blockerReason: value.blockerReason } : {}),+ };+ if (Buffer.byteLength(JSON.stringify(report)) > MAX_REPORT_BYTES) return "report exceeds 256 KiB";+ return report;+}diff --git a/packages/agent-runtime/src/modes/mode-state.test.ts b/packages/agent-runtime/src/modes/mode-state.test.tsindex 6937b91ed..f215a9730 100644--- a/packages/agent-runtime/src/modes/mode-state.test.ts+++ b/packages/agent-runtime/src/modes/mode-state.test.ts@@ -118,3 +118,15 @@ describe("mode turn notices", () => {}});});++it("adds blocked reporting to an existing immutable Goal snapshot without changing its objective or gates", async () => {+ const snapshot = goal();+ snapshot.prompt = "Legacy Goal instructions: complete only after verification.";+ const before = JSON.stringify(snapshot);+ const state = new RuntimeModeState("goal", snapshot);+ await state.beginTurn(TURN, missing);+ expect(state.instructions()).toContain("report.status: blocked");+ expect(state.instructions()).toContain("not successful completion");+ expect(state.instructions()).toContain(TURN.input);+ expect(JSON.stringify(snapshot)).toBe(before);+});diff --git a/packages/agent-runtime/src/modes/stage-brief.ts b/packages/agent-runtime/src/modes/stage-brief.tsindex 7725c8490..c8a2e4677 100644--- a/packages/agent-runtime/src/modes/stage-brief.ts+++ b/packages/agent-runtime/src/modes/stage-brief.ts@@ -133,7 +133,7 @@ function originLine(turn: ModeTurnContext): string {function flowLine(stage: ModeStage): string {if (stage.loop) {- return "This stage repeats: after each turn the host starts another turn of it until its exit checks pass or the run's budget runs out.";+ return "This stage repeats: after each normal turn the host starts another turn until its exit checks pass, a blocked report or execution error stops continuation, or the run's budget runs out.";}if (stage.exit.length === 0) {return `This stage has no exit checks: it completes when this turn ends, or as soon as you call ${COMPLETE_STAGE_TOOL_NAME}.`;@@ -180,6 +180,8 @@ export function stageBrief(definition: ModeDefinition, stage: ModeStage, turn: Mlines.push("",`Call ${COMPLETE_STAGE_TOOL_NAME} with a short summary of what the stage produced and the complete Markdown of every artifact you write (\`artifacts: { <id>: <markdown> }\`) once the stage's work is done. If a check fails, fix the cause and call it again. When it reports that the stage advanced, finished, is blocked, or awaits approval, the turn ends.`,+ `A blocker report is not successful completion or an ordinary progress update. Even when the saved stage instructions permit completion only after verification, use ${COMPLETE_STAGE_TOOL_NAME} with report.status: blocked if no authorized work can currently proceed. Include outcomes for the original acceptance criteria (met, unmet, or unverified, each with evidence), remainingWork, and a concrete blockerReason. This records a non-success and stops autonomous continuation until the user intervenes. Do not report blocked just because one detail is unfinished when other authorized work can proceed.`,+ "For a completed report, every criterion must be met with fresh evidence, remainingWork must be empty, and blockerReason must be absent. Reports cannot change the objective, budget, permissions, or user controls; successful completion still requires the configured exit checks.",);return lines.join("\n");}diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex a5706ad19..7f8c5c6d9 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -4557,6 +4557,13 @@ Do not invent objections or turn speculative risks into blockers. Stop when theendTurn: () => {this.gracefulStopRequested = true;},+ failTurn: (failure) => {+ this.terminateParentTurn();+ this.gracefulStopRequested = true;+ const error = { ...classifyAgentError(new Error(failure.message)), code: failure.code, retriable: false };+ this.finalizeCurrentAssistant("error", error);+ this.emit({ type: "error", error });+ },});}diff --git a/packages/computer-use/package.json b/packages/computer-use/package.jsonindex 9ac6cf0ee..5323ceced 100644--- a/packages/computer-use/package.json+++ b/packages/computer-use/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/computer-use",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","main": "./dist/index.js",diff --git a/packages/host-runtime/package.json b/packages/host-runtime/package.jsonindex 339dc52e8..cde68a31b 100644--- a/packages/host-runtime/package.json+++ b/packages/host-runtime/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/host-runtime",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","main": "./dist/index.js",diff --git a/packages/host-runtime/src/agent-sidecar.ts b/packages/host-runtime/src/agent-sidecar.tsindex eefe0c471..cbac8d280 100644--- a/packages/host-runtime/src/agent-sidecar.ts+++ b/packages/host-runtime/src/agent-sidecar.ts@@ -70,6 +70,9 @@ const HOST_PROXY_ALLOWED = new Set(["plans.submit","plans.pending","plans.abort",+ // Host validates the live session/run/turn claim; user controls stay private.+ "modes.completeStage",+ "modes.gateResult","project.instructions.resolve","provider.resolveAuth","provider.resolveSubagentModel",diff --git a/packages/host-runtime/src/host-ports.ts b/packages/host-runtime/src/host-ports.tsindex 5aa5cc7bb..4ab6f1ebc 100644--- a/packages/host-runtime/src/host-ports.ts+++ b/packages/host-runtime/src/host-ports.ts@@ -118,6 +118,7 @@ export type HostQueueEntry = {idempotencyKey?: string;inputHash: string;content: string;+ startGoal?: boolean;sessionMessageId?: string;userMessageId?: string;voiceOrigin?: VoiceOrigin;@@ -136,6 +137,7 @@ export function fromHostQueueEntry(entry: HostQueueEntry): QueuedTurnRecord {sessionId: entry.sessionId,principalSubject: entry.principal,content: entry.content,+ startGoal: entry.startGoal === true,...(entry.sessionMessageId ? { sessionMessageId: entry.sessionMessageId } : {}),...(entry.userMessageId ? { userMessageId: entry.userMessageId } : {}),...(entry.voiceOrigin ? { voiceOrigin: entry.voiceOrigin } : {}),@@ -165,6 +167,7 @@ export function createHostQueueStore(getHost: () => HostRpc | null): QueueStore...(record.idempotencyKey ? { idempotencyKey: record.idempotencyKey } : {}),inputHash: record.inputHash,content: record.content,+ ...(record.startGoal ? { startGoal: true } : {}),...(record.sessionMessageId ? { sessionMessageId: record.sessionMessageId } : {}),...(record.userMessageId ? { userMessageId: record.userMessageId } : {}),...(record.voiceOrigin ? { voiceOrigin: record.voiceOrigin } : {}),diff --git a/packages/host-runtime/src/sidecar-mode-completion.test.ts b/packages/host-runtime/src/sidecar-mode-completion.test.tsnew file mode 100644index 000000000..6bebe0460--- /dev/null+++ b/packages/host-runtime/src/sidecar-mode-completion.test.ts@@ -0,0 +1,66 @@+import { afterEach, expect, it, vi } from "vitest";+import { AgentSidecar, type SidecarHostLink } from "./agent-sidecar.js";++const sidecars: AgentSidecar[] = [];+afterEach(async () => {+ await Promise.all(sidecars.splice(0).map((sidecar) => sidecar.dispose()));+});++/** A model boundary fixture; the production receiver handles every reverse RPC. */+function proxy(invoke: (method: string, params?: unknown) => Promise<unknown>) {+ const source = `+ const pending = new Map();+ const rl = require('node:readline').createInterface({ input: process.stdin });+ rl.on('line', line => {+ const frame = JSON.parse(line);+ if (frame.method === 'probe') {+ const id = 'reverse-' + frame.id;+ pending.set(id, frame.id);+ console.log(JSON.stringify({ jsonrpc: '2.0', id, method: 'host.proxy', params: frame.params }));+ } else if (pending.has(frame.id)) {+ const id = pending.get(frame.id);+ pending.delete(frame.id);+ console.log(JSON.stringify({ jsonrpc: '2.0', id, ...('error' in frame ? {error: frame.error} : {result: frame.result}) }));+ }+ });`;+ const sidecar = new AgentSidecar({+ launch: { command: process.execPath, args: ["-e", source] },+ onStderr: () => {},+ });+ const host: SidecarHostLink = {+ call: async <T = unknown>(method: string, params?: unknown): Promise<T> => await invoke(method, params) as T,+ onNotification: () => () => {},+ onExit: () => () => {},+ };+ sidecar.setHost(host);+ sidecars.push(sidecar);+ return sidecar;+}++it.each(["modes.completeStage", "modes.gateResult"])("forwards %s through real stdio without changing the claim", async (method) => {+ const outcome = { status: "finished", run: { id: "run-1", state: "finished" } };+ const invoke = vi.fn(async () => outcome);+ const sidecar = proxy(invoke);+ const params = { sessionId: "session-1", runId: "run-1", turnId: "turn-1", input: "Original objective", summary: "Verified" };+ expect(await sidecar.call("probe", { method, params })).toEqual(outcome);+ expect(invoke).toHaveBeenCalledExactlyOnceWith(method, params);+});++it.each(["modes.start", "modes.control", "modes.update", "modes.resolve", "modes.settleTurn", "provider.get"])(+ "does not expose %s to model-directed sidecar code",+ async (method) => {+ const invoke = vi.fn(async () => ({}));+ const sidecar = proxy(invoke);+ await expect(sidecar.call("probe", { method, params: {} })).rejects.toMatchObject({ code: -32601 });+ expect(invoke).not.toHaveBeenCalled();+ },+);++it.each(["MODE_CLAIM_MISMATCH", "MODE_INPUT_CHANGED", "MODE_INVALID_ARGUMENT"])("preserves Host rejection %s", async (errorCode) => {+ const sidecar = proxy(async () => {+ throw Object.assign(new Error(errorCode), { code: -32000, data: { errorCode } });+ });+ await expect(sidecar.call("probe", { method: "modes.completeStage", params: { runId: "stale" } })).rejects.toMatchObject({+ code: -32000, errorCode, data: { errorCode },+ });+});diff --git a/packages/i18n/package.json b/packages/i18n/package.jsonindex 80603bd6f..b35c01e6f 100644--- a/packages/i18n/package.json+++ b/packages/i18n/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/i18n",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","main": "./dist/index.js",diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 52fac8034..42a3ed5c9 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -876,6 +876,7 @@ export const de = {"budgetExhausted": "Budget aufgebraucht",},"rounds": "Runden {{completed}}/{{max}}",+ "elapsed": "Dauer {{duration}}","lastError": "Letzter Fehler: {{message}}","pause": "Pausieren","resume": "Fortsetzen",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 7a01eef55..1ae9d6cf3 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -888,6 +888,7 @@ export const en = {budgetExhausted: "Budget exhausted",},rounds: "Rounds {{completed}}/{{max}}",+ elapsed: "Elapsed {{duration}}",lastError: "Last error: {{message}}",pause: "Pause",resume: "Resume",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 1d9224899..29c7206b7 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -876,6 +876,7 @@ export const es = {"budgetExhausted": "Presupuesto agotado",},"rounds": "Rondas {{completed}}/{{max}}",+ "elapsed": "Tiempo {{duration}}","lastError": "Último error: {{message}}","pause": "Pausar","resume": "Reanudar",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 00341ff32..0bf83620e 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -876,6 +876,7 @@ export const fr = {"budgetExhausted": "Budget épuisé",},"rounds": "Tours {{completed}}/{{max}}",+ "elapsed": "Durée {{duration}}","lastError": "Dernière erreur : {{message}}","pause": "Mettre en pause","resume": "Reprendre",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 9f300ee74..805ed2941 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -885,6 +885,7 @@ export const ko = {budgetExhausted: "예산 소진",},rounds: "라운드 {{completed}}/{{max}}",+ elapsed: "소요 시간 {{duration}}",lastError: "마지막 오류: {{message}}",pause: "일시 중지",resume: "재개",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 1f6ffc31f..46654830e 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -875,6 +875,7 @@ export const ptBR = {budgetExhausted: "Orçamento esgotado",},rounds: "Rodadas {{completed}}/{{max}}",+ elapsed: "Tempo {{duration}}",lastError: "Último erro: {{message}}",pause: "Pausar",resume: "Retomar",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex b486d0ba9..9ed72c627 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -885,6 +885,7 @@ export const tr = {budgetExhausted: "Bütçe tükendi",},rounds: "Turlar {{completed}}/{{max}}",+ elapsed: "Geçen süre {{duration}}",lastError: "Son hata: {{message}}",pause: "Duraklat",resume: "Sürdür",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex c8982aae1..aec05f14f 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -881,6 +881,7 @@ export const zhCN = {budgetExhausted: "预算已用完",},rounds: "轮次 {{completed}}/{{max}}",+ elapsed: "耗时 {{duration}}",lastError: "最近错误:{{message}}",pause: "暂停",resume: "继续",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex a16ee6191..f778eb137 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -881,6 +881,7 @@ export const zhTW = {budgetExhausted: "預算已用完",},rounds: "輪次 {{completed}}/{{max}}",+ elapsed: "耗時 {{duration}}",lastError: "最近錯誤:{{message}}",pause: "暫停",resume: "繼續",diff --git a/packages/plugin-devkit/package.json b/packages/plugin-devkit/package.jsonindex 0406e0c50..16c60b2b0 100644--- a/packages/plugin-devkit/package.json+++ b/packages/plugin-devkit/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/plugin-devkit",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","main": "./dist/index.js",diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.jsonindex 7532598a2..0f6ce3ef5 100644--- a/packages/plugin-sdk/package.json+++ b/packages/plugin-sdk/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/plugin-sdk",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","main": "./dist/index.js",diff --git a/packages/racp/package.json b/packages/racp/package.jsonindex 2aced7cbd..738236124 100644--- a/packages/racp/package.json+++ b/packages/racp/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/racp",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","main": "./dist/index.js",diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 77c26450b..c3715bafd 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/shared",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","main": "./dist/index.js",diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 5f34dd4d9..8dfc50c27 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -2,7 +2,7 @@ export const PROTOCOL_VERSION = 11 as const;export const SCHEMA_VERSION = 16 as const;export const APP_ID = "net.aiuo.pi-desktop";export const APP_NAME = "PI-Desktop";-export const APP_VERSION = "0.21.0";+export const APP_VERSION = "0.21.2";export const APP_MENU_COMMANDS = ["newTask",diff --git a/packages/shared/src/types/agent.ts b/packages/shared/src/types/agent.tsindex ff266a101..e3a15276a 100644--- a/packages/shared/src/types/agent.ts+++ b/packages/shared/src/types/agent.ts@@ -11,6 +11,8 @@ import type { RacpPermissionMode } from "../racp.js";export type AgentPromptRequest = {sessionId: string;content: string;+ /** Explicit user request to start a fresh builtin Goal, never inferred from text. */+ startGoal?: boolean;/** Host-owned collaboration delivery; its durable record supplies the input. */sessionMessageId?: string;/** Attachments are resolved by Electron main and never trusted by the sidecar. */@@ -120,6 +122,7 @@ export type QueuedTurnSummary = {id: string;sessionId: string;content: string;+ startGoal?: boolean;sessionMessageId?: string;userMessageId?: string;voiceOrigin?: VoiceOrigin;@@ -133,6 +136,7 @@ export type QueuedTurnSummary = {export type AgentQueuePushRequest = {sessionId: string;content: string;+ startGoal?: boolean;sessionMessageId?: string;userMessageId?: string;voiceOrigin?: VoiceOrigin;diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.tsindex 81f6e8f69..45184ece2 100644--- a/packages/shared/src/types/messages.ts+++ b/packages/shared/src/types/messages.ts@@ -111,6 +111,8 @@ export type ToolTokenUsage = {export type UiMessage = {id: string;+ /** Durable root conversation identity for display grouping, never authorization. */+ turnId?: string;role: UiMessageRole;content: string;/** Internal model instructions/tool declarations; never a visible chat row. */diff --git a/packages/shared/src/types/mode-runs.ts b/packages/shared/src/types/mode-runs.tsindex b1fda22ac..ed5391b30 100644--- a/packages/shared/src/types/mode-runs.ts+++ b/packages/shared/src/types/mode-runs.ts@@ -14,10 +14,10 @@ export type ModeRunState =| "stopped";/** Why a `waiting` run waits. */-export type ModeRunWaitReason = "approval" | "retries" | "turn_end" | "error";+export type ModeRunWaitReason = "approval" | "retries" | "turn_end" | "error" | "blocked";-/** Who started the turn that holds the claim. `host` turns run at most- * `accept-edits`; `user` and `approval` turns keep the session permission. */+/** Builtin Goal keeps the session permission; other `host` turns run at most+ * `accept-edits`. User and approval turns keep the session permission. */export type ModeTurnOrigin = "user" | "approval" | "host";export const MODE_RUN_OPEN_STATES: readonly ModeRunState[] = ["running", "waiting", "paused", "budget_exhausted"];@@ -26,6 +26,14 @@ export function isModeRunOpen(state: ModeRunState): boolean {return MODE_RUN_OPEN_STATES.includes(state);}+/** Model-submitted evidence, not an independent verification of its truth. */+export type ModeCompletionReport = {+ status: "completed" | "blocked";+ outcomes: Array<{ criterion: string; outcome: "met" | "unmet" | "unverified"; evidence: string }>;+ remainingWork: string[];+ blockerReason?: string;+};+export type ModeRun = {id: string;sessionId: string;@@ -38,11 +46,17 @@ export type ModeRun = {waitReason?: ModeRunWaitReason;/** Last gate or turn failure shown to the user. */lastError?: string;+ /** Last submitted stage report; exit gates still decide successful completion. */+ completionReport?: ModeCompletionReport;revision: number;activeTurnId?: string;activeOrigin?: ModeTurnOrigin;roundsCompleted: number;tokensUsed: number;+ /** Accumulated active time; legacy hosts may omit it. */+ elapsedMs?: number;+ /** Epoch milliseconds of the current active interval, absent while frozen. */+ activeSinceMs?: number;maxTurns: number | null;maxTokens: number | null;/** Workspace-relative artifact paths resolved for this run. */diff --git a/packages/voice-runtime/package.json b/packages/voice-runtime/package.jsonindex 373d87387..7f7359aea 100644--- a/packages/voice-runtime/package.json+++ b/packages/voice-runtime/package.json@@ -1,6 +1,6 @@{"name": "@pi-desktop/voice-runtime",- "version": "0.21.0",+ "version": "0.21.2","private": true,"type": "module","exports": {diff --git a/scripts/e2e-goal-completion.mjs b/scripts/e2e-goal-completion.mjsnew file mode 100644index 000000000..d8a96b16c--- /dev/null+++ b/scripts/e2e-goal-completion.mjs@@ -0,0 +1,242 @@+#!/usr/bin/env node+/** Real production sidecar/proxy/Host completion; only the model is a loopback fixture. */+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";+import { join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { register } from "node:module";+import { setImmediate as nextEventLoop } from "node:timers/promises";+import { resolveHostBinary } from "./e2e/host.mjs";+import { createSession, beginTurn, endTurn } from "./e2e/session.mjs";+import { AgentSidecar } from "../packages/host-runtime/dist/agent-sidecar.js";+import { HostProcess } from "../packages/host-runtime/dist/host-process.js";+import { TurnEventPipeline } from "../packages/host-runtime/dist/turn-events.js";++register(new URL("../apps/desktop/test/helpers/ts-import-hooks.mjs", import.meta.url));+const { createModeRunCoordinator } = await import("../apps/desktop/electron/main/runtime/mode-runs.ts");+const { createModeCatalogService } = await import("../apps/desktop/electron/main/runtime/mode-catalog.ts");+const { createSessionCoordination } = await import("../apps/desktop/electron/main/runtime/session-coordination.ts");+const { createPlanRuntime } = await import("../apps/desktop/electron/main/runtime/plans.ts");+const { createAgentHostBridge } = await import("../apps/desktop/electron/main/agent-host-bridge.ts");+const { builtinModeDefinition } = await import("../packages/agent-runtime/dist/mode-definitions.js");+const { IPC } = await import("@pi-desktop/shared");+const scratch = process.env.PI_SCRATCH_DIR;+assert.ok(scratch, "PI_SCRATCH_DIR is required");+const root = await mkdtemp(join(scratch, "goal-completion-"));+const agents = join(root, "agents");+await mkdir(agents, { recursive: true });+const entry = resolve(process.env.PI_DESKTOP_SIDECAR_ENTRY ?? fileURLToPath(new URL("../packages/agent-runtime/dist-bundle/sidecar.js", import.meta.url)));+const binary = resolveHostBinary();++async function scenario(kind) {+ const dir = join(root, kind);+ const dataDir = join(dir, "data");+ const workspace = join(dir, "workspace");+ await Promise.all([mkdir(dataDir, { recursive: true }), mkdir(workspace, { recursive: true })]);+ const env = { PI_DESKTOP_DATA_DIR: dataDir, PI_DESKTOP_AGENTS_DIR: agents, TMP: scratch, TEMP: scratch, TMPDIR: scratch };+ let host;+ let sidecar;+ let pipeline;+ let requests = 0;+ const errors = [];+ const settlements = [];+ const stageOutcomes = [];+ let continuations = 0;+ let gateApprovals = 0;+ let completedArgs;+ const server = createServer(async (request, response) => {+ try {+ let raw = "";+ for await (const part of request) raw += part;+ const body = JSON.parse(raw);+ assert.equal(request.url, "/v1/chat/completions");+ assert.ok(body.tools.some((tool) => tool.function?.name === "CompleteStage"));+ requests += 1;+ const delta = requests === 1+ ? { role: "assistant", tool_calls: [{ index: 0, id: "completion-call", type: "function", function: { name: "CompleteStage", arguments: JSON.stringify(completedArgs) } }] }+ : { role: "assistant", content: "Unexpected extra model request" };+ response.writeHead(200, { "content-type": "text/event-stream" });+ response.end(`data: ${JSON.stringify({ id: "fixture", object: "chat.completion.chunk", created: 1, model: "fixture", choices: [{ index: 0, delta, finish_reason: requests === 1 ? "tool_calls" : "stop" }], usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 } })}\n\ndata: [DONE]\n\n`);+ } catch (error) {+ errors.push(String(error));+ response.writeHead(500);+ response.end("Fixture rejected request");+ }+ });+ try {+ await new Promise((done) => server.listen(0, "127.0.0.1", done));+ const baseUrl = `http://127.0.0.1:${server.address().port}/v1`;+ const startHost = async () => {+ const process = new HostProcess({ binaryPath: binary, dataDir, env, onStderr() {} });+ await process.handshake();+ await process.call("workspace.set", { path: workspace });+ return process;+ };+ host = await startHost();+ const session = await createSession(host, workspace, `Completion ${kind}`);+ const sessionId = session.id;+ host.onNotification((method, params) => {+ if (method !== "permissions.request") return;+ const allowed = kind === "gate" && params.sessionId === sessionId && params.toolName === "Bash"+ && String(params.toolCallId).startsWith("mode-gate-") && JSON.stringify(params.argsPreview).includes("echo completion-gate-ok");+ if (allowed) gateApprovals += 1;+ else errors.push("Unexpected permission request");+ void host.call("permissions.resolve", { requestId: params.requestId, decision: allowed ? "allow-once" : "deny" })+ .catch((error) => errors.push(String(error)));+ });+ const definition = builtinModeDefinition("goal");+ assert.ok(definition);+ if (kind === "snapshot") definition.stages[0].prompt = "Legacy snapshot: complete only when all work is verified.";+ if (kind === "gate") {+ definition.id = "completion-gate";+ definition.source = "user";+ definition.stages[0].exit.push({ kind: "run", command: "echo completion-gate-ok", timeoutMinutes: 1, onFail: { retries: 0 } });+ }+ await host.call("session.configure", { id: sessionId, mode: definition.id, modeSnapshot: definition, permissionMode: "auto" });+ const resumedSnapshot = kind === "snapshot" || kind === "gate";+ if (resumedSnapshot) {+ const seedTurn = await beginTurn(host, sessionId);+ const seed = await host.call("modes.start", { sessionId, turnId: seedTurn, input: "Verify the completion fixture" });+ await endTurn(host, seedTurn, "aborted");+ const paused = await host.call("modes.settleTurn", { sessionId, runId: seed.run.id, turnId: seedTurn, tokens: 0, outcome: "aborted" });+ await host.call("modes.control", { sessionId, runId: seed.run.id, expectedRevision: paused.run.revision, action: "resume" });+ }+ const port = { async call(method, params) {+ const answer = await host.call(method, params);+ if (method === "modes.settleTurn") settlements.push(answer);+ return answer;+ } };+ const activeTurns = new Map();+ const coordination = createSessionCoordination({ activeTurns, getMainWindow: () => null, getViewingSessionId: () => null });+ const bridge = createAgentHostBridge({ channels: IPC.invoke, getHost: () => port, isSessionBusy: coordination.isSessionBusy,+ invoke: async () => { throw new Error("No extra turn is authorized by this fixture"); }, log() {} });+ const runs = createModeRunCoordinator({ getHost: () => port, catalog: createModeCatalogService({ dir: join(dataDir, "modes") }),+ logger: { app() {} }, isQuitting: () => false, startContinuation: async () => { continuations += 1; },+ abortTurn: async () => {}, notifyTurn: async () => {},+ });+ const plans = createPlanRuntime({+ runtimeState: { host: port, agentHostBridge: bridge }, planState: { approvedExecutionDrain: null }, logger: { app() {} },+ sendToRenderer() {}, coordination, scheduledRunsBySession: new Map(), activeToolCalls: new Map(), planSubmissionTurnIds: new Set(),+ approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(), approvedExecutionTurns: new Map(),+ startedApprovedExecutions: new Set(), finishedApprovedExecutions: new Set(), dispatchingApprovedExecutions: new Set(),+ inFlightExecutionFinishes: new Set(), pendingExecutionFinishes: new Map(), announceTurnEnded() {}, emitAgentEvent() {},+ acquireSessionOperation: coordination.acquireSessionOperation, isQuitting: () => false,+ onTurnEnded: (...args) => runs.settleTurn(...args),+ });+ const turnId = await beginTurn(host, sessionId);+ activeTurns.set(sessionId, turnId);+ coordination.recordTurnStart(sessionId, turnId);+ const prepared = await runs.prepareTurn({ sessionId, turnId, sessionMode: definition.id, origin: resumedSnapshot ? "host" : "user", content: "Verify the completion fixture" });+ assert.ok(prepared?.modeTurn);+ const runId = prepared.modeTurn.runId;+ const markdown = "# Objective\nVerify the completion fixture\n# Acceptance criteria\nObserve a real Host completion\n# Evidence\nDeterministic loopback model and real Host.\n";+ const report = kind === "blocked"+ ? { status: "blocked", outcomes: [{ criterion: "Approval", outcome: "unverified", evidence: "Only the user can approve the missing prerequisite" }], remainingWork: ["Verify after user approval"], blockerReason: "A required user decision is missing" }+ : { status: "completed", outcomes: [{ criterion: "Completion fixture", outcome: "met", evidence: "The scripted fixture reached the authorized completion step" }], remainingWork: [] };+ completedArgs = { summary: `Fixture ${kind}`, ...(kind === "blocked" ? {} : { artifacts: { goal: markdown } }), ...(kind === "legacy" ? {} : { report }) };+ const finished = Promise.withResolvers();+ const ended = Promise.withResolvers();+ let finalization;+ pipeline = new TurnEventPipeline({ getHost: () => host,+ ownership: { activeTurnId: (id) => activeTurns.get(id),+ isStaleTerminalEvent: coordination.isStaleTerminalEvent,+ finishTurn: (...args) => {+ finalization ??= plans.finishTurn(...args);+ void finalization.then(finished.resolve, finished.reject);+ return finalization;+ },+ },+ emit: (event) => {+ bridge.ingest(event);+ if (event.event.type === "agent_end") ended.resolve();+ if (event.event.type === "error") errors.push(event.event.error.code);+ }, log() {},+ });+ sidecar = new AgentSidecar({ launch: { command: process.execPath, args: [entry], cwd: workspace, env: { ...process.env, ...env } }, onStderr() {} });+ sidecar.setHost({+ async call(method, params) {+ if (kind === "fault" && method === "modes.completeStage") throw Object.assign(new Error("fixture unavailable completion RPC"), { code: -32601 });+ const answer = await host.call(method, params);+ if (method === "modes.completeStage" || method === "modes.gateResult") stageOutcomes.push(answer);+ return answer;+ }, onNotification: (handler) => host.onNotification(handler), onExit: (handler) => host.onExit(handler),+ });+ sidecar.onNotification((method, event) => {+ if (method !== "agent.event") return;+ if (event.event.type === "agent_end") ended.resolve();+ pipeline.handle(event);+ });+ await sidecar.call("sidecar.configure", { networkProxy: { mode: "direct" } });+ const shell = (await host.call("commandShells.list")).effective;+ await sidecar.call("agent.prompt", {+ sessionId, turnId, content: "Verify the completion fixture", mode: definition.id, modeDefinition: prepared.definition, modeTurn: prepared.modeTurn,+ workspaceRoot: workspace, projectPath: workspace, projectInstructions: { entries: [] }, scratchDir: dir,+ commandShell: shell, thinkingLevel: "off", trustedExtensions: [], pluginTools: [], pluginSkills: [], subagents: [],+ compactionSettings: { enabled: false, reserveTokens: 0, keepRecentTokens: 0 },+ provider: { id: "fixture", name: "Offline fixture", vendorKey: "custom", baseUrl, modelId: "fixture", apiKey: "fixture-only",+ apiStyle: "chat_completions", supportsReasoning: false, supportedThinkingLevels: ["off"],+ modelConfig: { source: "generic", name: "Fixture", baseUrl, reasoning: false, input: ["text"],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 128000, maxTokens: 4096 },+ },+ });+ let deadline;+ try {+ await Promise.race([Promise.all([finished.promise, ended.promise]), new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error(`Completion timed out: ${kind}; ${errors.join(", ")}`)), 30000); })]);+ } finally { clearTimeout(deadline); }+ await nextEventLoop();+ assert.equal(requests, 1, "no next model request after completion, blocker or infrastructure failure");+ assert.equal(gateApprovals, kind === "gate" ? 1 : 0, "the custom Host-origin gate retains its permission ceiling");+ assert.equal(settlements.length, 1, "error plus agent_end settles once");+ const settled = settlements[0];+ assert.equal(settled.continue, false);+ assert.equal(settled.run.activeTurnId, undefined);+ assert.equal(await runs.canContinue(sessionId), false);+ assert.equal(continuations, 0, "Main must not schedule another autonomous round");+ if (kind === "blocked") {+ assert.equal(settled.run.state, "waiting");+ assert.equal(settled.run.waitReason, "blocked");+ assert.deepEqual(settled.run.completionReport, report);+ assert.equal(stageOutcomes[0].status, "blocked");+ assert.deepEqual(errors, []);+ } else if (kind === "fault") {+ assert.equal(settled.run.state, "waiting");+ assert.equal(settled.run.waitReason, "error");+ assert.equal(settled.run.roundsCompleted, 0);+ assert.deepEqual(errors, ["MODE_COMPLETE_STAGE_FAILED"]);+ } else {+ assert.equal(settled.run.state, "finished");+ assert.equal(stageOutcomes.at(-1).status, "finished");+ assert.equal((await host.call("modes.get", { sessionId })).run, null);+ assert.equal(await readFile(join(workspace, prepared.modeTurn.artifactPaths.goal), "utf8"), markdown);+ if (kind === "gate") assert.deepEqual(stageOutcomes.map((outcome) => outcome.status), ["run", "finished"]);+ assert.deepEqual(errors, []);+ }+ const again = await host.call("modes.settleTurn", { sessionId, runId, turnId, tokens: 999, outcome: "completed" });+ assert.equal(again.continue, false);+ assert.equal(again.run.tokensUsed, settled.run.tokensUsed);+ assert.equal(again.run.roundsCompleted, settled.run.roundsCompleted);+ await sidecar.dispose(); sidecar = undefined;+ await pipeline.dispose(); pipeline = undefined;+ await host.dispose();+ host = await startHost();+ const restored = (await host.call("modes.get", { sessionId })).run;+ if (kind === "blocked" || kind === "fault") {+ assert.equal(restored.state, "waiting");+ assert.equal(restored.waitReason, kind === "blocked" ? "blocked" : "error");+ assert.equal(restored.activeTurnId, undefined);+ if (kind === "blocked") assert.deepEqual(restored.completionReport, report);+ } else assert.equal(restored, null);+ console.log(`PASS ${kind}: production sidecar -> stdio proxy -> real Host -> Main settlement; no continuation; duplicate settlement and restart safe`);+ } finally {+ await sidecar?.dispose();+ await pipeline?.dispose();+ await host?.dispose();+ server.closeAllConnections();+ await new Promise((done) => server.close(done));+ }+}++try {+ for (const kind of ["finished", "legacy", "blocked", "fault", "gate", "snapshot"]) await scenario(kind);+} finally { await rm(root, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 }); }diff --git a/scripts/e2e-goal-layout.mjs b/scripts/e2e-goal-layout.mjsnew file mode 100644index 000000000..8a7314017--- /dev/null+++ b/scripts/e2e-goal-layout.mjs@@ -0,0 +1,163 @@+#!/usr/bin/env node+/** Isolated production-component/Chromium geometry; no Desktop instance, Host or provider. */+import assert from "node:assert/strict";+import { spawn, execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { existsSync } from "node:fs";+import { mkdir, mkdtemp, readFile, readdir, stat, writeFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { dirname, isAbsolute, join, relative, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const desktop = join(root, "apps/desktop");+const scratch = process.env.PI_SCRATCH_DIR;+assert(scratch && isAbsolute(scratch), "PI_SCRATCH_DIR must name an absolute isolated scratch directory");+for (const key of ["TMP", "TEMP", "TMPDIR"]) process.env[key] = scratch;+await mkdir(scratch, { recursive: true });+const renderer = join(desktop, "out/renderer");+assert(existsSync(join(renderer, "index.html")), "Task renderer CSS is not built yet: apps/desktop/out/renderer/index.html");+const html = await readFile(join(renderer, "index.html"), "utf8");+const styles = [...html.matchAll(/<link\b[^>]*>/g)].map(([tag]) => {+ if (!/\brel=["']stylesheet["']/.test(tag)) return null;+ return /\bhref=["']([^"']+)["']/.exec(tag)?.[1];+}).filter(Boolean);+assert(styles.length > 0, "No built stylesheet is linked by the task renderer");+// Modes are lazy-loaded by the app, so their CSS need not be linked by index.html.+for (const name of await readdir(join(renderer, "assets"))) {+ const href = `assets/${name}`;+ if (name.endsWith(".css") && !styles.includes(href) &&+ (await readFile(join(renderer, href), "utf8")).includes(".mode-run-bar")) styles.push(href);+}+const temp = await mkdtemp(join(scratch, "goal-layout-"));+const cssEvidence = [];+for (const [index, href] of styles.entries()) {+ assert(!/^[a-z]+:/i.test(href), "Remote stylesheets are not allowed");+ const source = resolve(renderer, href.replace(/^\//, ""));+ assert(!relative(renderer, source).startsWith(".."), "Stylesheet is outside the task renderer");+ const bytes = await readFile(source);+ await writeFile(join(temp, `built-${index}.css`), bytes);+ cssEvidence.push({ path: relative(root, source), sha256: createHash("sha256").update(bytes).digest("hex"), modifiedAt: (await stat(source)).mtime.toISOString() });+}+const require = createRequire(join(desktop, "package.json"));+const { build } = require("esbuild");+const candidate = execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim();+const base = execFileSync("git", ["rev-parse", "origin/main"], { cwd: root, encoding: "utf8" }).trim();+await build({+ entryPoints: [join(root, "scripts/e2e/goal-layout.tsx")],+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "iife", jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env": "{}" },+ loader: { ".css": "empty" },+ alias: {+ "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),+ react: dirname(require.resolve("react/package.json")),+ "react-dom": dirname(require.resolve("react-dom/package.json")),+ },+ nodePaths: [join(desktop, "node_modules"), join(root, "node_modules")],+ plugins: [{ name: "goal-layout-application-services", setup(api) {+ api.onResolve({ filter: /stores\/app-store$/ }, () => ({ path: join(root, "scripts/e2e/fixtures/goal-layout-store.ts") }));+ } }],+});+console.log(`Goal layout fixture bundled; artifacts: ${temp}`);+const electronBinary = process.env.PI_DESKTOP_ELECTRON_BIN ?? resolveElectronBinary(root).electronBinary;+assert(existsSync(electronBinary), `Electron binary missing: ${electronBinary}`);+await writeFile(join(temp, "index.html"), `<!doctype html><html lang="en" data-theme="dark"><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'none'">${styles.map((_, index) => `<link rel="stylesheet" href="built-${index}.css">`).join("")}<title>Goal layout regression</title></head><body><script src="renderer.js"></script></body></html>`);+await writeFile(join(temp, "main.cjs"), String.raw`+const { app, BrowserWindow } = require("electron");+const fs = require("node:fs");+const path = require("node:path");+app.setPath("userData", path.join(__dirname, "profile"));+app.setPath("sessionData", path.join(__dirname, "session"));+app.setPath("crashDumps", path.join(__dirname, "crashes"));+app.disableHardwareAcceleration();+app.commandLine.appendSwitch("disable-background-networking");+app.whenReady().then(async () => {+ const window = new BrowserWindow({ show: false, width: 1120, height: 1000,+ frame: false, useContentSize: true,+ webPreferences: { offscreen: true, backgroundThrottling: false, sandbox: true,+ contextIsolation: true, nodeIntegration: false, partition: "goal-layout-isolated" } });+ window.webContents.session.setPermissionRequestHandler((_contents, _permission, callback) => callback(false));+ window.webContents.session.webRequest.onBeforeRequest((details, callback) => callback({ cancel: !details.url.startsWith("file:") }));+ window.webContents.on("console-message", (event) => console.error(event.message));+ window.webContents.on("render-process-gone", (_event, details) => { console.error(JSON.stringify(details)); app.exit(2); });+ const cases = [];+ const call = (method, ...args) => window.webContents.executeJavaScript("globalThis.goalLayout." + method + "(" + args.map((value) => JSON.stringify(value)).join(",") + ")");+ async function click(key, action = true) {+ const point = await call("target", key);+ window.webContents.sendInputEvent({ type: "mouseMove", ...point });+ window.webContents.sendInputEvent({ type: "mouseDown", button: "left", clickCount: 1, ...point });+ window.webContents.sendInputEvent({ type: "mouseUp", button: "left", clickCount: 1, ...point });+ if (action) await call("after", key);+ }+ async function typeBudget(index, value) {+ await click("budget:" + index, false);+ await call("inputReady", index);+ const modifiers = process.platform === "darwin" ? ["meta"] : ["control"];+ window.webContents.sendInputEvent({ type: "keyDown", keyCode: "A", modifiers });+ window.webContents.sendInputEvent({ type: "keyUp", keyCode: "A", modifiers });+ await call("inputSelected", index);+ await window.webContents.insertText(String(value));+ await call("inputEdited", index, value);+ window.webContents.sendInputEvent({ type: "keyDown", keyCode: "Return" });+ window.webContents.sendInputEvent({ type: "keyUp", keyCode: "Return" });+ await call("inputSaved", index, value);+ }+ for (const language of ["en", "zh-CN"]) for (const width of [320, 480, 720, 1120]) {+ const entry = { language, width };+ try {+ window.setContentSize(width, 1000);+ await window.loadFile(path.join(__dirname, "index.html"));+ // Pin CSS pixels independently from Windows native frame rounding.+ window.webContents.enableDeviceEmulation({ screenPosition: "desktop", viewSize: { width, height: 1000 }, deviceScaleFactor: 1, scale: 1 });+ entry.mount = await call("mount", language);+ if (entry.mount.viewport[0] !== width) throw new Error("Wrong Chromium viewport: " + entry.mount.viewport[0]);+ fs.writeFileSync(path.join(__dirname, language + "-" + width + ".png"), (await window.webContents.capturePage()).toPNG());+ for (const key of ["resume", "pause", "edit", "cancelEdit", "stop", "cancel", "remove", "cancel"]) {+ await click(key);+ if (key === "edit") fs.writeFileSync(path.join(__dirname, language + "-" + width + "-objective.png"), (await window.webContents.capturePage()).toPNG());+ }+ await typeBudget(0, 37);+ await typeBudget(1, 123456);+ await call("clockStart");+ await click("pause");+ await call("frozen");+ await click("resume");+ Object.assign(entry, await call("cleanup"));+ } catch (error) {+ entry.error = String(error);+ fs.writeFileSync(path.join(__dirname, language + "-" + width + "-error.png"), (await window.webContents.capturePage()).toPNG());+ }+ cases.push(entry);+ }+ const result = { ok: cases.every((entry) => !entry.error && entry.failures.length === 0),+ versions: process.versions, cases };+ fs.writeFileSync(path.join(__dirname, "probe.json"), JSON.stringify(result, null, 2));+ console.log("GOAL_LAYOUT_RESULT " + JSON.stringify(result));+ window.destroy();+ app.exit(result.ok ? 0 : 1);+}).catch((error) => { console.error(error); app.exit(2); });+`);+const env = { ...process.env, TMP: scratch, TEMP: scratch, TMPDIR: scratch, PI_DESKTOP_MCP_CONTROL: "0" };+delete env.ELECTRON_RUN_AS_NODE;+delete env.ELECTRON_RENDERER_URL;+const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });+let output = "";+for (const stream of [child.stdout, child.stderr]) stream.on("data", (data) => { output += data; });+const timeout = setTimeout(() => child.kill("SIGKILL"), 90_000);+let code;+try {+ code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });+} finally {+ clearTimeout(timeout);+ await writeFile(join(temp, "electron.log"), output);+}+const line = output.split(/\r?\n/).find((value) => value.startsWith("GOAL_LAYOUT_RESULT "));+assert(line, `No Goal layout result (exit ${code}); artifacts: ${temp}\n${output.slice(-2500)}`);+const result = { ...JSON.parse(line.slice("GOAL_LAYOUT_RESULT ".length)), candidate, base, dirtyCandidate: true, electronBinary, cssEvidence, artifacts: temp };+await writeFile(join(temp, "result.json"), JSON.stringify(result, null, 2));+const failures = result.cases.flatMap((entry) => (entry.error ? [entry.error] : entry.failures).map((failure) => `${entry.language}/${entry.width}: ${failure}`));+console.log(JSON.stringify({ ok: result.ok, cases: result.cases.length, checks: result.cases.reduce((sum, entry) => sum + (entry.checks ?? 0), 0), failures, artifacts: temp }, null, 2));+assert.equal(result.ok, true, `Goal layout defects; see ${join(temp, "result.json")}`);+assert.equal(code, 0);diff --git a/scripts/e2e-goal-run-repairs.mjs b/scripts/e2e-goal-run-repairs.mjsnew file mode 100644index 000000000..eea4b1a06--- /dev/null+++ b/scripts/e2e-goal-run-repairs.mjs@@ -0,0 +1,132 @@+#!/usr/bin/env node+/** Goal acceptance through production Main admission and a real isolated Host. */+import assert from "node:assert/strict";+import { mkdir } from "node:fs/promises";+import { join } from "node:path";+import { register } from "node:module";+import { withScenario } from "./e2e/fixture.mjs";+import { resolveHostBinary } from "./e2e/host.mjs";+import { createSession } from "./e2e/session.mjs";++register(new URL("../apps/desktop/test/helpers/ts-import-hooks.mjs", import.meta.url));+const { createModeRunCoordinator } = await import("../apps/desktop/electron/main/runtime/mode-runs.ts");+const { createModeCatalogService } = await import("../apps/desktop/electron/main/runtime/mode-catalog.ts");+const { createSessionCoordination } = await import("../apps/desktop/electron/main/runtime/session-coordination.ts");+const { createPlanRuntime } = await import("../apps/desktop/electron/main/runtime/plans.ts");+const { createAgentHostBridge } = await import("../apps/desktop/electron/main/agent-host-bridge.ts");+const { registerAgentIpc } = await import("../apps/desktop/electron/main/ipc/agent-ipc.ts");+const { IPC } = await import("@pi-desktop/shared");+const scratch = process.env.PI_SCRATCH_DIR;+assert.ok(scratch, "PI_SCRATCH_DIR is required");+const temp = join(scratch, "goal-run-acceptance");+await mkdir(temp, { recursive: true });+await withScenario("goal-repairs", async ({ host, workspace, dataDir }) => {+ const session = await createSession(host, workspace, "Goal repairs");+ const sessionId = session.id;+ await host.call("session.configure", { id: sessionId, mode: "agent", permissionMode: "auto" });+ const settlements = [];+ const port = { async call(method, params) {+ const value = await host.call(method, params);+ if (method === "modes.settleTurn") settlements.push(value);+ return value;+ } };+ const handlers = new Map();+ const prompts = [];+ const promptWaiters = new Map();+ const waitForPrompt = count => prompts.length >= count ? Promise.resolve(prompts[count - 1]) :+ new Promise(resolve => promptWaiters.set(count, resolve));+ const activeTurns = new Map();+ const coordination = createSessionCoordination({ activeTurns, getMainWindow: () => null, getViewingSessionId: () => null });+ let bridge;+ let plans;+ const catalog = createModeCatalogService({ dir: join(dataDir, "modes") });+ const runs = createModeRunCoordinator({+ getHost: () => port, catalog, logger: { app() {} }, isQuitting: () => false,+ startContinuation: (...args) => bridge.startModeContinuation(...args),+ abortTurn: async id => {+ const turnId = activeTurns.get(id);+ assert.ok(turnId, "replacement must abort only the old active turn");+ await plans.finishTurn(id, "aborted", undefined, { turnId });+ },+ notifyTurn: async () => {},+ });+ bridge = createAgentHostBridge({+ channels: IPC.invoke, getHost: () => port, isSessionBusy: coordination.isSessionBusy,+ invoke: (channel, args) => handlers.get(channel)(...args), log() {},+ });+ plans = createPlanRuntime({+ runtimeState: { host: port, agentHostBridge: bridge }, planState: { approvedExecutionDrain: null },+ logger: { app() {} }, sendToRenderer() {}, coordination,+ scheduledRunsBySession: new Map(), activeToolCalls: new Map(), planSubmissionTurnIds: new Set(),+ approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(), approvedExecutionTurns: new Map(),+ startedApprovedExecutions: new Set(), finishedApprovedExecutions: new Set(), dispatchingApprovedExecutions: new Set(),+ inFlightExecutionFinishes: new Set(), pendingExecutionFinishes: new Map(), announceTurnEnded() {}, emitAgentEvent() {},+ acquireSessionOperation: coordination.acquireSessionOperation, isQuitting: () => false,+ onTurnEnded: (...args) => runs.settleTurn(...args),+ });+ registerAgentIpc({+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },+ modeRuns: runs, getHost: () => port, getAgentHostBridge: () => bridge,+ getSidecar: () => ({+ setProjectInstructionRoot() {},+ async call(method, params) {+ assert.equal(method, "agent.prompt");+ const message = { id: `answer-${prompts.length + 1}`, role: "assistant", content: "Synthetic answer", status: "complete", createdAt: new Date().toISOString() };+ await host.call("session.appendMessage", { sessionId, turnId: params.turnId, message });+ bridge.ingest({ sessionId, turnId: params.turnId, ts: Date.now(), event: { type: "agent_start" } });+ prompts.push(params);+ promptWaiters.get(prompts.length)?.(params);+ return { accepted: true, turnId: params.turnId };+ },+ }),+ logger: { app() {} }, persistenceOutbox: {}, dataDir, activeTurns, completionNoticeTurns: new Set(),+ activeTurnUsages: coordination.activeTurnUsages, approvedExecutionIdsBySession: new Map(), claimedExecutionSessions: new Map(),+ recordTurnStart: coordination.recordTurnStart, acquireSessionOperation: coordination.acquireSessionOperation,+ resolveAgentRuntimeLaunch: async () => {+ const current = (await host.call("session.get", { id: sessionId, messageLimit: 1 })).session;+ return { providerId: "fixture", modelId: "fixture", workspaceRoot: workspace,+ sidecarParams: { sessionId, mode: current.mode, provider: { modelConfig: { input: ["text"] } } } };+ },+ finishTurn: plans.finishTurn, emitAgentEvent() {}, setNotificationViewingSessionId() {},+ });+ const first = await handlers.get(IPC.invoke.agentPrompt)({ sessionId, content: "first objective", startGoal: true });+ assert.equal(first.accepted, true);+ const original = prompts[0].modeTurn.runId;+ assert.equal((await host.call("session.get", { id: sessionId, messageLimit: 1 })).session.mode, "agent");+ assert.equal((await runs.get(sessionId)).run.state, "running");+ coordination.activeTurnUsages.set(sessionId, { inputTokens: 3, outputTokens: 2 });+ const automatic = waitForPrompt(2);+ await plans.finishTurn(sessionId, "completed", undefined, { turnId: first.turnId });+ const continued = await automatic;+ assert.equal(continued.mode, "goal");+ assert.equal(continued.modeTurn.runId, original);+ assert.equal(continued.modeTurn.origin, "host");+ const decision = await host.call("permissions.evaluate", { sessionId, toolName: "Bash", args: { command: "echo goal-continuation" } });+ assert.equal(decision.decision, "allow-once", "second turn retains Auto after input reset");+ coordination.activeTurnUsages.set(sessionId, { inputTokens: 7, outputTokens: 1 });+ const replacement = await handlers.get(IPC.invoke.agentQueuePush)({ sessionId, content: "second objective", startGoal: true });+ assert.ok(replacement.id);+ const replaced = await waitForPrompt(3);+ const current = (await runs.get(sessionId)).run;+ assert.notEqual(current.id, original);+ assert.equal(current.id, replaced.modeTurn.runId);+ assert.equal(current.input, "second objective");+ assert.equal(current.roundsCompleted, 0);+ assert.equal(current.tokensUsed, 0);+ assert.equal(current.state, "running");+ const old = settlements.filter(value => value.run.id === original).at(-1);+ assert.equal(old.run.state, "stopped");+ assert.equal(old.run.roundsCompleted, 1);+ assert.equal(old.run.tokensUsed, 13);+ assert.equal(old.continue, false);+ const detail = (await host.call("session.get", { id: sessionId })).session;+ const answers = detail.messages.filter(message => message.role === "assistant");+ assert.equal(answers.length, 3);+ assert.equal(new Set(answers.map(message => message.turnId)).size, 3);+ assert.equal(detail.messages.filter(message => message.role === "user").length, 2, "autonomous turns create no synthetic user rows");+ assert.equal(detail.mode, "agent");+ assert.equal(bridge.queue.list(sessionId).length, 0);+ await runs.control({ sessionId, runId: current.id, expectedRevision: current.revision, action: "stop" });+ assert.equal((await runs.get(sessionId)).run, null);+ console.log("PASS Goal -> Agent input -> automatic Goal with Auto -> durable second Goal replacement -> separate transcript turns -> Stop");+}, resolveHostBinary(), temp);diff --git a/scripts/e2e/fixtures/goal-layout-store.ts b/scripts/e2e/fixtures/goal-layout-store.tsnew file mode 100644index 000000000..897dd549b--- /dev/null+++ b/scripts/e2e/fixtures/goal-layout-store.ts@@ -0,0 +1,9 @@+import { create } from "zustand";++/** Only unrelated application services are replaced; mode IPC/store wiring stays real. */+export const goalLayoutServices = { toasts: [] as string[], sessionRefreshes: 0 };++export const useAppStore = create(() => ({+ showToast: (message: string) => { goalLayoutServices.toasts.push(message); },+ refreshSessions: async () => { goalLayoutServices.sessionRefreshes += 1; },+}));diff --git a/scripts/e2e/goal-layout.tsx b/scripts/e2e/goal-layout.tsxnew file mode 100644index 000000000..b3cc09423--- /dev/null+++ b/scripts/e2e/goal-layout.tsx@@ -0,0 +1,309 @@+import { useState } from "react";+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { catalogs } from "@pi-desktop/i18n";+import { IPC, type AppSettings, type ModeControlRequest, type ModeRun } from "@pi-desktop/shared";+import { ModeRunStatusBar } from "../../apps/desktop/src/features/modes/ModeRunStatusBar";+import { GoalBudgetSettingsRow } from "../../apps/desktop/src/features/modes/GoalBudgetSettingsRow";+import { SettingsCard } from "../../apps/desktop/src/features/settings/primitives";+import { startModesSync } from "../../apps/desktop/src/features/modes/modes-sync";+import { goalLayoutServices } from "./fixtures/goal-layout-store";++const i18n = createInstance();+const failures: string[] = [];+const measurements: unknown[] = [];+let checks = 0;+const check = (value: unknown, message: string) => { checks += 1; if (!value) failures.push(message); };+const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+async function settle() { await frame(); await frame(); }+async function until(predicate: () => boolean, message: string) {+ for (let attempt = 0; attempt < 120; attempt += 1) { if (predicate()) return; await frame(); }+ throw new Error(message);+}+function element<T extends HTMLElement = HTMLElement>(selector: string): T {+ const found = document.querySelector<T>(selector);+ if (!found) throw new Error(`Missing ${selector}`);+ return found;+}+const box = (node: Element) => {+ const r = node.getBoundingClientRect();+ return { left: r.left, right: r.right, top: r.top, bottom: r.bottom, width: r.width, height: r.height };+};+const overlaps = (a: ReturnType<typeof box>, b: ReturnType<typeof box>) =>+ Math.min(a.right, b.right) - Math.max(a.left, b.left) > 0.5 && Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top) > 0.5;++// The only clock seam is the browser clock/timer boundary. React effects run normally.+let now = 1_800_000_000_000;+let nextTimer = 0;+let callbacks = 0;+const intervals = new Map<number, { next: number; delay: number; fire: () => void }>();+const realNow = Date.now;+const realSetInterval = window.setInterval;+const realClearInterval = window.clearInterval;+Date.now = () => now;+window.setInterval = (handler: TimerHandler, delay = 0, ...args: unknown[]) => {+ if (typeof handler !== "function" || delay <= 0) throw new Error("Unexpected fixture interval");+ const id = ++nextTimer;+ intervals.set(id, { next: now + delay, delay, fire: () => { callbacks += 1; handler(...args); } });+ return id;+};+window.clearInterval = (id?: number) => { if (id !== undefined) intervals.delete(id); };+async function advance(ms: number) {+ const target = now + ms;+ for (;;) {+ const due = [...intervals.values()].filter((timer) => timer.next <= target).sort((a, b) => a.next - b.next)[0];+ if (!due) break;+ now = due.next;+ due.next += due.delay;+ flushSync(due.fire);+ }+ now = target;+ await settle();+}++const objective = "Verify a very long Goal objective without hiding controls. ".repeat(70) + "目标验收条件".repeat(80) + "x".repeat(500);+const longElapsed = (1234 * 86_400 + 5 * 3600 + 6 * 60 + 7) * 1000;+let run: ModeRun = {+ id: "layout-run", sessionId: "layout-session", modeId: "goal", snapshotHash: "fixture",+ input: objective, stageId: "work", state: "paused", revision: 1,+ roundsCompleted: 2, tokensUsed: 0, maxTurns: 20, maxTokens: null, artifactPaths: {},+ elapsedMs: longElapsed, createdAt: "2000-01-01T00:00:00Z", updatedAt: "2000-01-01T00:00:00Z",+};+const listeners = new Map<string, Set<(...args: unknown[]) => void>>();+const requests: ModeControlRequest[] = [];+const saves: Partial<AppSettings>[] = [];+function emit() {+ for (const listener of listeners.get(IPC.event.modesChanged) ?? []) listener({ sessionId: run.sessionId, run });+}+function push(patch: Partial<ModeRun>) {+ run = { ...run, ...patch, revision: run.revision + 1 };+ flushSync(emit);+}+window.piDesktop = {+ channels: IPC, platform: "win32",+ on(channel, listener) {+ const set = listeners.get(channel) ?? new Set();+ set.add(listener); listeners.set(channel, set);+ return () => { set.delete(listener); };+ },+ async invoke<T>(channel: string, ...args: unknown[]) {+ let data: unknown;+ if (channel === IPC.invoke.modesCatalog) {+ data = { directory: "/isolated/modes", modes: [], diagnostics: [] };+ } else if (channel === IPC.invoke.modesRunGet) {+ if (args[0] !== run.sessionId) throw new Error("Unexpected session read");+ data = { run };+ } else if (channel === IPC.invoke.modesRunControl) {+ const request = args[0] as ModeControlRequest;+ if (request.runId !== run.id || request.sessionId !== run.sessionId || request.expectedRevision !== run.revision) {+ throw new Error("Control lost the displayed run identity/revision");+ }+ if (request.action !== "pause" && request.action !== "resume") throw new Error("Unexpected destructive control");+ requests.push(request);+ const elapsedMs = (run.elapsedMs ?? 0) + (run.state === "running" ? Math.max(0, now - (run.activeSinceMs ?? now)) : 0);+ run = { ...run, state: request.action === "pause" ? "paused" : "running", elapsedMs,+ activeSinceMs: request.action === "resume" ? now : undefined, revision: run.revision + 1 };+ data = { run, continue: false };+ } else {+ throw new Error(`Unexpected fixture IPC: ${channel}`);+ }+ return { ok: true as const, data: data as T };+ },+};+const host = document.createElement("div");+host.id = "root";+document.body.append(host);+const root = createRoot(host);+let disposeSync: (() => void) | undefined;+function Fixture() {+ const [settings, setSettings] = useState<AppSettings>({+ defaultMode: "goal", theme: "dark", enterToSend: true, onboardingDismissed: true,+ goalBudget: { maxTurns: 20, maxTokens: null },+ });+ return <main data-testid="goal-layout" style={{ width: "100%", height: "100%", padding: 8, overflow: "auto" }}>+ <ModeRunStatusBar sessionId={run.sessionId} />+ <div className="settings-content-inner" style={{ marginTop: 24 }}>+ <SettingsCard><GoalBudgetSettingsRow settings={settings} saveSettings={async (patch) => {+ saves.push(patch); setSettings((current) => ({ ...current, ...patch }));+ }} /></SettingsCard>+ </div>+ </main>;+}+function label(key: string) { return i18n.t(`modes.run.${key}`); }+function button(key: string): HTMLButtonElement {+ const scope = key === "cancelEdit" ? ".mode-run-edit" : ".mode-run-actions";+ const text = label(key === "cancelEdit" ? "cancel" : key);+ const found = [...document.querySelectorAll<HTMLButtonElement>(`${scope} button`)].find((item) => (item.getAttribute("aria-label") ?? item.textContent?.trim()) === text);+ if (!found) throw new Error(`Missing action ${key}: ${text}`);+ return found;+}+function target(node: HTMLElement) {+ node.scrollIntoView({ block: "nearest", inline: "nearest" });+ const r = node.getBoundingClientRect();+ const point = { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) };+ check(r.width > 0 && r.height > 0 && point.x >= 0 && point.x < innerWidth && point.y >= 0 && point.y < innerHeight, "Native input target outside viewport");+ check(node.contains(document.elementFromPoint(point.x, point.y)), "Native input target is covered");+ return point;+}+function bounded(node: HTMLElement, name: string) {+ const r = box(node);+ check(r.left >= -0.5 && r.right <= innerWidth + 0.5, `${name}: outside viewport ${JSON.stringify(r)}`);+ check(node.scrollWidth <= node.clientWidth + 1, `${name}: horizontal overflow ${node.scrollWidth}/${node.clientWidth}`);+}+function geometry(phase: string) {+ const bar = element(".mode-run-bar");+ const rounds = element(".mode-run-rounds");+ const elapsed = element(".mode-run-elapsed");+ const r = box(rounds), e = box(elapsed);+ check(getComputedStyle(bar).display === "flex", "Built production mode stylesheet missing");+ check(rounds.nextElementSibling === elapsed, `${phase}: elapsed is not the next metadata item`);+ check(Math.abs((r.top + r.bottom) / 2 - (e.top + e.bottom) / 2) <= 2 && e.left >= r.right - 0.5 && e.left - r.right <= 16,+ `${phase}: elapsed is not immediately right of rounds: ${JSON.stringify({ rounds: r, elapsed: e })}`);+ check(!/\{\{|modes\.run\./.test(elapsed.getAttribute("aria-label") ?? ""), `${phase}: unresolved elapsed accessible label: ${elapsed.getAttribute("aria-label")}`);+ check(Boolean(elapsed.getAttribute("aria-label")) && elapsed.title === elapsed.getAttribute("aria-label"), `${phase}: elapsed accessible title missing`);+ check(/^\d+ [dhms](?: \d+ [dhms])*$/.test(elapsed.textContent ?? ""), `${phase}: duration symbols/spacing are invalid`);+ bounded(bar, `${phase}/bar`);+ bounded(element(".mode-run-summary"), `${phase}/metadata`);+ bounded(element(".mode-run-actions"), `${phase}/actions`);+ const actions = [...document.querySelectorAll<HTMLButtonElement>(".mode-run-actions button")];+ for (const action of actions) {+ const name = action.getAttribute("aria-label") ?? action.textContent?.trim();+ check(Boolean(name) && action.tabIndex >= 0 && !action.disabled, `${phase}: action is not accessible`);+ if (["resume", "pause", "edit", "remove"].some((key) => label(key) === name)) {+ check(Boolean(action.querySelector('svg[aria-hidden="true"]')) && action.textContent?.trim() === "", `${phase}: ${name} is not icon-only`);+ }+ bounded(action, `${phase}/${name}`);+ check(!overlaps(e, box(action)) && !overlaps(r, box(action)), `${phase}: metadata overlaps ${name}`);+ target(action);+ }+ for (let i = 0; i < actions.length; i++) for (const other of actions.slice(i + 1)) {+ check(!overlaps(box(actions[i]), box(other)), `${phase}: actions overlap`);+ }+ if (phase === "paused") {+ check(elapsed.textContent === "1234 d 5 h 6 m 7 s", "Long duration lost units or exact spacing");+ }+ measurements.push({ phase, rounds: r, elapsed: e, actions: actions.map((item) => ({ name: item.getAttribute("aria-label") ?? item.textContent, ...box(item) })) });+}+function budgetGeometry() {+ const fields = [...document.querySelectorAll<HTMLElement>(".settings-goal-budget-field")];+ check(fields.length === 2, "Goal budget must expose two fields");+ const rects = fields.map(box);+ check(Math.abs(rects[0].top - rects[1].top) <= 1 && rects[1].left >= rects[0].right - 0.5, "Goal budget fields are not horizontal");+ bounded(element(".settings-goal-budget"), "Goal budget");+ bounded(element(".settings-row"), "Goal settings row");+ for (const field of fields) {+ const caption = field.querySelector<HTMLElement>(".settings-goal-budget-label");+ const input = field.querySelector<HTMLInputElement>("input");+ if (!caption || !input) throw new Error("Budget shared label/input missing");+ const c = box(caption), i = box(input);+ const range = document.createRange(); range.selectNodeContents(caption);+ const lineTops = [...range.getClientRects()].map((rect) => Math.round(rect.top));+ check(new Set(lineTops).size === 1 && caption.scrollWidth <= caption.clientWidth + 1, `Budget label wraps glyphs: ${caption.textContent}`);+ check(i.left >= c.right - 0.5 && Math.abs((i.top + i.bottom) / 2 - (c.top + c.bottom) / 2) <= 1, "Budget label/input is not horizontal");+ check(i.width >= 60 && input.classList.contains("field-input") && input.inputMode === "numeric", "Budget input is not usable/shared numeric control");+ bounded(field, "Budget field"); target(input);+ measurements.push({ phase: "budget", label: caption.textContent, caption: c, input: i, labelLines: lineTops });+ }+}+function elapsedText() { return element(".mode-run-elapsed").textContent; }+function seconds(value: number) { return `${value} s`; }++const probe = {+ async mount(language: "en" | "zh-CN") {+ await i18n.init({ lng: language, fallbackLng: "en", resources: {+ en: { translation: catalogs.en }, "zh-CN": { translation: catalogs["zh-CN"] },+ }, interpolation: { escapeValue: false } });+ document.documentElement.lang = language;+ document.documentElement.dataset.theme = "dark";+ disposeSync = startModesSync();+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><Fixture /></I18nextProvider>));+ await until(() => Boolean(document.querySelector(".mode-run-elapsed")), "Mode run did not load through IPC");+ await document.fonts.ready; await settle();+ geometry("paused"); budgetGeometry();+ check(intervals.size === 0, "Paused run owns a ticking interval");+ return { viewport: [innerWidth, innerHeight], objectiveLength: objective.length };+ },+ async target(key: string) {+ await settle();+ const node = key.startsWith("budget:")+ ? element<HTMLInputElement>(`.settings-goal-budget-field:nth-child(${Number(key.split(":")[1]) + 1}) input`)+ : button(key);+ return target(node);+ },+ async after(key: string) {+ if (key === "resume" || key === "pause") {+ await until(() => element(".mode-run-bar").dataset.state === (key === "resume" ? "running" : "paused") && element(".mode-run-bar").getAttribute("aria-busy") === "false", `${key} did not settle`);+ check(requests.at(-1)?.action === key, `${key} did not reach the preload boundary`);+ check(intervals.size === (key === "resume" ? 1 : 0), `${key}: active timer ownership wrong`);+ }+ await settle();+ if (key === "edit") {+ const input = element<HTMLTextAreaElement>(".mode-run-edit-objective textarea");+ check(input.value === objective, "Long objective changed in the edit form");+ bounded(input, "Long objective editor"); bounded(element(".mode-run-edit"), "Run edit form");+ geometry("edit");+ } else if (key === "stop" || key === "remove") {+ check(Boolean(document.querySelector(".mode-run-confirm[role='alert']")), `${key}: confirmation missing`);+ geometry(`${key}-confirmation`);+ } else if (key === "cancelEdit") {+ check(!document.querySelector(".mode-run-edit"), "Edit cancel did not close form");+ } else if (key === "cancel") {+ check(!document.querySelector(".mode-run-confirm"), "Confirmation cancel failed");+ }+ },+ async inputReady(index: number) {+ const input = element<HTMLInputElement>(`.settings-goal-budget-field:nth-child(${index + 1}) input`);+ await until(() => document.activeElement === input, `Budget ${index}: native click did not focus the input`);+ },+ async inputSelected(index: number) {+ const input = element<HTMLInputElement>(`.settings-goal-budget-field:nth-child(${index + 1}) input`);+ await until(() => input.selectionStart === 0 && input.selectionEnd === input.value.length, `Budget ${index}: select-all did not settle`);+ },+ async inputEdited(index: number, value: number) {+ const input = element<HTMLInputElement>(`.settings-goal-budget-field:nth-child(${index + 1}) input`);+ await until(() => input.value === String(value), `Budget ${index}: native text insertion did not settle`);+ await settle();+ check(input.value === String(value), `Budget ${index}: controlled render lost inserted text`);+ },+ async inputSaved(index: number, value: number) {+ await until(() => (index === 0 ? saves.at(-1)?.goalBudget?.maxTurns : saves.at(-1)?.goalBudget?.maxTokens) === value, "Budget native input/Enter did not save");+ await settle();+ const input = element<HTMLInputElement>(`.settings-goal-budget-field:nth-child(${index + 1}) input`);+ check(input.value === String(value) && document.activeElement === input, "Budget value/focus lost after save");+ check(input.labels?.length === 1 && Boolean(input.labels[0].textContent?.trim()), "Budget input has no accessible label");+ budgetGeometry();+ },+ async clockStart() {+ push({ state: "running", elapsedMs: 5000, activeSinceMs: now }); await settle();+ check(elapsedText() === seconds(5) && intervals.size === 1, "Active timer did not initialize");+ await advance(1000);+ check(elapsedText() === seconds(6), "Active timer did not tick with controlled clock");+ push({ elapsedMs: 20_000, activeSinceMs: now }); await settle();+ check(elapsedText() === seconds(20) && intervals.size === 1, "Revision did not recompute/re-own timer");+ await advance(1000);+ check(elapsedText() === seconds(21), "Revised timer did not tick");+ },+ async frozen() {+ const frozen = elapsedText(); await advance(5000);+ check(frozen === seconds(21) && elapsedText() === frozen && intervals.size === 0, "Paused timer kept counting");+ },+ async cleanup() {+ await advance(1000);+ check(elapsedText() === seconds(22), "Resumed timer lost accumulated time");+ push({ id: "legacy-run", state: "running", elapsedMs: undefined, activeSinceMs: undefined }); await settle();+ check(elapsedText() === seconds(0) && intervals.size === 0, "Legacy replacement inferred time or leaked timer");+ push({ id: "active-replacement", state: "running", elapsedMs: 3000, activeSinceMs: now }); await settle();+ check(elapsedText() === seconds(3) && intervals.size === 1, "Replacement run did not initialize its timer");+ flushSync(() => root.unmount()); disposeSync?.();+ check(intervals.size === 0, "Unmount leaked timer");+ const before = callbacks; await advance(5000);+ check(callbacks === before, "Timer fired after unmount");+ check([...listeners.values()].every((set) => set.size === 0), "Mode sync listeners survived disposal");+ check(goalLayoutServices.toasts.length === 0, `Unexpected errors: ${goalLayoutServices.toasts.join("; ")}`);+ Date.now = realNow; window.setInterval = realSetInterval; window.clearInterval = realClearInterval;+ return { checks, failures, measurements, requests, saves, timerCallbacks: callbacks };+ },+};+Object.assign(globalThis, { goalLayout: probe });