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(plan): preserve submitted contracts in chat history
xjx9d5da4b79eae
diff --git a/apps/desktop/src/features/chat/transcript/PlanHistoryCard.tsx b/apps/desktop/src/features/chat/transcript/PlanHistoryCard.tsxnew file mode 100644index 000000000..79d5c050d--- /dev/null+++ b/apps/desktop/src/features/chat/transcript/PlanHistoryCard.tsx@@ -0,0 +1,49 @@+import { useId } from "react";+import { useTranslation } from "react-i18next";+import type { PlanProposal, UiMessage } from "@pi-desktop/shared";+import { Badge, Button, Panel } from "../../../components/ui";+import { Markdown } from "../../../components/Markdown";+import { useAppStore } from "../../../stores/app-store";+import { preferredFileWorkPanelTab } from "../../../lib/work-panel-tabs";+import { useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";+import { disclosureKey, useAutomaticDisclosure } from "./disclosure";+import { useMessageRevealRequest } from "./shared";+import "../../../styles/plan-history.css";++/** Historical submissions are read-only; approval remains in PlanApprovalBar. */+export function PlanHistoryCard({ message, proposal, autoOpen = false, onUserInteraction }: {+ message: UiMessage; proposal: PlanProposal; autoOpen?: boolean; onUserInteraction?: () => void;+}) {+ const { t } = useTranslation();+ const bodyId = useId();+ const reveal = useMessageRevealRequest(message.id);+ const disclosure = useAutomaticDisclosure(autoOpen, reveal, disclosureKey("tool", message.id));+ const openTab = useAppStore(state => state.openWorkPanelTabForSession);+ const views = useAppStore(state => state.pluginViews);+ const sessionId = useSlotSessionId() || proposal.sessionId;+ const path = proposal.artifact?.relativePath;+ const status = message.planHistory?.proposal.status ?? "unknown";+ const statusKey = ["pending", "approved", "rejected", "expired", "interrupted"].includes(status) ? status : "unknown";+ const kind = proposal.kind === "goal" ? "goal" : "plan";+ return <Panel className="plan-history-card">+ <div className="plan-history-heading">+ <Button ref={disclosure.titleRef} variant="ghost" className="plan-history-title" aria-expanded={disclosure.open} aria-controls={bodyId}+ onClick={() => { onUserInteraction?.(); disclosure.toggle(); }}>+ <span aria-hidden="true">{disclosure.open ? "▾" : "▸"}</span>+ {proposal.title || t(`${kind}.untitled`)}+ </Button>+ <Badge tone={status === "approved" ? "success" : status === "pending" ? "warning" : "neutral"}>+ {t(`planHistory.${statusKey}`)}+ </Badge>+ {message.planHistory?.superseded && <Badge>{t("planHistory.superseded")}</Badge>}+ </div>+ {path && <Button variant="ghost" className="plan-history-artifact"+ aria-label={t(`${kind}.openArtifactLabel`, { path })}+ onClick={() => { onUserInteraction?.(); openTab(sessionId, preferredFileWorkPanelTab(path, views)); }}>+ {path}+ </Button>}+ {disclosure.open && <div id={bodyId} className="plan-history-body">+ <Markdown source={proposal.markdown} baseDir={path?.slice(0, path.lastIndexOf("/"))} />+ </div>}+ </Panel>;+}diff --git a/apps/desktop/src/features/chat/transcript/ToolRow.tsx b/apps/desktop/src/features/chat/transcript/ToolRow.tsxindex a61600453..f2fd8d17c 100644--- a/apps/desktop/src/features/chat/transcript/ToolRow.tsx+++ b/apps/desktop/src/features/chat/transcript/ToolRow.tsx@@ -1,3 +1,5 @@+import { PlanHistoryCard } from "./PlanHistoryCard";+import { planSubmission } from "../../../lib/plan-history";import { GeneratedImages } from "./GeneratedImages";import "../../../styles/generated-images.css";import {@@ -156,6 +158,10 @@ export const ToolRow = memo(function ToolRow(props: ToolRowProps) {"toolCard",variant === "default" && message.toolStatus !== "denied" ? message.toolName : undefined,);+ const proposal = planSubmission(message);+ if (proposal && variant === "default" && message.toolStatus !== "denied") {+ return <PlanHistoryCard message={message} proposal={proposal} autoOpen={props.autoOpen} onUserInteraction={props.onUserInteraction} />;+ }const hostRow = <HostToolRow {...props} />;return cardEntry ? (<PluginToolCard key={cardEntry.id} entry={cardEntry} message={message} fallback={hostRow} />diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex ddaf408bc..1cc3ef44e 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -1,3 +1,4 @@+import { projectPlanHistory } from "./plan-history";import type {ScheduledTaskRun,ActivationScope,@@ -338,6 +339,7 @@ function normalizeSessionDetail(detail: SessionDetail | null): SessionDetail | nreturn detail? {...detail,+ messages: projectPlanHistory(detail.messages, detail.planHistory ?? [], detail.id),mode: normalizeMode((detail as { mode?: unknown }).mode),}: null;diff --git a/apps/desktop/src/lib/plan-history.ts b/apps/desktop/src/lib/plan-history.tsnew file mode 100644index 000000000..54178344a--- /dev/null+++ b/apps/desktop/src/lib/plan-history.ts@@ -0,0 +1,50 @@+import type { PlanHistoryEntry, PlanProposal, UiMessage } from "@pi-desktop/shared";++/** Only host-owned submission tools carry contract snapshots. */+export function planSubmission(message: UiMessage): PlanProposal | undefined {+ if (message.role !== "tool" || !["SubmitPlan", "SubmitGoal"].includes(message.toolName ?? "")) return;+ if (message.planHistory) return message.planHistory.proposal;+ const result = message.toolResult as { details?: { proposal?: PlanProposal } } | undefined;+ const proposal = result?.details?.proposal;+ return proposal && proposal.toolCallId === message.toolCallId &&+ typeof proposal.id === "string" && typeof proposal.markdown === "string" &&+ typeof proposal.title === "string" ? proposal : undefined;+}++/** Stale reads/terminal tool echoes must not roll back a newer host revision. */+export function preservePlanHistory(message: UiMessage, previous?: UiMessage): UiMessage {+ const old = previous?.planHistory;+ const next = message.planHistory;+ if (!old || message.toolCallId !== previous?.toolCallId || message.toolName !== previous?.toolName) return message;+ if (next && next.proposal.id !== old.proposal.id) return message;+ const proposal = !next || old.proposal.version > next.proposal.version ||+ (old.proposal.version === next.proposal.version && old.proposal.updatedAt > next.proposal.updatedAt)+ ? old.proposal : next.proposal;+ const superseded = old.superseded || !!next?.superseded;+ if (next?.proposal === proposal && next.superseded === superseded) return message;+ return { ...message, planHistory: { proposal, superseded } };+}++export function projectPlanHistory(+ messages: UiMessage[], entries: readonly PlanHistoryEntry[], sessionId: string,+): UiMessage[] {+ if (!entries.length) return messages;+ const byCall = new Map(entries.filter(entry => entry.proposal.sessionId === sessionId)+ .map(entry => [entry.proposal.toolCallId, entry]));+ let changed = false;+ const next = messages.map(message => {+ if (message.role !== "tool" || !["SubmitPlan", "SubmitGoal"].includes(message.toolName ?? "")) return message;+ const entry = byCall.get(message.toolCallId ?? "");+ const current = message.planHistory;+ // A new submission supersedes only the same kind, never a Goal with a Plan.+ const superseded = current && entries.some(({ proposal }) =>+ proposal.sessionId === sessionId && proposal.kind === current.proposal.kind &&+ proposal.id !== current.proposal.id && proposal.createdAt >= current.proposal.createdAt);+ const projected = entry ? preservePlanHistory({ ...message, planHistory: entry }, message)+ : superseded && !current.superseded ? { ...message, planHistory: { ...current, superseded: true } }+ : message;+ if (projected !== message) changed = true;+ return projected;+ });+ return changed ? next : messages;+}diff --git a/apps/desktop/src/lib/session-transcript.ts b/apps/desktop/src/lib/session-transcript.tsindex 682c4f160..3f9754994 100644--- a/apps/desktop/src/lib/session-transcript.ts+++ b/apps/desktop/src/lib/session-transcript.ts@@ -1,3 +1,4 @@+import { preservePlanHistory } from "./plan-history";import type { AgentEvent, MessageAttachment, UiMessage } from "@pi-desktop/shared";import {getSessionMessageSnapshot,@@ -129,7 +130,7 @@ export function upsertLiveSessionMessage(if (index === undefined) return registerSessionMessageAppend(normalized, [...normalized, message]);if (normalized[index] === message) return normalized;const next = normalized.slice();- next[index] = message;+ next[index] = preservePlanHistory(message, normalized[index]);return registerSessionMessageReplacement(normalized, next, index);}@@ -274,7 +275,7 @@ export function mergeLiveSessionMessages(const liveIndex = liveIndexById.get(durableMessage.id);const live =liveIndex === undefined ? undefined : liveNormalized[liveIndex];- push(live && isInFlightMessage(live) ? live : durableMessage);+ push(preservePlanHistory(live && isInFlightMessage(live) ? live : durableMessage, live));// Live-only rows between two durable ids belong in the overlap. Trailing// rows after the last shared id wait until the durable page is complete// so a not-yet-cached user echo stays ahead of the streaming tail.diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.tsindex bcaecb7fe..e72bbfad5 100644--- a/apps/desktop/src/stores/slices/events-slice.ts+++ b/apps/desktop/src/stores/slices/events-slice.ts@@ -1,3 +1,4 @@+import { projectPlanHistory } from "../../lib/plan-history";import i18n from "i18next";import {dedupeSessionMessages,@@ -13,6 +14,7 @@ import {import type {AgentEventEnvelope,PlanningStateEvent,+ PlanProposal,SessionTodoSnapshot,UiMessage,} from "@pi-desktop/shared";@@ -122,6 +124,31 @@ export function createEventsSlice({}});+ // Only full host proposals certify approval. The live approval bar's+ // legacy state-only fallbacks must not become authoritative history.+ const historyCheckpoints = new Map<string, PlanProposal>();+ const projectCheckpointHistory = (sessionId: string, proposal?: PlanProposal) => {+ if (!proposal || proposal.sessionId !== sessionId) return;+ const previous = historyCheckpoints.get(sessionId);+ if (previous && (previous.id === proposal.id+ ? previous.version > proposal.version ||+ (previous.version === proposal.version && previous.updatedAt > proposal.updatedAt)+ : previous.createdAt > proposal.createdAt)) return;+ historyCheckpoints.set(sessionId, proposal);+ runtime.liveSessionTranscripts.add(sessionId);+ const project = (messages: UiMessage[]) => projectPlanHistory(+ messages, [{ proposal, superseded: false }], sessionId,+ );+ const cached = runtime.sessionTranscriptCache.get(sessionId);+ if (cached) runtime.cacheSessionTranscript(sessionId, project(cached));+ set(state => ({+ ...(state.activeSessionId === sessionId ? { messages: project(state.messages) } : {}),+ ...(state.retainedTranscripts[sessionId] ? { retainedTranscripts: {+ ...state.retainedTranscripts, [sessionId]: project(state.retainedTranscripts[sessionId]),+ } } : {}),+ }));+ };+return {applyTodosChanged: (snapshot: SessionTodoSnapshot) => {if (!isSessionTodoSnapshot(snapshot)) return;@@ -174,6 +201,7 @@ export function createEventsSlice({),};});+ projectCheckpointHistory(event.sessionId, event.proposal);const checkpoint = get().planCheckpoints[event.sessionId];if (event.state === "awaiting_approval" && isPendingPlan(checkpoint)) {openPlanArtifact(@@ -194,6 +222,17 @@ export function createEventsSlice({},handleAgentEvent: (envelope) => {+ if (envelope.event.type === "message_end") {+ const checkpoint = historyCheckpoints.get(envelope.sessionId);+ if (checkpoint) {+ const [message] = projectPlanHistory(+ [envelope.event.message],+ [{ proposal: checkpoint, superseded: false }],+ envelope.sessionId,+ );+ envelope = { ...envelope, event: { ...envelope.event, message } };+ }+ }const event = envelope.event;if (event.type === "agent_end" || event.type === "error") {runtime.submittedComposerDrafts.delete(envelope.sessionId);@@ -371,6 +410,7 @@ export function createEventsSlice({: withoutRecordKey(state.pendingPlans, envelope.sessionId),};});+ projectCheckpointHistory(envelope.sessionId, event.proposal);if (event.state === "awaiting_approval") {const checkpoint = get().planCheckpoints[envelope.sessionId];if (isPendingPlan(checkpoint)) {diff --git a/apps/desktop/src/styles/plan-history.css b/apps/desktop/src/styles/plan-history.cssnew file mode 100644index 000000000..72176271b--- /dev/null+++ b/apps/desktop/src/styles/plan-history.css@@ -0,0 +1,31 @@+.plan-history-card {+ margin-block: 8px;+ padding: 12px;+ min-width: 0;+}+.plan-history-heading {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 8px;+}+.plan-history-title {+ min-width: 0;+ text-align: start;+ white-space: normal;+ overflow-wrap: anywhere;+}+.plan-history-artifact {+ max-width: 100%;+ justify-content: flex-start;+ text-align: start;+ white-space: normal;+ overflow-wrap: anywhere;+ font-size: var(--text-xs);+ color: var(--ds-text-secondary);+}+.plan-history-body {+ margin-top: 12px;+ min-width: 0;+ overflow-wrap: anywhere;+}diff --git a/apps/desktop/test/plan-history.test.mjs b/apps/desktop/test/plan-history.test.mjsnew file mode 100644index 000000000..4caf692bb--- /dev/null+++ b/apps/desktop/test/plan-history.test.mjs@@ -0,0 +1,46 @@+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { projectPlanHistory, planSubmission } = await import("../src/lib/plan-history.ts");+const { upsertLiveSessionMessage, mergeLiveSessionMessages } = await import("../src/lib/session-transcript.ts");+const proposal = (overrides = {}) => ({ id: "p1", sessionId: "s1", toolCallId: "c1", kind: "plan", title: "API plan", markdown: "# Exact\n- text \n", status: "pending", version: 1, createdAt: "2026-10-04T00:00:00.000Z", updatedAt: "2026-10-04T00:00:00.000Z", ...overrides });+const row = (p = proposal()) => ({ id: "tool-" + p.toolCallId, role: "tool", content: "submitted", toolName: p.kind === "goal" ? "SubmitGoal" : "SubmitPlan", toolCallId: p.toolCallId, toolResult: { details: { proposal: p } } });++test("authoritative approvals override immutable pending snapshots and stale echoes", () => {+ const pending = row();+ const approved = proposal({ status: "approved", version: 2 });+ const history = projectPlanHistory([pending], [{ proposal: approved, superseded: false }], "s1");+ assert.equal(planSubmission(history[0]).status, "approved");+ assert.equal(pending.toolResult.details.proposal.status, "pending");+ assert.equal(upsertLiveSessionMessage(history, pending)[0].planHistory.proposal.status, "approved");+ assert.equal(mergeLiveSessionMessages([pending], history)[0].planHistory.proposal.status, "approved");+ const stale = projectPlanHistory([pending], [{ proposal: proposal(), superseded: false }], "s1");+ assert.equal(mergeLiveSessionMessages(stale, history)[0].planHistory.proposal.version, 2);+});++test("new revisions supersede old submissions without losing approved state or affecting Goal", () => {+ const first = proposal({ status: "approved", version: 2 });+ const goal = proposal({ id: "g1", toolCallId: "gc1", kind: "goal" });+ const messages = projectPlanHistory([row(first), row(goal)], [{ proposal: first, superseded: false }, { proposal: goal, superseded: false }], "s1");+ const second = proposal({ id: "p2", toolCallId: "c2", createdAt: "2026-10-04T00:01:00.000Z" });+ const next = projectPlanHistory(messages, [{ proposal: second, superseded: false }], "s1");+ assert.equal(next[0].planHistory.superseded, true);+ assert.equal(next[0].planHistory.proposal.status, "approved");+ assert.equal(next[0].planHistory.proposal.markdown, first.markdown);+ assert.equal(next[1].planHistory.superseded, false);+ assert.equal(projectPlanHistory(next, [{ proposal: first, superseded: false }], "s1")[0].planHistory.superseded, true);+});++test("history is scoped by session, exact call and host tool; snapshot fallback does not invent current state", () => {+ const messages = [row(), { ...row(), toolName: "plugin:SubmitPlan" }, { ...row(), toolCallId: "other" }];+ assert.strictEqual(projectPlanHistory(messages, [{ proposal: proposal({ sessionId: "other" }), superseded: false }], "s1"), messages);+ const next = projectPlanHistory(messages, [{ proposal: proposal({ status: "rejected" }), superseded: false }], "s1");+ assert.equal(next[0].planHistory.proposal.status, "rejected");+ assert.equal(next[1].planHistory, undefined);+ assert.equal(next[2].planHistory, undefined);+ assert.equal(planSubmission(messages[1]), undefined);+ assert.equal(planSubmission(messages[2]), undefined);+ assert.equal(planSubmission(messages[0]).markdown, proposal().markdown);+ assert.equal(messages[0].planHistory, undefined);+});diff --git a/apps/desktop/test/session-collaboration-ipc.test.mjs b/apps/desktop/test/session-collaboration-ipc.test.mjsindex 9308aa8d9..eeb9fd7d8 100644--- a/apps/desktop/test/session-collaboration-ipc.test.mjs+++ b/apps/desktop/test/session-collaboration-ipc.test.mjs@@ -86,7 +86,10 @@ function rendererApi(invoke) {"@pi-desktop/shared": shared,"@pi-desktop/shared/protocol": shared,});- const { api } = load("../src/lib/api.ts", { "@pi-desktop/shared": shared }, {+ const { api } = load("../src/lib/api.ts", {+ "@pi-desktop/shared": shared,+ "./plan-history": load("../src/lib/plan-history.ts", {}),+ }, {window: { piDesktop: bridge },});return { api, bridge };diff --git a/crates/host-core/src/plans.rs b/crates/host-core/src/plans.rsindex 73efa2dcf..38b76eaef 100644--- a/crates/host-core/src/plans.rs+++ b/crates/host-core/src/plans.rs@@ -24,8 +24,8 @@ mod repository;pub use approval::{expire_pending_approvals, gate_session_configure};pub use model::{- kind_for_mode, normalize_kind, PlanArtifact, PlanExecution, PlanManager, PlanProposal,- PlanResolution, PlanResolveParams, PlanSubmitParams, EXECUTION_COMPLETED,+ kind_for_mode, normalize_kind, PlanArtifact, PlanExecution, PlanHistoryEntry, PlanManager,+ PlanProposal, PlanResolution, PlanResolveParams, PlanSubmitParams, EXECUTION_COMPLETED,EXECUTION_INTERRUPTED, EXECUTION_QUEUED, EXECUTION_RUNNING, KIND_GOAL, KIND_PLAN,PLAN_MAX_MARKDOWN_BYTES, STATUS_APPROVED, STATUS_EXPIRED, STATUS_INTERRUPTED, STATUS_PENDING,STATUS_REJECTED,@@ -37,8 +37,8 @@ pub(crate) use artifact::{};pub(crate) use execution::{execution_from_proposal, resolution_from_proposal};pub(crate) use repository::{- get_proposal, live_turn_belongs_to_session, proposal_from_row, session_submit_kind,- PROPOSAL_COLUMNS,+ get_proposal, history_for_tool_calls, live_turn_belongs_to_session, proposal_from_row,+ session_submit_kind, PROPOSAL_COLUMNS,};#[cfg(test)]diff --git a/crates/host-core/src/plans/history_tests.rs b/crates/host-core/src/plans/history_tests.rsnew file mode 100644index 000000000..a533360a6--- /dev/null+++ b/crates/host-core/src/plans/history_tests.rs@@ -0,0 +1,152 @@+use super::*;++#[test]+fn plan_history_returns_authoritative_approved_snapshot_without_rewriting_transcript() {+ let (dir, db) = test_db();+ let root = dir.path().join("workspace");+ fs::create_dir_all(&root).unwrap();+ let proposal = submit(&PlanManager, &db, &root, "submit-history");+ let message: sessions::UiMessage = serde_json::from_value(json!({+ "id": "plan-tool", "role": "tool", "content": "Plan submitted",+ "createdAt": proposal.created_at, "toolName": "SubmitPlan",+ "toolCallId": proposal.tool_call_id, "toolStatus": "success",+ "toolResult": { "details": { "proposal": proposal } }+ }))+ .unwrap();+ sessions::append_message(&db, &proposal.session_id, &message, Some(&proposal.turn_id)).unwrap();+ let transcript =+ crate::transcripts::transcript_path(db.data_dir(), &proposal.session_id).unwrap();+ let before = fs::read(&transcript).unwrap();+ PlanManager+ .resolve(+ &db,+ PlanResolveParams {+ workspace_root: Some(&root),+ proposal_id: &proposal.id,+ session_id: &proposal.session_id,+ turn_id: &proposal.turn_id,+ tool_call_id: &proposal.tool_call_id,+ version: Some(proposal.version),+ action: "approve",+ target_permission_mode: Some("ask"),+ },+ )+ .unwrap();+ fs::remove_file(root.join(&proposal.artifact.as_ref().unwrap().relative_path)).unwrap();+ let detail = sessions::get_session_with_options(+ &db,+ &proposal.session_id,+ sessions::SessionReadOptions {+ content_limit: Some(16),+ ..Default::default()+ },+ )+ .unwrap()+ .unwrap();+ let view = serde_json::to_value(detail).unwrap();+ assert_eq!(view["planHistory"][0]["proposal"]["status"], "approved");+ assert_eq!(+ view["planHistory"][0]["proposal"]["markdown"],+ proposal.markdown+ );+ assert_eq!(+ view["planHistory"][0]["proposal"]["artifact"],+ serde_json::to_value(proposal.artifact).unwrap()+ );+ assert_eq!(view["planHistory"][0]["superseded"], false);+ assert_eq!(+ fs::read(transcript).unwrap(),+ before,+ "history projection must not rewrite model evidence"+ );+}++#[test]+fn plan_history_is_page_scoped_survives_reopen_and_retains_superseded_versions() {+ let (dir, db) = test_db();+ let root = dir.path().join("workspace");+ fs::create_dir_all(&root).unwrap();+ let first = submit(&PlanManager, &db, &root, "version-one");+ let append = |proposal: &PlanProposal| {+ let message = serde_json::from_value(json!({+ "id": proposal.tool_call_id, "role": "tool", "content": "submitted",+ "createdAt": proposal.created_at, "toolName": "SubmitPlan",+ "toolCallId": proposal.tool_call_id, "toolResult": { "details": { "proposal": proposal } }+ })).unwrap();+ sessions::append_message(&db, &proposal.session_id, &message, Some(&proposal.turn_id))+ .unwrap();+ };+ append(&first);+ PlanManager+ .resolve(+ &db,+ PlanResolveParams {+ workspace_root: Some(&root),+ proposal_id: &first.id,+ session_id: &first.session_id,+ turn_id: &first.turn_id,+ tool_call_id: &first.tool_call_id,+ version: Some(first.version),+ action: "reject",+ target_permission_mode: None,+ },+ )+ .unwrap();+ sessions::end_turn(&db, &first.turn_id, "completed", None, None, false).unwrap();+ let turn = live_turn(&db, &first.session_id);+ let second = PlanManager+ .submit(+ &db,+ PlanSubmitParams {+ workspace_root: &root,+ session_id: &first.session_id,+ turn_id: &turn,+ tool_call_id: "version-two",+ kind: KIND_PLAN,+ title: "Revised API",+ markdown: "# Revised\n- preserve this version",+ question: "Proceed?",+ },+ )+ .unwrap();+ append(&second);+ assert!(+ history_for_tool_calls(&db, "another-session", &["version-one"])+ .unwrap()+ .is_empty()+ );+ assert!(history_for_tool_calls(&db, &first.session_id, &[])+ .unwrap()+ .is_empty());+ drop(db);+ let reopened = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let latest = sessions::get_session_with_options(+ &reopened,+ &first.session_id,+ sessions::SessionReadOptions {+ message_limit: Some(1),+ content_limit: Some(16),+ ..Default::default()+ },+ )+ .unwrap()+ .unwrap();+ assert_eq!(latest.plan_history.len(), 1);+ assert_eq!(latest.plan_history[0].proposal.id, second.id);+ assert!(!latest.plan_history[0].superseded);+ let older = sessions::get_session_with_options(+ &reopened,+ &first.session_id,+ sessions::SessionReadOptions {+ message_limit: Some(1),+ message_before: latest.message_start,+ ..Default::default()+ },+ )+ .unwrap()+ .unwrap();+ assert_eq!(older.plan_history.len(), 1);+ assert_eq!(older.plan_history[0].proposal.status, STATUS_REJECTED);+ assert_eq!(older.plan_history[0].proposal.markdown, first.markdown);+ assert!(older.plan_history[0].superseded);+}diff --git a/crates/host-core/src/plans/model.rs b/crates/host-core/src/plans/model.rsindex 85124eacb..672d5e31e 100644--- a/crates/host-core/src/plans/model.rs+++ b/crates/host-core/src/plans/model.rs@@ -128,3 +128,11 @@ pub struct PlanResolveParams<'a> {pub action: &'a str,pub target_permission_mode: Option<&'a str>,}++/// Authoritative display metadata for one immutable submission in a history page.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PlanHistoryEntry {+ pub proposal: PlanProposal,+ pub superseded: bool,+}diff --git a/crates/host-core/src/plans/repository.rs b/crates/host-core/src/plans/repository.rsindex f9674abab..0669efe38 100644--- a/crates/host-core/src/plans/repository.rs+++ b/crates/host-core/src/plans/repository.rs@@ -85,3 +85,34 @@ pub(crate) fn live_turn_belongs_to_session(|row| row.get(0),)?)}++/// Return only submissions represented in this page. The transcript is immutable;+/// approval/execution state belongs to SQLite and must never come from tool output.+pub(crate) fn history_for_tool_calls(+ db: &Database,+ session_id: &str,+ tool_call_ids: &[&str],+) -> Result<Vec<PlanHistoryEntry>> {+ if tool_call_ids.is_empty() {+ return Ok(Vec::new());+ }+ let sql = format!(+ "SELECT {PROPOSAL_COLUMNS}, EXISTS(+ SELECT 1 FROM plan_approvals newer+ WHERE newer.session_id = history.session_id+ AND COALESCE(newer.kind, 'plan') = COALESCE(history.kind, 'plan')+ AND newer.rowid > history.rowid+ ) FROM plan_approvals history+ WHERE session_id = ?1 AND tool_call_id IN (SELECT value FROM json_each(?2))+ ORDER BY rowid"+ );+ let ids = serde_json::to_string(tool_call_ids)?;+ let mut statement = db.conn().prepare_cached(&sql)?;+ let entries = statement.query_map(params![session_id, ids], |row| {+ Ok(PlanHistoryEntry {+ proposal: proposal_from_row(row)?,+ superseded: row.get(23)?,+ })+ })?;+ Ok(entries.collect::<rusqlite::Result<Vec<_>>>()?)+}diff --git a/crates/host-core/src/plans/tests.rs b/crates/host-core/src/plans/tests.rsindex c11f7d503..23b34e13d 100644--- a/crates/host-core/src/plans/tests.rs+++ b/crates/host-core/src/plans/tests.rs@@ -886,3 +886,6 @@ fn entering_goal_mode_writes_the_goal_mode_and_kind() {"PLAN_INVALID_ARGUMENT");}++#[path = "history_tests.rs"]+mod history;diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex b86166114..8cc084a6a 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -262,6 +262,8 @@ pub struct SessionDetail {#[serde(flatten)]pub summary: SessionSummary,pub messages: Vec<UiMessage>,+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub plan_history: Vec<crate::plans::PlanHistoryEntry>,/// Owning Task for a nested messageAround target, outside the page cursors.#[serde(skip_serializing_if = "Option::is_none")]pub navigation_parent: Option<UiMessage>,@@ -1563,6 +1565,17 @@ pub fn get_session_with_options(.collect(),None => records.into_iter().map(record_to_ui).collect(),};+ let plan_calls: Vec<&str> = messages+ .iter()+ .filter(|message| {+ matches!(+ message.tool_name.as_deref(),+ Some("SubmitPlan" | "SubmitGoal")+ )+ })+ .filter_map(|message| message.tool_call_id.as_deref())+ .collect();+ let plan_history = crate::plans::history_for_tool_calls(db, id, &plan_calls)?;let parent_call_id = options.message_around.as_deref().and_then(|target| {messages.iter()@@ -1582,6 +1595,7 @@ pub fn get_session_with_options(};Ok(Some(SessionDetail {summary,+ plan_history,navigation_parent,message_start,message_end,@@ -1771,6 +1785,7 @@ pub fn fork_session_through(let messages = records.into_iter().map(record_to_ui).collect();Ok(ForkSessionResult::Created(Box::new(SessionDetail {summary,+ plan_history: Vec::new(),navigation_parent: None,message_start: None,message_end: None,diff --git a/docs/adr/0053-plan-checkpoint-artifact-and-execution-epoch.md b/docs/adr/0053-plan-checkpoint-artifact-and-execution-epoch.mdindex 80b9165df..470b7c7ef 100644--- a/docs/adr/0053-plan-checkpoint-artifact-and-execution-epoch.md+++ b/docs/adr/0053-plan-checkpoint-artifact-and-execution-epoch.md@@ -78,6 +78,17 @@ Renderer reload preserves the original deadline while the host remains alive.Expiry is recorded with the canonical error `PLAN_APPROVAL_TIMEOUT`; thedeadline never extends when the card is reopened.+### Historical display amendment (issue #933)++The live approval card remains unchanged. Completed submission rows additionally+render read-only historical cards. `session.get` joins only returned submission+call IDs to the existing approval table, preserving complete Markdown and the+current host status without rewriting the original tool result. Same-kind newer+rows mark older submissions superseded, independently of approval status.+This is an additive read projection with no schema migration or execution grant.+Old/native hosts and forks lacking approvals may display the immutable snapshot,+but its captured `pending` result is not authoritative current approval state.+### 4. Process-epoch fence and recoveryThe host process has an internal boot epoch, but it is not serialized in thediff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 98d7aa37f..7a391ed54 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -959,6 +959,8 @@ type ToolTokenUsage = {type SessionDetail = SessionSummary & {messages: UiMessage[];+ /** Authoritative metadata for SubmitPlan/SubmitGoal calls in this page. */+ planHistory?: Array<{ proposal: PlanProposal; superseded: boolean }>;/** Zero-based start offset when the renderer received a bounded page. */messageStart?: number;/** True when an older page can be requested with session.get. */@@ -966,6 +968,17 @@ type SessionDetail = SessionSummary & {};```+Historical contract reads attach `planHistory` only for submission call IDs in+that session's returned page. SQLite supplies the current approval status,+exact Markdown snapshot, artifact path, and same-kind supersession; original+JSONL tool results stay immutable. Display content caps do not truncate these+bounded contract snapshots (submission already enforces the Markdown limit).+This additive field is optional for older/native hosts and empty forks: no+approval record is copied or inferred from tool output or artifact filenames.+The renderer may attach it to `UiMessage.planHistory` as display-only metadata;+it must never persist that projection as model evidence.++`messageCount` is the host-authoritative count of messages in the currentcanonical transcript. The renderer uses it to distinguish an empty durablesession from a session whose title still looks untitled; title text is not adiff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex cd596d524..871c2656e 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -689,6 +689,17 @@ once with a new complete Markdown snapshot to create a new artifact. If approvalalready committed and a queued/running execution is interrupted, durable moderemains Agent and the execution is not replayed.++Historical SubmitPlan/SubmitGoal rows render read-only contract cards with an+expandable exact Markdown snapshot, authoritative approval status, an artifact+opener, and a superseded badge when a later submission of the same kind exists.+The live approval bar remains the only approval surface. Host history metadata+and planning events reconcile by proposal identity/revision, so delayed pending+tool echoes cannot undo approval. Plans remain readable after continued chat,+compaction, session reselection, and host restart; deleting an artifact does not+remove the stored Markdown. Hosts without approval metadata show snapshot text+with unavailable status rather than presenting a stale pending result as truth.+Manual mode and configuration selection may be staged by the renderer while aturn runs, but host persistence remains idle-only. Selecting Agent is anintentional user override and does not synthesize a plan or approval. Eachdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 39d2062d4..2447a0590 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -16648,3 +16648,25 @@ registry-only installation and credential isolation.- **Status**: Automated headless runtime/provider integration via`node scripts/e2e-subagent-parent-error.mjs`; no real accounts or Desktop data.Runtime tests separately cover exhausted parent 429 and Stop racing settlement.+++#### E2E-PLAN-HISTORY: Immutable submissions retain current status in chat++Run `node scripts/e2e-plan-history.mjs` against the committed candidate host.+Use an isolated Electron profile/workspace and the production session IPC,+preload, API normalization, store events, ToolRow, and Markdown renderer.++1. Submit Plan and read a capped history page: expand the full Markdown and+ open its exact artifact path in the owning session's work panel.+2. Approve and deliver a stale pending tool echo: history still says approved.+ Cover approval-before-message and inactive retained-session events.+3. Complete execution, submit/reject a revision, and read both newest/older+ pages: retain both exact bodies and statuses, mark only the older Plan+ superseded, and leave unrelated sessions/Goal untouched.+4. Submit/reject Goal and check localized Chinese status.+5. Continue chat, append a compaction checkpoint, restart host and renderer:+ both versions remain readable; no historical card has approval controls.++No provider credentials or paid model calls are required. The fixture ends at+work-panel file-request routing; artifact bytes are verified from the real+host-created files. The full app's file-preview viewer is covered separately.diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex c5682c4a1..deb892cfc 100644--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@ -811,9 +811,18 @@ type ToolTokenUsage = {type SessionDetail = SessionSummary & {messages: UiMessage[];+ /** Authoritative metadata for SubmitPlan/SubmitGoal calls in this page. */+ planHistory?: Array<{ proposal: PlanProposal; superseded: boolean }>;};```+历史读取仅为当前会话返回页中的 SubmitPlan/SubmitGoal 调用附加 `planHistory`。+SQLite 提供真实审批状态、完整 Markdown 快照、文件路径及同类型的新版本替代标记,+原始 JSONL 工具结果保持不变。显示截断不影响这些有提交大小限制的计划快照。+该字段兼容旧主机和原生会话;分叉会话不复制审批记录,也不从工具结果或文件名推断状态。+渲染器可将其投影到 `UiMessage.planHistory`,但不得将显示元数据写回模型证据。++Electron 主进程用该会话精确 provider/API URL 与 model 的本地 models.dev记录,丰富 session list/get/create/fork/configure 结果中的有效推理能力。未固定 `providerId`/`modelId` 的会话仅在此丰富步骤继承应用默认供应商/模型。diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 91e214f9f..606dd218c 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -510,6 +510,12 @@ Plan 和 Goal 是两种 **合约模式** (D198)。他们共用一个耐用的已提交且 queued/running 执行被中断,持久模式仍然是 Agent 并且不会重播执行。+历史 SubmitPlan/SubmitGoal 显示只读卡片:可展开完整 Markdown、查看真实审批状态、打开+计划文件;同类型后续提交出现后,旧版本标记为已被替代。审批操作仍只在实时审批栏中。+历史元数据与规划事件按提案身份及版本合并,迟到的 pending 工具回显不能覆盖审批结果。+继续聊天、上下文压缩、切换会话及重启后仍可阅读;文件被删除也不影响数据库中的正文。+缺少审批元数据的旧主机仅显示快照并标注状态不可用,不把旧 pending 当作当前状态。+手动模式和配置选择可以由渲染器上演,同时轮运行,但主机持久性仅保持空闲状态。选择 Agent 是故意的用户覆盖并且不综合计划或批准。每个diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex cdd21fc08..0a3e3eef4 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -9388,3 +9388,25 @@ the latest destination. These assertions measure work counts, not device FPS.- **状态**:通过 `node scripts/e2e-subagent-parent-error.mjs` 自动验证无头运行时与provider 集成;不使用真实账户或桌面数据。运行时测试另行覆盖父级 429 耗尽与Stop 和结算之间的竞态。+++#### E2E-PLAN-HISTORY: Immutable submissions retain current status in chat++Run `node scripts/e2e-plan-history.mjs` against the committed candidate host.+Use an isolated Electron profile/workspace and the production session IPC,+preload, API normalization, store events, ToolRow, and Markdown renderer.++1. Submit Plan and read a capped history page: expand the full Markdown and+ open its exact artifact path in the owning session's work panel.+2. Approve and deliver a stale pending tool echo: history still says approved.+ Cover approval-before-message and inactive retained-session events.+3. Complete execution, submit/reject a revision, and read both newest/older+ pages: retain both exact bodies and statuses, mark only the older Plan+ superseded, and leave unrelated sessions/Goal untouched.+4. Submit/reject Goal and check localized Chinese status.+5. Continue chat, append a compaction checkpoint, restart host and renderer:+ both versions remain readable; no historical card has approval controls.++No provider credentials or paid model calls are required. The fixture ends at+work-panel file-request routing; artifact bytes are verified from the real+host-created files. The full app's file-preview viewer is covered separately.diff --git a/package.json b/package.jsonindex e7a107fa6..fa2fb700c 100644--- a/package.json+++ b/package.json@@ -28,6 +28,7 @@"test:e2e:live-voice": "node scripts/e2e-live-voice.mjs","test:e2e:rpc-unicode": "node scripts/e2e-rpc-unicode.mjs","test:e2e:plan": "node scripts/e2e-plan.mjs",+ "test:e2e:plan-history": "node scripts/e2e-plan-history.mjs","test:e2e:plan-ui": "node scripts/e2e-plan-ui.mjs","test:e2e:theme-surfaces": "node scripts/e2e-theme-surfaces.mjs","test:e2e:composer-occlusion": "node scripts/e2e-theme-surfaces.mjs --dock-mask-only",diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex be8541350..4a70b14f5 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -566,6 +566,15 @@ export const de = {"renameSave": "Speichern","renameSaving": "Speichern…"},+ planHistory: {+ pending: "Genehmigung ausstehend",+ approved: "Genehmigt",+ rejected: "Abgelehnt",+ expired: "Abgelaufen",+ interrupted: "Unterbrochen",+ unknown: "Status nicht verfügbar",+ superseded: "Ersetzt",+ },"plan": {"planning": "Planung","approvalRegion": "Plangenehmigung",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 200bec80c..fd8cafe39 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -578,6 +578,15 @@ export const en = {renameSave: "Save",renameSaving: "Saving…",},+ planHistory: {+ pending: "Awaiting approval",+ approved: "Approved",+ rejected: "Rejected",+ expired: "Expired",+ interrupted: "Interrupted",+ unknown: "Status unavailable",+ superseded: "Superseded",+ },plan: {planning: "Planning",approvalRegion: "Plan approval",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 539e21c15..a04226cdb 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -566,6 +566,15 @@ export const es = {"renameSave": "Guardar","renameSaving": "Guardando…"},+ planHistory: {+ pending: "Pendiente de aprobación",+ approved: "Aprobado",+ rejected: "Rechazado",+ expired: "Caducado",+ interrupted: "Interrumpido",+ unknown: "Estado no disponible",+ superseded: "Sustituido",+ },"plan": {"planning": "Planificación","approvalRegion": "Aprobación del plan",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 31692ef38..ae35a093a 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -566,6 +566,15 @@ export const fr = {"renameSave": "Enregistrer","renameSaving": "Enregistrer…"},+ planHistory: {+ pending: "En attente d’approbation",+ approved: "Approuvé",+ rejected: "Rejeté",+ expired: "Expiré",+ interrupted: "Interrompu",+ unknown: "État indisponible",+ superseded: "Remplacé",+ },"plan": {"planning": "Planification","approvalRegion": "Approbation du plan",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 82cc1011e..2520593d2 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -575,6 +575,15 @@ export const ko = {renameSave: "저장",renameSaving: "저장 중…",},+ planHistory: {+ pending: "승인 대기",+ approved: "승인됨",+ rejected: "거부됨",+ expired: "만료됨",+ interrupted: "중단됨",+ unknown: "상태를 확인할 수 없음",+ superseded: "새 버전으로 대체됨",+ },plan: {planning: "계획 중",approvalRegion: "계획 승인",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex f350d3f02..09e8af6e9 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -564,6 +564,15 @@ export const ptBR = {renameSave: "Salvar",renameSaving: "Salvando…"},+ planHistory: {+ pending: "Aguardando aprovação",+ approved: "Aprovado",+ rejected: "Rejeitado",+ expired: "Expirado",+ interrupted: "Interrompido",+ unknown: "Estado indisponível",+ superseded: "Substituído",+ },plan: {planning: "Planejando",approvalRegion: "Aprovação do plano",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 2f713e0b0..dc08727ed 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -575,6 +575,15 @@ export const tr = {renameSave: "Kaydet",renameSaving: "Kaydediliyor…",},+ planHistory: {+ pending: "Onay bekleniyor",+ approved: "Onaylandı",+ rejected: "Reddedildi",+ expired: "Süresi doldu",+ interrupted: "Kesintiye uğradı",+ unknown: "Durum kullanılamıyor",+ superseded: "Yeni sürümle değiştirildi",+ },plan: {planning: "Planlanıyor",approvalRegion: "Plan onayı",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 4b366c428..a094d6213 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -570,6 +570,15 @@ export const zhCN = {renameSave: "保存",renameSaving: "保存中…",},+ planHistory: {+ pending: "待审批",+ approved: "已批准",+ rejected: "已拒绝",+ expired: "已过期",+ interrupted: "已中断",+ unknown: "状态不可用",+ superseded: "已被新版本替代",+ },plan: {planning: "正在规划",approvalRegion: "规划审批",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex bd3e59f41..cb78a4cd6 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -570,6 +570,15 @@ export const zhTW = {renameSave: "儲存",renameSaving: "儲存中…",},+ planHistory: {+ pending: "待審批",+ approved: "已批准",+ rejected: "已拒絕",+ expired: "已過期",+ interrupted: "已中斷",+ unknown: "狀態無法取得",+ superseded: "已被新版本取代",+ },plan: {planning: "正在規劃",approvalRegion: "規劃審批",diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.tsindex 4532533aa..1a2073130 100644--- a/packages/shared/src/types/messages.ts+++ b/packages/shared/src/types/messages.ts@@ -1,3 +1,4 @@+import type { PlanHistoryEntry } from "./plans.js";/** Shared public types grouped by the owning application domain. */import type { SessionMessageOrigin } from "../session-collaboration.js";import type { AppError } from "../errors.js";@@ -133,6 +134,8 @@ export type UiMessage = {toolStatus?: "running" | "success" | "error" | "denied";toolArgs?: unknown;toolResult?: unknown;+ /** Renderer projection; never written back into canonical model evidence. */+ planHistory?: PlanHistoryEntry;/** Estimated tokens occupied by this tool call and its result. */toolUsage?: ToolTokenUsage;toolCompletedAt?: string;diff --git a/packages/shared/src/types/plans.ts b/packages/shared/src/types/plans.tsindex 909be46a2..d87d82a3b 100644--- a/packages/shared/src/types/plans.ts+++ b/packages/shared/src/types/plans.ts@@ -162,3 +162,6 @@ export type PlanResolutionResult = {targetPermissionMode?: GlobalPermissionMode;execution?: PlanExecution;};++/** Current host state for one immutable plan/goal submission in a history page. */+export type PlanHistoryEntry = { proposal: PlanProposal; superseded: boolean };diff --git a/packages/shared/src/types/sessions.ts b/packages/shared/src/types/sessions.tsindex f46d0f9c0..844b5cb42 100644--- a/packages/shared/src/types/sessions.ts+++ b/packages/shared/src/types/sessions.ts@@ -3,7 +3,7 @@ import type { Mode } from "./common.js";import type { SessionThinkingLevel, ThinkingLevel } from "./models.js";import type { PermissionMode } from "./permissions.js";import type { UiMessage } from "./messages.js";-import type { PlanningState } from "./plans.js";+import type { PlanHistoryEntry, PlanningState } from "./plans.js";/*** Which authority owns a session's transcript.@@ -59,6 +59,8 @@ export type SessionSummary = {export type SessionDetail = SessionSummary & {messages: UiMessage[];+ /** Authoritative metadata scoped to the submitted contracts in this page. */+ planHistory?: PlanHistoryEntry[];/** Owning Task for a nested search target; context only, outside page cursors. */navigationParent?: UiMessage;/** Zero-based offset of the first message returned by a bounded history read. */diff --git a/scripts/e2e-plan-history.mjs b/scripts/e2e-plan-history.mjsnew file mode 100644index 000000000..94594e373--- /dev/null+++ b/scripts/e2e-plan-history.mjs@@ -0,0 +1,148 @@+#!/usr/bin/env node+/** Historical contracts through production session IPC, renderer and an isolated Rust host. */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";+import { resolveHostBinary } from "./e2e/host.mjs";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const require = createRequire(join(root, "packages/agent-runtime/package.json"));+const { build } = require("esbuild");+const { electronBinary } = resolveElectronBinary(root);+const binary = resolveHostBinary();+const temp = await mkdtemp(join(tmpdir(), "pi-plan-history-"));+try {+ await build({+ entryPoints: [join(root, "scripts/e2e/plan-history.tsx")],+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "iife", jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"' },+ loader: { ".woff": "file", ".woff2": "file", ".ttf": "file" },+ alias: {+ "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),+ react: join(root, "apps/desktop/node_modules/react"),+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),+ },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ await build({+ entryPoints: [join(root, "apps/desktop/electron/main/ipc/session-ipc.ts")],+ outfile: join(temp, "session-ipc.cjs"), bundle: true, platform: "node", format: "cjs",+ external: ["electron"],+ });+ await build({ entryPoints: [join(root, "apps/desktop/electron/preload/index.ts")],+ outfile: join(temp, "preload.cjs"), bundle: true, platform: "node", format: "cjs", external: ["electron"],+ alias: { "@pi-desktop/shared/protocol": join(root, "packages/shared/src/protocol.ts") } });+ await writeFile(join(temp, "tokens.css"), (await readFile(join(root, "apps/desktop/src/styles/tokens.css"), "utf8")).replace(/@theme(?: inline)?/g, ":root"));+ await writeFile(join(temp, "index.html"), `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'"><link rel="stylesheet" href="tokens.css"><link rel="stylesheet" href="renderer.css"><body><script src="renderer.js"></script>`);+ await writeFile(join(temp, "main.cjs"), `+const { app, BrowserWindow, ipcMain } = require("electron");+const path = require("node:path");+const { registerSessionIpc } = require("./session-ipc.cjs");+app.setPath("userData", path.join(__dirname, "profile"));+app.whenReady().then(async () => {+ const { Host } = await import(${JSON.stringify(pathToFileURL(join(root, "scripts/e2e/host.mjs")).href)});+ const { IPC } = await import(${JSON.stringify(pathToFileURL(join(root, "packages/shared/dist/protocol.js")).href)});+ const host = new Host(${JSON.stringify(binary)}, path.join(__dirname, "data"));+ let window;+ let failure;+ try {+ await host.start();+ const fs = require("node:fs/promises");+ const workspace = path.join(__dirname, "workspace");+ await fs.mkdir(workspace);+ const { session } = await host.call("session.create", { title: "Plan history", mode: "plan", projectPath: workspace });+ const submit = async (owner, title, kind = "plan") => {+ const { turnId } = await host.call("session.beginTurn", { sessionId: owner.id });+ const { proposal } = await host.call("plans.submit", { sessionId: owner.id, turnId, toolCallId: title, kind,+ title, markdown: "# Exact " + title + "\\n\\n- retain exact bytes \\n\\nEND-" + title, question: "Proceed?" });+ const message = { id: "tool-" + title, role: "tool", content: "submitted", createdAt: proposal.createdAt,+ toolName: kind === "goal" ? "SubmitGoal" : "SubmitPlan", toolCallId: title,+ toolResult: { details: { proposal } }, toolStatus: "success" };+ await host.call("session.appendMessage", { sessionId: owner.id, turnId, message });+ if (await fs.readFile(path.join(workspace, proposal.artifact.relativePath), "utf8") !== proposal.markdown) throw new Error("artifact bytes changed");+ return { proposal, message };+ };+ const resolve = (proposal, action) => host.call("plans.resolve", { proposalId: proposal.id, sessionId: proposal.sessionId,+ turnId: proposal.turnId, toolCallId: proposal.toolCallId, version: proposal.version, action,+ ...(action === "approve" ? { targetPermissionMode: "ask" } : {}) });+ const first = await submit(session, "v1");+ const registrar = { handle(channel, handler) {+ ipcMain.handle(channel, async (_event, input) => {+ try { return { ok: true, data: await handler(input) }; }+ catch (error) { return { ok: false, error: { code: error.errorCode || "INTERNAL", message: error.message } }; }+ });+ } };+ registerSessionIpc({ registrar, getHost: () => host, getSidecar: () => null,+ dataDir: path.join(__dirname, "data"), activeTurns: new Map(), sessionProjects: new Map(),+ persistenceOutbox: {}, logger: { app() {} }, plugins: { broadcastEvent() {} },+ sessionCapabilityContext: async () => ({ providers: [], defaults: {} }),+ enrichSession: session => session, acquireSessionOperation: async () => () => {}, stripWinLongPrefix: value => value });+ registrar.handle(IPC.invoke.agentQueueList, async () => ({ entries: [] }));+ window = new BrowserWindow({ show: false, width: 1000, height: 1000, webPreferences: {+ preload: ${JSON.stringify(join(temp, "preload.cjs"))},+ sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false,+ } });+ window.webContents.on("console-message", (event) => console.error(event.message));+ await window.loadFile(path.join(__dirname, "index.html"));+ const probe = (name, ...args) => window.webContents.executeJavaScript("globalThis." + name + "(" + args.map(value => JSON.stringify(value)).join(",") + ")");+ const pending = await probe("planHistoryLoad", session.id, ["pending"]);+ const stateOnly = await probe("planHistoryStateOnly");+ const approval = await resolve(first.proposal, "approve");+ const live = await probe("planHistoryLive", approval.proposal, first.message);+ await host.call("session.endTurn", { turnId: first.proposal.turnId, createNotification: false });+ await host.call("plans.claimExecution", { executionId: approval.proposal.executionId });+ await host.call("plans.finishExecution", { executionId: approval.proposal.executionId, status: "completed" });+ await host.call("session.configure", { id: session.id, mode: "plan" });+ const second = await submit(session, "v2");+ await resolve(second.proposal, "reject");+ await host.call("session.endTurn", { turnId: second.proposal.turnId, createNotification: false });+ const versions = await probe("planHistoryLoad", session.id, ["approved", "rejected"]);+ const pagination = await probe("planHistoryPagination", session.id);+ if (process.env.PI_DESKTOP_E2E_EVIDENCE_DIR) {+ await fs.mkdir(process.env.PI_DESKTOP_E2E_EVIDENCE_DIR, { recursive: true });+ await fs.writeFile(path.join(process.env.PI_DESKTOP_E2E_EVIDENCE_DIR, "plan-history.png"), (await window.webContents.capturePage()).toPNG());+ }+ const { session: goal } = await host.call("session.create", { title: "Goal history", mode: "goal", projectPath: workspace });+ const goalSubmission = await submit(goal, "goal", "goal");+ await resolve(goalSubmission.proposal, "reject");+ await host.call("session.endTurn", { turnId: goalSubmission.proposal.turnId, createNotification: false });+ const goals = await probe("planHistoryLoad", goal.id, ["rejected"], "zh-CN");+ await host.call("session.appendCompaction", { sessionId: session.id, compaction: { id: "history-compaction",+ summary: "Earlier planning condensed", throughMessageId: second.message.id, tokensBefore: 100, createdAt: new Date().toISOString() } });+ await host.call("session.appendMessage", { sessionId: session.id, message: { id: "continued", role: "assistant", content: "continued after compaction", createdAt: new Date().toISOString() } });+ await host.restart();+ await window.loadFile(path.join(__dirname, "index.html"));+ const restart = await probe("planHistoryLoad", session.id, ["approved", "rejected"]);+ console.log("PLAN_HISTORY_PROBE " + JSON.stringify({ ok: true, pending, stateOnly, live, versions, pagination, goals, restart, compaction: true }));+ } catch (error) {+ failure = error;+ console.error("PLAN_HISTORY_PROBE " + JSON.stringify({ ok: false, error: String(error) }));+ } finally {+ window?.destroy();+ await host.stop();+ app.exit(failure ? 1 : 0);+ }+});+`);+ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ 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 timer = setTimeout(() => child.kill("SIGKILL"), 60_000);+ let code;+ try {+ code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });+ } finally { clearTimeout(timer); }+ const line = output.split(/\r?\n/).find((line) => line.startsWith("PLAN_HISTORY_PROBE "));+ assert(line, `no result (exit=${code}): ${output.slice(-4000)}`);+ console.log(line);+ assert.equal(code, 0, output.slice(-6000));+ assert.equal(JSON.parse(line.slice("PLAN_HISTORY_PROBE ".length)).ok, true);+} finally { await rm(temp, { recursive: true, force: true }); }diff --git a/scripts/e2e/plan-history.tsx b/scripts/e2e/plan-history.tsxnew file mode 100644index 000000000..d074a7db9--- /dev/null+++ b/scripts/e2e/plan-history.tsx@@ -0,0 +1,94 @@+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 type { PlanProposal, SessionDetail, UiMessage } from "@pi-desktop/shared";+import { api } from "../../apps/desktop/src/lib/api";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";+import { ToolRow } from "../../apps/desktop/src/features/chat/transcript/ToolRow";+import { TranscriptDisclosureProvider } from "../../apps/desktop/src/features/chat/transcript/disclosure";+import "../../apps/desktop/src/styles/ui-kit.css";+import "../../apps/desktop/src/styles/base.css";++const i18n = createInstance();+const ready = i18n.init({ lng: "en", resources: Object.fromEntries(Object.entries(catalogs).map(([key, catalog]) => [key, { translation: catalog }])), interpolation: { escapeValue: false } });+const root = createRoot(document.body);+const assert = (condition: unknown, message: string) => { if (!condition) throw new Error(message); };+const painted = () => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));+function History() {+ const messages = useAppStore(state => state.messages);+ return <TranscriptDisclosureProvider>{messages.filter(message => message.role === "tool").map(message => <ToolRow key={message.id} message={message} />)}</TranscriptDisclosureProvider>;+}+function select(detail: SessionDetail) {+ flushSync(() => useAppStore.setState({ activeSessionId: detail.id, messages: detail.messages, sessions: [detail] }));+}++Object.assign(globalThis, {+ async planHistoryLoad(id: string, statuses: string[], locale = "en") {+ await ready;+ await i18n.changeLanguage(locale);+ const { session } = await api.getSession(id, { messageLimit: 20, contentLimit: 16 });+ assert(session, "session read failed");+ select(session!);+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><History /></I18nextProvider>));+ await painted();+ const cards = [...document.querySelectorAll<HTMLElement>(".plan-history-card")];+ assert(cards.length === statuses.length, "missing historical submission card");+ for (const [index, card] of cards.entries()) {+ const message = session!.messages.filter(message => message.role === "tool")[index];+ const proposal = message.planHistory!.proposal;+ assert(proposal.status === statuses[index], "host approval status missing");+ assert(card.textContent?.includes(i18n.t(`planHistory.${statuses[index]}`)), "localized status missing");+ const title = card.querySelector<HTMLButtonElement>(".plan-history-title")!;+ if (title.getAttribute("aria-expanded") === "false") flushSync(() => title.click());+ await painted();+ assert(card.querySelector(".plan-history-body h1")?.textContent === "Exact " + proposal.title, "full Markdown snapshot was capped or missing");+ assert(card.querySelector(".plan-history-body")?.textContent?.includes("END-" + proposal.title), "Markdown tail was lost");+ flushSync(() => card.querySelector<HTMLButtonElement>(".plan-history-artifact")!.click());+ assert(useAppStore.getState().workPanelFileRequest?.path === proposal.artifact!.relativePath, "artifact did not open for its owning session");+ assert(!card.querySelector(".plan-approve") && !card.textContent?.includes("Approve (Ask)"), "history must not offer approval actions");+ }+ return { cards: cards.length, locale, statuses };+ },+ async planHistoryStateOnly() {+ const state = useAppStore.getState();+ const proposal = state.messages[0].planHistory!.proposal;+ useAppStore.setState({ planCheckpoints: { [proposal.sessionId]: proposal } });+ flushSync(() => state.handlePlansChanged({ sessionId: proposal.sessionId, state: "inactive", kind: proposal.kind }));+ assert(useAppStore.getState().messages[0].planHistory?.proposal.status === "pending", "state-only mode change invented approval");+ return { stateOnlyDoesNotApprove: true };+ },+ async planHistoryLive(proposal: PlanProposal, staleMessage: UiMessage) {+ const state = useAppStore.getState();+ // Both live channels must project the accepted host checkpoint.+ flushSync(() => state.handlePlansChanged({ sessionId: proposal.sessionId, state: "inactive", proposal, kind: proposal.kind }));+ flushSync(() => state.handleAgentEvent({ sessionId: proposal.sessionId, event: { type: "message_end", message: staleMessage } }));+ await painted();+ assert(useAppStore.getState().messages.find(row => row.toolCallId === proposal.toolCallId)?.planHistory?.proposal.status === "approved", "late pending tool echo rolled back approval");+ assert(document.querySelector(".plan-history-card")?.textContent?.includes("Approved"), "live history status did not repaint");+ const pending = (staleMessage.toolResult as { details: { proposal: PlanProposal } }).details.proposal;+ flushSync(() => state.handlePlansChanged({ sessionId: proposal.sessionId, state: "awaiting_approval", proposal: pending, kind: pending.kind }));+ assert(useAppStore.getState().messages[0].planHistory?.proposal.status === "approved", "stale host revision rolled back history");+ // An authoritative event can arrive before the tool's terminal row.+ flushSync(() => useAppStore.setState({ messages: [] }));+ flushSync(() => state.handleAgentEvent({ sessionId: proposal.sessionId, ts: Date.now(), event: {+ type: "planning_state", state: "inactive", proposal, kind: proposal.kind,+ } }));+ flushSync(() => state.handleAgentEvent({ sessionId: proposal.sessionId, ts: Date.now(), event: { type: "message_end", message: staleMessage } }));+ assert(useAppStore.getState().messages[0]?.planHistory?.proposal.status === "approved", "approval-before-message was lost");+ // Switching away retains a pane; events must update that transcript too.+ flushSync(() => useAppStore.setState({ activeSessionId: "other", messages: [], retainedTranscripts: { [proposal.sessionId]: [staleMessage] } }));+ flushSync(() => state.handlePlansChanged({ sessionId: proposal.sessionId, state: "inactive", proposal, kind: proposal.kind }));+ assert(useAppStore.getState().retainedTranscripts[proposal.sessionId][0].planHistory?.proposal.status === "approved", "inactive retained pane kept pending state");+ flushSync(() => useAppStore.setState({ activeSessionId: proposal.sessionId, messages: useAppStore.getState().retainedTranscripts[proposal.sessionId] }));+ return { liveApproval: true, staleEcho: true, eventBeforeMessage: true, inactiveRetainedPane: true };+ },+ async planHistoryPagination(id: string) {+ const latest = (await api.getSession(id, { messageLimit: 1, contentLimit: 16 })).session!;+ assert(latest.planHistory?.length === 1 && latest.planHistory[0].proposal.status === "rejected", "latest page included unrelated plans");+ const older = (await api.getSession(id, { messageLimit: 1, messageBefore: latest.messageStart })).session!;+ assert(older.planHistory?.length === 1 && older.planHistory[0].superseded && older.planHistory[0].proposal.status === "approved", "old page lost its current state/superseded marker");+ return { pagination: true };+ },+});