Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(todo): add session-scoped checklist

Hanawa37f29a2bfe1b
diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.ts
index 65333f3d1..5fb41a095 100644
--- a/apps/desktop/electron/main/ipc/session-ipc.ts
+++ b/apps/desktop/electron/main/ipc/session-ipc.ts
@@ -134,6 +134,15 @@ export function registerSessionIpc({
if (!host) throw new Error("host unavailable");
return host.call("search.context", input);
});
+ handle(IPC.invoke.todosGet, async (input: { sessionId?: unknown } = {}) => {
+ if (!host) throw new Error("host unavailable");
+ if (typeof input.sessionId !== "string" || !input.sessionId.trim()) {
+ throw Object.assign(new Error("sessionId is required"), {
+ errorCode: ErrorCodes.INVALID_ARGUMENT,
+ });
+ }
+ return host.call("todos.get", { sessionId: input.sessionId });
+ });
handle(IPC.invoke.sessionList, async () => {
if (!host) throw new Error("host unavailable");
const [result, native, { providers, defaults }] = await Promise.all([
diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.ts
index 5f35052eb..a94e52449 100644
--- a/apps/desktop/electron/main/runtime/host.ts
+++ b/apps/desktop/electron/main/runtime/host.ts
@@ -304,6 +304,8 @@ export function createHostRuntime({
);
} else if (method === "plans.changed") {
sendToRenderer(IPC.event.plansChanged, params);
+ } else if (method === "todos.changed") {
+ sendToRenderer(IPC.event.todosChanged, params);
} else if (method === "configSync.changed") {
sendToRenderer(IPC.event.configSyncChanged, params);
} else if (method === "configSync.progress") {
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index 53955165d..4e81c2ac5 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -30,6 +30,7 @@ import {
import { ComposerAutocomplete } from "./ComposerAutocomplete";
import { AskToolCard } from "./AskToolCard";
import { PlanApprovalBar } from "./PlanApprovalBar";
+import { TodoDock } from "./TodoDock";
import {
COMPOSER_MAX_VISIBLE_ROWS,
COMPOSER_MIN_HEIGHT_PX,
@@ -510,6 +511,7 @@ export function Composer({
data-composer-dock={variant}
>
<div className="composer-stack">
+ {activeSessionId ? <TodoDock sessionId={activeSessionId} /> : null}
{planCheckpoint?.status === "pending" ? (
<PlanApprovalBar proposal={planCheckpoint} />
) : null}
diff --git a/apps/desktop/src/components/TodoDock.tsx b/apps/desktop/src/components/TodoDock.tsx
new file mode 100644
index 000000000..919a09358
--- /dev/null
+++ b/apps/desktop/src/components/TodoDock.tsx
@@ -0,0 +1,101 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { SessionTodo, TodoStatus } from "@pi-desktop/shared";
+import { Button } from "./ui";
+import { IconChevronDown, IconChevronUp } from "./icons";
+import { api } from "../lib/api";
+import { useAppStore } from "../stores/app-store";
+
+const VISIBLE_LIMIT = 8;
+
+function statusSymbol(status: TodoStatus): string {
+ switch (status) {
+ case "completed":
+ return "✓";
+ case "in_progress":
+ return "◐";
+ case "cancelled":
+ return "⊘";
+ default:
+ return "○";
+ }
+}
+
+export function TodoDock({ sessionId }: { sessionId: string }) {
+ const { t } = useTranslation();
+ const snapshot = useAppStore((state) => state.sessionTodos[sessionId]);
+ const [expanded, setExpanded] = useState(false);
+
+ useEffect(() => {
+ setExpanded(false);
+ }, [sessionId]);
+
+ useEffect(() => {
+ if (sessionId.startsWith("remote:")) return;
+ if (snapshot) return;
+ void api.getTodos(sessionId).then(useAppStore.getState().applyTodosChanged).catch(() => undefined);
+ }, [sessionId, snapshot]);
+ if (!snapshot || snapshot.todos.length === 0) return null;
+ const completed = snapshot.todos.filter((todo) => todo.status === "completed").length;
+ const cancelled = snapshot.todos.filter((todo) => todo.status === "cancelled").length;
+ const denominator = snapshot.todos.length - cancelled;
+ const current = snapshot.todos.find((todo) => todo.status === "in_progress");
+ const allCancelled = cancelled === snapshot.todos.length;
+ const finished = snapshot.todos.every(
+ (todo) => todo.status === "completed" || todo.status === "cancelled",
+ );
+ const visible = expanded ? snapshot.todos.slice(0, VISIBLE_LIMIT) : [];
+ const remaining = Math.max(0, snapshot.todos.length - VISIBLE_LIMIT);
+ const statusLabel = allCancelled
+ ? t("chat.todo.status.cancelled")
+ : finished
+ ? t("chat.todo.completed", { completed, total: denominator })
+ : current
+ ? t("chat.todo.current", { completed, total: denominator, content: current.content })
+ : t("chat.todo.progress", { completed, total: denominator });
+
+ return (
+ <div className={`todo-dock${expanded ? " is-expanded" : ""}`}>
+ <Button
+ type="button"
+ variant="ghost"
+ className="todo-dock-header"
+ aria-expanded={expanded}
+ onClick={() => setExpanded((value) => !value)}
+ >
+ <span className="todo-dock-header-symbol" aria-hidden>
+ {allCancelled ? "⊘" : finished ? "✓" : "◐"}
+ </span>
+ <span className="todo-dock-header-text">{statusLabel}</span>
+ {expanded ? <IconChevronUp size={14} /> : <IconChevronDown size={14} />}
+ </Button>
+ {expanded ? (
+ <div className="todo-dock-list" role="list">
+ {visible.map((todo, index) => (
+ <TodoRow key={`${index}:${todo.content}`} todo={todo} />
+ ))}
+ {remaining > 0 ? (
+ <div className="todo-dock-more" role="status">
+ {t("chat.todo.more", { count: remaining })}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+function TodoRow({ todo }: { todo: SessionTodo }) {
+ const { t } = useTranslation();
+ const label = t(`chat.todo.status.${todo.status}`);
+ return (
+ <div className={`todo-dock-row todo-dock-row-${todo.status}`} role="listitem">
+ <span className="todo-dock-row-symbol" role="img" aria-label={label} title={label}>
+ {statusSymbol(todo.status)}
+ </span>
+ <span className="todo-dock-row-content" title={todo.content}>
+ {todo.content}
+ </span>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/components/icons.tsx b/apps/desktop/src/components/icons.tsx
index 934b999e3..f7bb43eec 100644
--- a/apps/desktop/src/components/icons.tsx
+++ b/apps/desktop/src/components/icons.tsx
@@ -18,6 +18,7 @@ import {
ChevronDown,
ChevronLeft,
ChevronRight,
+ ChevronUp,
CircleAlert,
CircleCheck,
CircleHelp,
@@ -197,9 +198,10 @@ export const IconSquare = icon(Square);
export const IconSliders = icon(SlidersHorizontal);
export const IconConfig = icon(RefreshCcw);
export const IconChevronLeft = icon(ChevronLeft);
-export const IconChevronRight = icon(ChevronRight);
export const IconExternal = icon(ExternalLink);
export const IconArrowUpRight = icon(ArrowUpRight);
+export const IconChevronRight = icon(ChevronRight);
+export const IconChevronUp = icon(ChevronUp);
export const IconUndo2 = icon(Undo2);
export const IconCloudDown = icon(CloudDownload);
export const IconDownload = icon(Download);
diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsx
index 51b60e076..9f417f267 100644
--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx
+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx
@@ -573,6 +573,9 @@ export function useAppShellRuntime() {
useAppStore.getState().applyQueueChanged(event),
);
const offPlansChanged = api.onPlansChanged(handlePlansChanged);
+ const offTodosChanged = api.onTodosChanged((snapshot) =>
+ useAppStore.getState().applyTodosChanged(snapshot),
+ );
// Host-pushed toasts (plugin runtime etc.) are informational.
const offToast = api.onToast((message) => showToast(message));
const offNotificationSound = api.onNotificationSound(playNotificationChime);
@@ -806,6 +809,7 @@ export function useAppShellRuntime() {
offEvent();
offQueueChanged();
offPlansChanged();
+ offTodosChanged();
offToast();
offNotificationSound();
offInsecureEndpoint();
diff --git a/apps/desktop/src/features/chat/transcript/shared.tsx b/apps/desktop/src/features/chat/transcript/shared.tsx
index 91d82f7c8..019dd4974 100644
--- a/apps/desktop/src/features/chat/transcript/shared.tsx
+++ b/apps/desktop/src/features/chat/transcript/shared.tsx
@@ -47,6 +47,7 @@ import {
IconFolder,
IconGlobe,
IconImage,
+ IconListChecks,
IconPencil,
IconSearch,
IconSheet,
@@ -320,7 +321,6 @@ export function AssistantErrorMessage({ message }: { message: UiMessage }) {
</section>
);
}
-
export const TOOL_ACTION_KEYS: Record<ToolAction, string> = {
read: "chat.toolRead",
list: "chat.toolListed",
@@ -331,6 +331,7 @@ export const TOOL_ACTION_KEYS: Record<ToolAction, string> = {
fetch: "chat.toolFetched",
fork: "chat.toolUsed",
delegate: "chat.toolDelegated",
+ todo: "chat.todo.updated",
use: "chat.toolUsed",
};
@@ -361,6 +362,7 @@ export const TOOL_RUNNING_KEYS: Record<ToolAction, string> = {
fetch: "chat.toolFetching",
fork: "chat.toolUsing",
delegate: "chat.toolDelegating",
+ todo: "chat.todo.updating",
use: "chat.toolUsing",
};
@@ -376,6 +378,8 @@ export function ToolActionIcon({ action }: { action: ToolAction }) {
case "write":
case "edit":
return <IconPencil {...props} />;
+ case "todo":
+ return <IconListChecks {...props} />;
case "run":
return <IconTerminal {...props} />;
case "fetch":
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 59b696406..695e3f1af 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -120,6 +120,7 @@ import type {
TrustedExtensionStatusEvent,
TrustedExtensionUiPrompt,
TrustedExtensionUiPromptResponse,
+ SessionTodoSnapshot,
} from "@pi-desktop/shared";
import {
defaultCommandShellForPlatform,
@@ -1492,6 +1493,14 @@ export const api = {
listener(normalizePlansChangedEvent(payload)),
);
},
+ getTodos: (sessionId: string) =>
+ invoke<SessionTodoSnapshot>(IPC.invoke.todosGet, { sessionId }),
+ onTodosChanged: (listener: (snapshot: SessionTodoSnapshot) => void) => {
+ if (!window.piDesktop?.on) return () => undefined;
+ return window.piDesktop.on(IPC.event.todosChanged, (payload) =>
+ listener(payload as SessionTodoSnapshot),
+ );
+ },
onOauthLogin: (listener: (event: OAuthLoginEvent) => void) => {
if (!window.piDesktop?.on) return () => undefined;
return window.piDesktop.on(IPC.event.providersOauth, (payload) =>
diff --git a/apps/desktop/src/lib/tool-display.ts b/apps/desktop/src/lib/tool-display.ts
index b637cd39f..802da3cf4 100644
--- a/apps/desktop/src/lib/tool-display.ts
+++ b/apps/desktop/src/lib/tool-display.ts
@@ -8,6 +8,7 @@ export type ToolAction =
| "fetch"
| "fork"
| "delegate"
+ | "todo"
| "use";
const SUMMARY_KEYS: Record<ToolAction, string[]> = {
@@ -24,6 +25,7 @@ const SUMMARY_KEYS: Record<ToolAction, string[]> = {
// tool (ADR 0089) carries only delegation ids, which read as bare UUIDs, so
// it summarizes from the agent names in its own result roster instead (D268).
delegate: ["description", "agent"],
+ todo: [],
use: [
"command",
"cmd",
@@ -36,7 +38,6 @@ const SUMMARY_KEYS: Record<ToolAction, string[]> = {
"prompt",
],
};
-
function compact(value: string, limit = 220) {
const singleLine = value.replace(/\s+/g, " ").trim();
return singleLine.length > limit
@@ -104,6 +105,7 @@ export function getToolAction(toolName?: string): ToolAction {
if (isDelegationStartTool(toolName) || delegationLifecycleKind(toolName)) {
return "delegate";
}
+ if (bareToolName(toolName) === "todowrite") return "todo";
if (matches(["websearch", "searchquery", "fetch", "http", "browser"])) {
return "fetch";
}
@@ -112,12 +114,8 @@ export function getToolAction(toolName?: string): ToolAction {
if (matches(["grep", "rg", "search", "searchfiles"])) return "search";
if (matches(["write", "writefile", "createfile"])) return "write";
if (matches(["edit", "editfile", "applypatch", "patch"])) return "edit";
- if (matches(["fork", "forkagent", "forktask", "forksession"])) {
- return "fork";
- }
- if (
- matches(["bash", "shell", "exec", "execcommand", "runcommand", "terminal"])
- ) {
+ if (matches(["fork", "forkagent", "forktask", "forksession"])) return "fork";
+ if (matches(["bash", "shell", "exec", "execcommand", "runcommand", "terminal"])) {
return "run";
}
return "use";
diff --git a/apps/desktop/src/lib/tool-presentation.ts b/apps/desktop/src/lib/tool-presentation.ts
index 146f2fd10..789c21795 100644
--- a/apps/desktop/src/lib/tool-presentation.ts
+++ b/apps/desktop/src/lib/tool-presentation.ts
@@ -619,6 +619,20 @@ function resultBlocks(
if (resolved) blocks.push(resolved);
break;
}
+ case "todo": {
+ const todoArgs = args ? safeJson(args) : "";
+ if (todoArgs) blocks.push(codeBlock("input", todoArgs, "json"));
+ const warnings = stringArray(details?.warnings);
+ if (warnings) {
+ for (const warning of warnings) {
+ blocks.push({ kind: "note", role: "notice", text: warning });
+ }
+ }
+ const text = stringAt(details, "text");
+ if (text) blocks.push({ kind: "note", role: "notice", text });
+ mapped = true;
+ break;
+ }
case "delegate": {
// A lifecycle row (ADR 0089) has no brief and no report of its own: it
// reports on subagents. Its body is the roster the runtime returned, as
diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.ts
index 46e377a5e..d84d83967 100644
--- a/apps/desktop/src/stores/app-state.ts
+++ b/apps/desktop/src/stores/app-state.ts
@@ -25,6 +25,7 @@ import type {
ReviewRollbackResult,
SessionSummary,
SessionThinkingLevel,
+ SessionTodoSnapshot,
UiMessage,
} from "@pi-desktop/shared";
import type { SettingsTabId } from "../lib/settings-search";
@@ -173,6 +174,9 @@ export type AppState = {
pendingPlans: Record<string, PlanProposal>;
/** Latest immutable Plan checkpoint/execution snapshot per session. */
planCheckpoints: Record<string, PlanProposal>;
+ /** Host-authoritative Todo snapshots keyed by session. */
+ sessionTodos: Record<string, SessionTodoSnapshot>;
+ applyTodosChanged: (snapshot: SessionTodoSnapshot) => void;
toasts: ToastItem[];
notifications: AppNotification[];
unreadNotificationCount: number;
diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.ts
index 868143415..446be4648 100644
--- a/apps/desktop/src/stores/slices/events-slice.ts
+++ b/apps/desktop/src/stores/slices/events-slice.ts
@@ -13,6 +13,7 @@ import {
import type {
AgentEventEnvelope,
PlanningStateEvent,
+ SessionTodoSnapshot,
UiMessage,
} from "@pi-desktop/shared";
import {
@@ -69,6 +70,29 @@ export type EventsSliceDependencies = StoreAccess & {
mark: NonNullable<AppState["sessionCompactions"][string]>[number],
) => NonNullable<AppState["sessionCompactions"][string]>;
};
+function isSessionTodoSnapshot(value: unknown): value is SessionTodoSnapshot {
+ if (!value || typeof value !== "object") return false;
+ const snapshot = value as SessionTodoSnapshot;
+ if (
+ typeof snapshot.sessionId !== "string" ||
+ !Number.isInteger(snapshot.revision) ||
+ snapshot.revision < 0 ||
+ typeof snapshot.updatedAt !== "number" ||
+ !Number.isFinite(snapshot.updatedAt) ||
+ !Array.isArray(snapshot.todos)
+ ) {
+ return false;
+ }
+ return snapshot.todos.every((todo) => {
+ if (!todo || typeof todo !== "object") return false;
+ const item = todo as SessionTodoSnapshot["todos"][number];
+ return (
+ typeof item.content === "string" &&
+ ["pending", "in_progress", "completed", "cancelled"].includes(item.status) &&
+ ["high", "medium", "low"].includes(item.priority)
+ );
+ });
+}
export function createEventsSlice({
get,
@@ -84,7 +108,7 @@ export function createEventsSlice({
withCompactionMark,
}: EventsSliceDependencies): Pick<
AppState,
- "handlePlansChanged" | "handleAgentEvent"
+ "handlePlansChanged" | "handleAgentEvent" | "applyTodosChanged"
> {
let flushingStreamUpdates = false;
const streamUpdates = createFrameBatcher<AgentEventEnvelope>((envelopes) => {
@@ -99,6 +123,14 @@ export function createEventsSlice({
});
return {
+ applyTodosChanged: (snapshot: SessionTodoSnapshot) => {
+ if (!isSessionTodoSnapshot(snapshot)) return;
+ set((state) => {
+ const current = state.sessionTodos[snapshot.sessionId];
+ if (current && current.revision >= snapshot.revision) return state;
+ return { sessionTodos: { ...state.sessionTodos, [snapshot.sessionId]: snapshot } };
+ });
+ },
handlePlansChanged: (event) => {
if (!event?.sessionId) return;
runtime.nextPlanSyncGeneration(event.sessionId);
diff --git a/apps/desktop/src/stores/slices/initial-state.ts b/apps/desktop/src/stores/slices/initial-state.ts
index 95518c86f..be1c1b8c6 100644
--- a/apps/desktop/src/stores/slices/initial-state.ts
+++ b/apps/desktop/src/stores/slices/initial-state.ts
@@ -72,6 +72,7 @@ export function createInitialState(): AppStateData {
planningStates: {},
pendingPlans: {},
planCheckpoints: {},
+ sessionTodos: {},
page: "chat",
settingsTab: "general",
settingsAnchor: null,
diff --git a/apps/desktop/src/styles/composer.css b/apps/desktop/src/styles/composer.css
index f43d631cb..c57b94ab3 100644
--- a/apps/desktop/src/styles/composer.css
+++ b/apps/desktop/src/styles/composer.css
@@ -788,3 +788,77 @@
.composer-directory-drop-action:hover {
background: var(--ds-tile-hover);
}
+
+.todo-dock {
+ border: 1px solid var(--ds-border-subtle);
+ border-radius: var(--radius-md);
+ background: var(--ds-bg-dock-raised);
+ overflow: hidden;
+}
+
+.todo-dock-header {
+ display: flex;
+ width: 100%;
+ align-items: center;
+ gap: 8px;
+ border: 0;
+ padding: 7px 10px;
+ background: transparent;
+ color: var(--ds-text-primary);
+ text-align: left;
+ cursor: pointer;
+}
+
+.todo-dock-header:hover,
+.todo-dock-header:focus-visible {
+ background: var(--ds-bg-hover);
+}
+
+.todo-dock-header-symbol,
+.todo-dock-row-symbol {
+ flex: 0 0 auto;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm);
+}
+
+.todo-dock-header-text {
+ min-width: 0;
+ flex: 1;
+ overflow: hidden;
+ font-size: var(--text-sm);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.todo-dock-list {
+ display: grid;
+ gap: 2px;
+ padding: 0 10px 8px;
+}
+
+.todo-dock-row {
+ display: flex;
+ min-width: 0;
+ align-items: center;
+ gap: 8px;
+ padding: 3px 0;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-xs);
+}
+
+.todo-dock-row-in_progress {
+ color: var(--ds-text-primary);
+ font-weight: var(--font-weight-medium);
+}
+
+.todo-dock-row-content {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.todo-dock-more {
+ color: var(--ds-text-muted);
+ font-size: var(--text-2xs);
+}
diff --git a/apps/desktop/test/todo-dock-rendering.test.mjs b/apps/desktop/test/todo-dock-rendering.test.mjs
new file mode 100644
index 000000000..838622f4e
--- /dev/null
+++ b/apps/desktop/test/todo-dock-rendering.test.mjs
@@ -0,0 +1,74 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { createInstance } from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { catalogs } from "@pi-desktop/i18n";
+import { createServer } from "vite";
+import { fileURLToPath } from "node:url";
+
+test("TodoDock renders bounded session progress and cancelled state", async () => {
+ const server = await createServer({
+ root: fileURLToPath(new URL("..", import.meta.url)),
+ configFile: false,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ esbuild: { jsx: "automatic" },
+ appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ try {
+ const { TodoDock } = await server.ssrLoadModule("/src/components/TodoDock.tsx");
+ const { useAppStore } = await server.ssrLoadModule("/src/stores/app-store.ts");
+ const i18n = createInstance();
+ await i18n.init({ lng: "en", resources: { en: { translation: catalogs.en } } });
+ const render = () =>
+ renderToStaticMarkup(
+ createElement(
+ I18nextProvider,
+ { i18n },
+ createElement(TodoDock, { sessionId: "session-todo-test" }),
+ ),
+ );
+
+ Object.assign(useAppStore.getInitialState(), {
+ sessionTodos: {
+ "session-todo-test": {
+ sessionId: "session-todo-test",
+ revision: 3,
+ updatedAt: 100,
+ todos: [
+ { content: "first", status: "completed", priority: "medium" },
+ { content: "second", status: "in_progress", priority: "high" },
+ ...Array.from({ length: 10 }, (_, index) => ({
+ content: `extra-${index}`,
+ status: "pending",
+ priority: "low",
+ })),
+ ],
+ },
+ },
+ });
+ const html = render();
+ assert.match(html, /1\/12 · Current: second/);
+ assert.doesNotMatch(html, /extra-0/);
+ assert.match(html, /aria-expanded="false"/);
+
+ Object.assign(useAppStore.getInitialState(), {
+ sessionTodos: {
+ "session-todo-test": {
+ sessionId: "session-todo-test",
+ revision: 4,
+ updatedAt: 101,
+ todos: [
+ { content: "cancelled work", status: "cancelled", priority: "low" },
+ ],
+ },
+ },
+ });
+ assert.match(render(), /Cancelled/);
+ assert.doesNotMatch(render(), /0\/0 completed/);
+ } finally {
+ await server.close();
+ }
+});
diff --git a/apps/desktop/test/todo-events.test.mjs b/apps/desktop/test/todo-events.test.mjs
new file mode 100644
index 000000000..ccb925a89
--- /dev/null
+++ b/apps/desktop/test/todo-events.test.mjs
@@ -0,0 +1,63 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { register } from "node:module";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+const { createEventsSlice } = await import("../src/stores/slices/events-slice.ts");
+
+function snapshot(revision, todos = []) {
+ return {
+ sessionId: "session-1",
+ todos,
+ revision,
+ updatedAt: revision,
+ };
+}
+
+function makeSlice() {
+ let state = { sessionTodos: {} };
+ const get = () => state;
+ const set = (update) => {
+ const next = typeof update === "function" ? update(state) : update;
+ state = { ...state, ...next };
+ };
+ return {
+ slice: createEventsSlice({
+ get,
+ set,
+ runtime: { nextPlanSyncGeneration() {} },
+ withoutRecordKey: (record, key) => {
+ const copy = { ...record };
+ delete copy[key];
+ return copy;
+ },
+ sessionModeForPlanningState: () => "agent",
+ openPlanArtifact() {},
+ notifyInteractivePrompt() {},
+ triggerAutoTitleSummarization: async () => {},
+ flushPendingSessionConfiguration: async () => {},
+ assistantErrorMessage: () => ({ role: "assistant", content: "" }),
+ withCompactionMark: (marks, mark) => [...(marks ?? []), mark],
+ }),
+ read: () => state,
+ };
+}
+
+test("Todo events keep the newest valid session snapshot only", () => {
+ const { slice, read } = makeSlice();
+ const apply = slice.applyTodosChanged;
+ apply(snapshot(2, [{ content: "new", status: "pending", priority: "medium" }]));
+ apply(snapshot(1, [{ content: "old", status: "pending", priority: "medium" }]));
+ assert.equal(read().sessionTodos["session-1"].todos[0].content, "new");
+ assert.equal(read().sessionTodos["session-1"].revision, 2);
+
+ apply({ sessionId: "session-1", revision: 3, updatedAt: 3 });
+ apply(snapshot(3, [{ content: "bad status", status: "unknown", priority: "medium" }]));
+ assert.equal(read().sessionTodos["session-1"].revision, 2);
+
+ apply(snapshot(3, [{ content: "cleared", status: "cancelled", priority: "low" }]));
+ assert.equal(read().sessionTodos["session-1"].revision, 3);
+});
diff --git a/apps/desktop/test/tool-presentation.test.mjs b/apps/desktop/test/tool-presentation.test.mjs
index aa273fb83..dd2cd5133 100644
--- a/apps/desktop/test/tool-presentation.test.mjs
+++ b/apps/desktop/test/tool-presentation.test.mjs
@@ -16,6 +16,7 @@ const {
toolResultChips,
toolResultPayload,
} = await import("../src/lib/tool-presentation.ts");
+const { getToolAction } = await import("../src/lib/tool-display.ts");
/** A host tool result as pi-ai delivers it: structured details plus text echo. */
function envelope(details) {
@@ -717,3 +718,19 @@ test("a malformed roster degrades instead of rendering blank rows", () => {
[],
);
});
+
+test("TodoWrite has a checklist action and keeps its arguments visible", () => {
+ assert.equal(getToolAction("TodoWrite"), "todo");
+ const message = {
+ toolName: "TodoWrite",
+ toolArgs: { todos: [{ content: "Inspect", status: "pending", priority: "high" }] },
+ toolResult: envelope({
+ text: "Checklist updated: 0/1 completed",
+ revision: 1,
+ summary: { completed: 0, total: 1, inProgress: 0, cancelled: 0 },
+ warnings: [],
+ }),
+ };
+ assert.deepEqual(roles(buildToolPresentation(message)), ["input", "notice"]);
+ assert.match(byRole(buildToolPresentation(message), "input").text, /Inspect/);
+});
diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rs
index 8e15d5e36..6d984a75a 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 = 20;
+pub const SCHEMA_VERSION: i64 = 21;
/// Absolute approval deadline for a newly submitted Plan or Goal proposal.
pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;
@@ -26,7 +26,7 @@ pub(crate) use migrations::{
archive_legacy_db, create_migration_backup, migrate_and_validate_top_level_mode,
migrate_app_settings, migrate_v10_to_v15, migrate_v11_to_v15, migrate_v12_to_v15,
migrate_v13_to_v15, migrate_v14_to_v15, migrate_v17_to_v18, migrate_v18_to_v19,
- migrate_v19_to_v20, migrate_v7_to_v8, migrate_v8_to_v15, migrate_v9_to_v15,
+ migrate_v19_to_v20, migrate_v20_to_v21, migrate_v7_to_v8, migrate_v8_to_v15, migrate_v9_to_v15,
migration_backup_path, validate_session_modes,
};
pub(crate) use model::PlanWorkRow;
@@ -37,7 +37,7 @@ pub(crate) use repositories::{
strip_obsolete_plan_approval_permission_mode, upsert_project_row, MAX_PROJECT_MEMORY_BYTES,
OBSOLETE_PLAN_APPROVAL_PERMISSION_MODE,
};
-pub(crate) use schema::{PLAN_APPROVALS_SCHEMA, SCHEMA_LATEST};
+pub(crate) use schema::{PLAN_APPROVALS_SCHEMA, SCHEMA_LATEST, SESSION_TODO_DDL};
pub fn now_ms() -> i64 {
chrono::Utc::now().timestamp_millis()
diff --git a/crates/host-core/src/db/migrations.rs b/crates/host-core/src/db/migrations.rs
index ea73c93ad..ae5cf50b5 100644
--- a/crates/host-core/src/db/migrations.rs
+++ b/crates/host-core/src/db/migrations.rs
@@ -878,3 +878,41 @@ pub(crate) fn migrate_v19_to_v20(conn: &Connection, path: &Path) -> Result<()> {
})?;
Ok(())
}
+
+/// v21 adds the per-session Todo checklist: the `todo_revision` /
+/// `todo_updated_at` stamps on `sessions` and the ordered `session_todo`
+/// rows that the `TodoWrite` tool replaces atomically.
+///
+/// The table DDL is shared verbatim with the fresh schema, and both the
+/// column probe and `IF NOT EXISTS` keep a second run harmless: an existing
+/// test fixture that downgrades `user_version` in place already carries the
+/// table and columns.
+pub(crate) fn migrate_v20_to_v21_tx(tx: &rusqlite::Transaction<'_>) -> Result<()> {
+ let has_todo_revision: bool = tx.query_row(
+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info('sessions') WHERE name = 'todo_revision')",
+ [],
+ |row| row.get(0),
+ )?;
+ if !has_todo_revision {
+ tx.execute_batch(
+ "ALTER TABLE sessions ADD COLUMN todo_revision INTEGER NOT NULL DEFAULT 0;
+ ALTER TABLE sessions ADD COLUMN todo_updated_at INTEGER;",
+ )?;
+ }
+ tx.execute_batch(SESSION_TODO_DDL)?;
+ tx.pragma_update(None, "user_version", 21i64)?;
+ Ok(())
+}
+
+pub(crate) fn migrate_v20_to_v21(conn: &Connection, path: &Path) -> Result<()> {
+ let backup = create_migration_backup(conn, path, 20)?;
+ let tx = conn.unchecked_transaction()?;
+ migrate_v20_to_v21_tx(&tx)?;
+ tx.commit().with_context(|| {
+ format!(
+ "commit schema v20 to v21 migration; backup {} remains",
+ backup.display()
+ )
+ })?;
+ Ok(())
+}
diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rs
index 2eaab3256..719a93def 100644
--- a/crates/host-core/src/db/repositories.rs
+++ b/crates/host-core/src/db/repositories.rs
@@ -183,6 +183,9 @@ impl Database {
19 => {
migrate_v19_to_v20(&conn, path)?;
}
+ 20 => {
+ migrate_v20_to_v21(&conn, path)?;
+ }
legacy @ 1..=6 => {
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
drop(conn);
@@ -217,6 +220,10 @@ impl Database {
}
if migrated_version == 19 {
migrate_v19_to_v20(&conn, path)?;
+ migrated_version = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
+ }
+ if migrated_version == 20 {
+ migrate_v20_to_v21(&conn, path)?;
}
let db = Self { conn, data_dir };
db.boot_maintenance()?;
diff --git a/crates/host-core/src/db/schema.rs b/crates/host-core/src/db/schema.rs
index 8724bbec5..d8ed27f71 100644
--- a/crates/host-core/src/db/schema.rs
+++ b/crates/host-core/src/db/schema.rs
@@ -1,4 +1,33 @@
-pub(crate) const SCHEMA_LATEST: &str = r#"
+/// `session_todo` table and its partial unique index in one place, so the
+/// fresh schema and the v20 -> v21 migration cannot drift. `IF NOT EXISTS`
+/// keeps the migration idempotent for a database that was downgraded in
+/// place (a test fixture) while still being a no-op on an empty schema.
+macro_rules! session_todo_ddl {
+ () => {
+ r#"
+CREATE TABLE IF NOT EXISTS session_todo (
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
+ position INTEGER NOT NULL CHECK (position >= 0 AND position < 50),
+ content TEXT NOT NULL CHECK (
+ length(content) > 0 AND length(content) <= 500
+ AND instr(content, char(0)) = 0
+ ),
+ status TEXT NOT NULL CHECK (status IN ('pending', 'in_progress', 'completed', 'cancelled')),
+ priority TEXT NOT NULL DEFAULT 'medium' CHECK (priority IN ('high', 'medium', 'low')),
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY (session_id, position)
+);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_session_todo_active
+ ON session_todo(session_id) WHERE status = 'in_progress';
+"#
+ };
+}
+
+/// Same DDL as the fresh schema, exposed for the v20 -> v21 migration.
+pub(crate) const SESSION_TODO_DDL: &str = session_todo_ddl!();
+
+pub(crate) const SCHEMA_LATEST: &str = concat!(
+ r#"
CREATE TABLE kv (
ns TEXT NOT NULL,
key TEXT NOT NULL,
@@ -69,6 +98,8 @@ CREATE TABLE sessions (
deleted_at INTEGER,
pinned INTEGER NOT NULL DEFAULT 0,
last_seq INTEGER NOT NULL DEFAULT 0,
+ todo_revision INTEGER NOT NULL DEFAULT 0,
+ todo_updated_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
@@ -76,6 +107,10 @@ CREATE INDEX idx_sessions_updated ON sessions(updated_at DESC);
CREATE INDEX idx_sessions_project ON sessions(project_id) WHERE project_id IS NOT NULL;
CREATE INDEX idx_sessions_deleted ON sessions(deleted_at) WHERE deleted_at IS NOT NULL;
+"#,
+ session_todo_ddl!(),
+ r#"
+
CREATE TABLE session_import_origins (
plugin_id TEXT NOT NULL,
source_id TEXT NOT NULL,
@@ -240,7 +275,8 @@ CREATE TABLE audit_log (
CREATE INDEX idx_audit_ts ON audit_log(ts);
CREATE INDEX idx_audit_session ON audit_log(session_id, ts) WHERE session_id IS NOT NULL;
-"#;
+"#,
+);
/// Approval storage is kept in one batch so fresh databases and migrations
/// cannot drift in table names, checks, or indexes.
diff --git a/crates/host-core/src/db/tests.rs b/crates/host-core/src/db/tests.rs
index 25d5d8fd1..1c2081d01 100644
--- a/crates/host-core/src/db/tests.rs
+++ b/crates/host-core/src/db/tests.rs
@@ -122,6 +122,109 @@ fn v18_database_migrates_session_thinking_omit() {
assert!(sql.contains("'omit'"), "{sql}");
}
+/// v21 owns the session checklist. A real v20 database has neither the
+/// `sessions` stamps nor the `session_todo` table, so the upgrade must add
+/// both, keep the v20 rows, leave a readable pre-migration backup, and stay
+/// idempotent when a fixture downgrades the same file in place.
+#[test]
+fn v20_database_migrates_the_session_checklist_with_a_backup() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("pi.sqlite");
+ let session_id = {
+ let db = Database::open(&path).unwrap();
+ let session = crate::sessions::create_session(
+ &db,
+ Some("v20 session".into()),
+ Some("agent".into()),
+ None,
+ None,
+ None,
+ )
+ .unwrap();
+ db.conn()
+ .execute(
+ "INSERT INTO artifacts (session_id, path, op, updated_at)
+ VALUES (?1, 'kept.txt', 'write', 1)",
+ params![session.id],
+ )
+ .unwrap();
+ session.id
+ };
+
+ let downgrade_to_v20 = |path: &Path| {
+ let conn = Connection::open(path).unwrap();
+ conn.execute_batch(
+ "PRAGMA foreign_keys = OFF;
+ DROP TABLE IF EXISTS session_todo;
+ ALTER TABLE sessions DROP COLUMN todo_revision;
+ ALTER TABLE sessions DROP COLUMN todo_updated_at;
+ PRAGMA user_version = 20;",
+ )
+ .unwrap();
+ drop(conn);
+ };
+ downgrade_to_v20(&path);
+
+ let db = Database::open(&path).unwrap();
+ assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
+ assert!(table_exists(db.conn(), "session_todo"));
+ assert!(migration_backup_path(&path, 20).exists());
+ assert_readable_migration_backup(&path, 20);
+ let todo_columns: i64 = db
+ .conn()
+ .query_row(
+ "SELECT COUNT(*) FROM pragma_table_info('sessions')
+ WHERE name IN ('todo_revision', 'todo_updated_at')",
+ [],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(todo_columns, 2, "both v21 session stamps are present");
+ let (title, revision, updated_at): (String, i64, Option<i64>) = db
+ .conn()
+ .query_row(
+ "SELECT title, todo_revision, todo_updated_at FROM sessions WHERE id = ?1",
+ params![session_id],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ )
+ .unwrap();
+ assert_eq!(title, "v20 session");
+ assert_eq!(revision, 0, "a migrated session starts at revision zero");
+ assert!(updated_at.is_none());
+ let kept: String = db
+ .conn()
+ .query_row(
+ "SELECT path FROM artifacts WHERE session_id = ?1",
+ params![session_id],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(kept, "kept.txt");
+
+ // A second run over the same file, both with and without the v21 objects
+ // already in place, must not fail or duplicate anything.
+ drop(db);
+ downgrade_to_v20(&path);
+ let db = Database::open(&path).unwrap();
+ assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
+ assert!(table_exists(db.conn(), "session_todo"));
+ drop(db);
+ {
+ let conn = Connection::open(&path).unwrap();
+ conn.pragma_update(None, "user_version", 20).unwrap();
+ }
+ let db = Database::open(&path).unwrap();
+ assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
+ assert!(table_exists(db.conn(), "session_todo"));
+ assert_eq!(
+ db.conn()
+ .query_row("SELECT COUNT(*) FROM session_todo", [], |row| row
+ .get::<_, i64>(0))
+ .unwrap(),
+ 0
+ );
+}
+
fn schema_version(conn: &Connection) -> i64 {
conn.query_row("PRAGMA user_version", [], |row| row.get(0))
.unwrap()
@@ -195,6 +298,7 @@ fn fresh_open_creates_latest_schema() {
"audit_log",
"plan_approvals",
"session_import_origins",
+ "session_todo",
] {
assert!(table_exists(db.conn(), table), "missing {table}");
}
diff --git a/crates/host-core/src/main.rs b/crates/host-core/src/main.rs
index ceaf188cc..2330c3da0 100644
--- a/crates/host-core/src/main.rs
+++ b/crates/host-core/src/main.rs
@@ -24,6 +24,7 @@ mod session_collaboration;
mod session_search;
mod sessions;
mod state;
+mod todos;
mod tool_budget;
mod tools;
mod transcripts;
diff --git a/crates/host-core/src/permissions.rs b/crates/host-core/src/permissions.rs
index 2b983904c..7aac10890 100644
--- a/crates/host-core/src/permissions.rs
+++ b/crates/host-core/src/permissions.rs
@@ -121,7 +121,7 @@ pub struct PermissionManager {
impl PermissionManager {
pub fn tool_risk_with_declared(tool_name: &str, declared: Option<&str>) -> Risk {
match tool_name {
- "Read" | "Glob" | "Grep" | "ScheduledTaskList" => Risk::Low,
+ "Read" | "Glob" | "Grep" | "ScheduledTaskList" | "TodoWrite" => Risk::Low,
"Write" | "Edit" | "Bash" | "GenerateImages" => Risk::High,
name if name.starts_with("plugin_") => match declared {
Some("low") => Risk::Low,
@@ -590,6 +590,50 @@ mod tests {
}
}
+ /// TodoWrite is the session checklist: low risk, so the normal permission
+ /// modes never prompt for it inside Agent mode, and part of the contract
+ /// modes' hard deny — a Plan/Goal checklist is negotiated through the
+ /// proposal instead of written directly.
+ #[test]
+ fn todo_write_is_low_risk_in_agent_and_denied_in_contract_modes() {
+ let pm = PermissionManager::default();
+ assert!(matches!(
+ PermissionManager::tool_risk_with_declared("TodoWrite", None),
+ Risk::Low
+ ));
+ for mode in ["ask", "accept-edits", "auto"] {
+ assert_eq!(
+ pm.evaluate_auto_with_permission_mode(
+ "s",
+ "TodoWrite",
+ "agent",
+ mode,
+ &no_grants()
+ ),
+ Some(PermissionDecision::AllowOnce),
+ "agent + {mode}"
+ );
+ }
+ let mut grants = HashMap::new();
+ grants.insert("s".to_string(), vec!["TodoWrite".to_string()]);
+ for contract in ["plan", "goal"] {
+ for mode in ["ask", "accept-edits", "auto"] {
+ assert_eq!(
+ pm.evaluate_auto_with_permission_mode(
+ "s",
+ "TodoWrite",
+ contract,
+ mode,
+ &grants
+ ),
+ Some(PermissionDecision::Deny),
+ "{contract} + {mode} denies even with a session grant"
+ );
+ }
+ }
+ assert!(!PermissionManager::plan_mode_allows("TodoWrite"));
+ }
+
#[test]
fn external_paths_prompt_for_low_risk_tools_outside_auto() {
let pm = PermissionManager::default();
diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rs
index 7a12a88b4..9b6191f88 100644
--- a/crates/host-core/src/plugins/providers/tests.rs
+++ b/crates/host-core/src/plugins/providers/tests.rs
@@ -91,9 +91,9 @@ fn declaration_manifest(providers: Value, permissions: Value) -> Value {
#[test]
fn a_new_database_carries_the_owner_column_at_the_current_schema_version() {
let (_dir, db, _secrets) = test_context();
- // v17 added the owner column, v18 the turn-queue priority column, v19 session omit; a fresh
+ // v17 added the owner column, v18 the turn-queue priority column, v19 session omit, and v21 the session Todo checklist; a fresh
// database is stamped with the newest, so the column set is the current one.
- assert_eq!(SCHEMA_VERSION, 20);
+ assert_eq!(SCHEMA_VERSION, 21);
let version: i64 = db
.conn()
.query_row("PRAGMA user_version", [], |row| row.get(0))
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 8f68c32a3..2417ce829 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -1,6 +1,7 @@
mod config_sync_rpc;
mod scheduled_rpc;
mod scheduled_tools;
+mod todos;
use std::io::{self, BufRead, BufReader as StdBufReader, Read, Write};
use std::path::{Path, PathBuf};
@@ -2515,6 +2516,15 @@ async fn handle_request(
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
Ok(json!({ "session": session }))
}
+ "todos.get" => {
+ let session_id = params
+ .get("sessionId")
+ .and_then(Value::as_str)
+ .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_ARGUMENT"))?;
+ let st = state.lock().await;
+ todos::get_from(&st, session_id)
+ }
+
"session.configure" => {
let id = params
.get("id")
@@ -3976,7 +3986,11 @@ async fn handle_request(
});
}
- let mut result = if tools::is_desktop_dispatched(&p.tool_name) {
+ let mut result = if p.tool_name == "TodoWrite" {
+ // The checklist body owns its own trusted-transport checks,
+ // the atomic write, and the after-commit notification.
+ todos::execute_write(&state, &tx, &p, call_started).await?
+ } else if tools::is_desktop_dispatched(&p.tool_name) {
// Plugin and MCP dispatch has its own bounded default, sized
// to outlast Electron's budgets; command-shell timeout
// semantics apply only to Bash.
diff --git a/crates/host-core/src/rpc/todos.rs b/crates/host-core/src/rpc/todos.rs
new file mode 100644
index 000000000..7d1c78dc6
--- /dev/null
+++ b/crates/host-core/src/rpc/todos.rs
@@ -0,0 +1,758 @@
+//! Session checklist RPC surface: `todos.get` and the `TodoWrite` tool body.
+//!
+//! Kept beside — not inside — the shared dispatcher so `rpc::mod` stays a
+//! registration surface. Validation and persistence rules live in
+//! `crate::todos`; this module owns the wire shapes, the trusted-transport
+//! checks, and the after-commit `todos.changed` notification.
+
+use std::sync::Arc;
+use std::time::Instant;
+
+use serde_json::{json, Value};
+use tokio::sync::{mpsc, Mutex};
+
+use super::{emit_notification, rpc_err, AppState, JsonRpcError};
+use crate::todos::{self, TodoRefusal, TodoSnapshot, TodoWriteError};
+use crate::tools::{ToolsExecuteParams, ToolsExecuteResult};
+
+/// Prefix of the Node-owned native Pi transcript authority (ADR 0254). Those
+/// sessions live outside SQLite, so they can never own a Desktop checklist.
+const NATIVE_PI_SESSION_PREFIX: &str = "native-pi:";
+
+/// Longest `current:` excerpt carried in the tool result text. The model gets
+/// the summary and the active item; it never gets the whole list echoed back.
+const CURRENT_CONTENT_PREVIEW_CHARS: usize = 80;
+
+/// `todos.get`: the committed snapshot for one live session.
+pub fn get_from(state: &AppState, session_id: &str) -> Result<Value, JsonRpcError> {
+ validate_session_id(session_id)?;
+ let snapshot = todos::get(&state.db, session_id)
+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?
+ .ok_or_else(|| rpc_err(1007, "session not found", "NOT_FOUND"))?;
+ serde_json::to_value(snapshot).map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))
+}
+
+fn validate_session_id(session_id: &str) -> Result<(), JsonRpcError> {
+ if session_id.trim().is_empty() {
+ return Err(rpc_err(1002, "sessionId required", "INVALID_ARGUMENT"));
+ }
+ if session_id.starts_with(NATIVE_PI_SESSION_PREFIX) {
+ return Err(rpc_err(
+ 1002,
+ "native Pi sessions keep no Desktop checklist",
+ "INVALID_ARGUMENT",
+ ));
+ }
+ Ok(())
+}
+
+/// Execute one `TodoWrite` call.
+///
+/// The session and turn come from the trusted transport fields, never from
+/// `args`, and the write is re-authorized inside the storage transaction.
+/// [`todos::replace_for_turn`] returns only after the commit, so the
+/// `todos.changed` snapshot below is by construction the committed one and a
+/// refusal can never be observed as a state change.
+pub async fn execute_write(
+ state: &Arc<Mutex<AppState>>,
+ tx: &mpsc::UnboundedSender<String>,
+ p: &ToolsExecuteParams,
+ started: Instant,
+) -> Result<ToolsExecuteResult, JsonRpcError> {
+ // A delegate's call carries its definition's permission scope (ADR 0089),
+ // `inherit` included. The checklist belongs to the session's own turn, so
+ // a subagent call is refused rather than attributed to the parent.
+ if p.permission_scope.is_some() {
+ return Ok(refused(
+ p,
+ "TOOL_DENIED",
+ "TodoWrite is not available to delegated subagent calls",
+ true,
+ started,
+ ));
+ }
+
+ let normalized = match todos::normalize_input(&p.args) {
+ Ok(normalized) => normalized,
+ Err(error) => {
+ return Ok(refused(
+ p,
+ "INVALID_ARGUMENT",
+ &error.to_string(),
+ false,
+ started,
+ ))
+ }
+ };
+
+ let committed = {
+ let st = state.lock().await;
+ if st.shutting_down {
+ return Err(rpc_err(1001, "host is shutting down", "HOST_SHUTTING_DOWN"));
+ }
+ todos::replace_for_turn(&st.db, &p.session_id, p.turn_id.as_deref(), &normalized)
+ };
+ let snapshot = match committed {
+ Ok(snapshot) => snapshot,
+ Err(TodoWriteError::Refused(refusal)) => {
+ let (code, message, denied) = refusal_wire(refusal);
+ return Ok(refused(p, code, message, denied, started));
+ }
+ Err(TodoWriteError::Internal(error)) => {
+ return Err(rpc_err(1000, error.to_string(), "INTERNAL"))
+ }
+ };
+
+ let payload = serde_json::to_value(&snapshot)
+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;
+ emit_notification(tx, "todos.changed", payload).await;
+
+ let summary = summary_of(&snapshot);
+ // Identifiers, counts, and timing only: checklist text never reaches the
+ // log, the audit row, or the tool result summary beyond the bounded
+ // `current:` excerpt.
+ tracing::info!(
+ session_id = %snapshot.session_id,
+ turn_id = p.turn_id.as_deref().unwrap_or(""),
+ revision = snapshot.revision,
+ completed = summary.completed,
+ total = summary.total,
+ in_progress = summary.in_progress,
+ cancelled = summary.cancelled,
+ warnings = normalized.warnings.len(),
+ "session checklist updated"
+ );
+
+ Ok(success(
+ p,
+ &snapshot,
+ &summary,
+ &normalized.warnings,
+ started,
+ ))
+}
+
+fn refusal_wire(refusal: TodoRefusal) -> (&'static str, &'static str, bool) {
+ match refusal {
+ TodoRefusal::SessionNotFound => ("NOT_FOUND", "session not found", false),
+ TodoRefusal::SessionNotAgent => (
+ "TOOL_DISABLED_IN_PLAN",
+ "TodoWrite requires Agent mode",
+ true,
+ ),
+ TodoRefusal::TurnMissing => (
+ "TOOL_TURN_CANCELLED",
+ "TodoWrite requires the running turn of the calling session",
+ false,
+ ),
+ TodoRefusal::TurnNotRunning => (
+ "TOOL_TURN_CANCELLED",
+ "the calling turn is no longer running for this session",
+ false,
+ ),
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct TodoSummary {
+ completed: usize,
+ total: usize,
+ in_progress: usize,
+ cancelled: usize,
+}
+
+/// `total` counts the items that still matter, so a cancelled item is neither
+/// completed nor outstanding.
+fn summary_of(snapshot: &TodoSnapshot) -> TodoSummary {
+ let completed = snapshot
+ .todos
+ .iter()
+ .filter(|item| item.status == todos::STATUS_COMPLETED)
+ .count();
+ let in_progress = snapshot
+ .todos
+ .iter()
+ .filter(|item| item.status == todos::STATUS_IN_PROGRESS)
+ .count();
+ let cancelled = snapshot
+ .todos
+ .iter()
+ .filter(|item| item.status == todos::STATUS_CANCELLED)
+ .count();
+ TodoSummary {
+ completed,
+ total: snapshot.todos.len().saturating_sub(cancelled),
+ in_progress,
+ cancelled,
+ }
+}
+
+fn success(
+ p: &ToolsExecuteParams,
+ snapshot: &TodoSnapshot,
+ summary: &TodoSummary,
+ warnings: &[String],
+ started: Instant,
+) -> ToolsExecuteResult {
+ let mut text = format!(
+ "Checklist updated: {}/{} completed",
+ summary.completed, summary.total
+ );
+ if summary.cancelled > 0 {
+ text.push_str(&format!(", {} cancelled", summary.cancelled));
+ }
+ if let Some(current) = snapshot
+ .todos
+ .iter()
+ .find(|item| item.status == todos::STATUS_IN_PROGRESS)
+ {
+ text.push_str(&format!(
+ "; current: {}",
+ short_single_line(&current.content, CURRENT_CONTENT_PREVIEW_CHARS)
+ ));
+ }
+ for warning in warnings {
+ text.push_str(&format!(" [{warning}]"));
+ }
+
+ ToolsExecuteResult {
+ tool_call_id: p.tool_call_id.clone(),
+ ok: true,
+ is_error: None,
+ content: json!({
+ "text": text,
+ "revision": snapshot.revision,
+ "summary": {
+ "completed": summary.completed,
+ "total": summary.total,
+ "inProgress": summary.in_progress,
+ "cancelled": summary.cancelled,
+ },
+ "warnings": warnings,
+ }),
+ duration_ms: started.elapsed().as_millis() as u64,
+ denied: None,
+ error_code: None,
+ command_shell_id: None,
+ }
+}
+
+/// A concrete wire code for a refused call, with an explicit `isError` so a
+/// model sees a fixable tool error rather than a transport failure.
+fn refused(
+ p: &ToolsExecuteParams,
+ code: &str,
+ message: &str,
+ denied: bool,
+ started: Instant,
+) -> ToolsExecuteResult {
+ ToolsExecuteResult {
+ tool_call_id: p.tool_call_id.clone(),
+ ok: false,
+ is_error: Some(true),
+ content: json!({ "error": message, "code": code }),
+ duration_ms: started.elapsed().as_millis() as u64,
+ denied: denied.then_some(true),
+ error_code: Some(code.to_string()),
+ command_shell_id: None,
+ }
+}
+
+/// Collapse whitespace and clip, so one newline-heavy item cannot inflate the
+/// tool result past its single-line contract.
+fn short_single_line(content: &str, max_chars: usize) -> String {
+ let mut collapsed = String::with_capacity(content.len().min(max_chars));
+ let mut in_whitespace = false;
+ for character in content.chars() {
+ if character.is_whitespace() {
+ in_whitespace = true;
+ continue;
+ }
+ if in_whitespace && !collapsed.is_empty() {
+ collapsed.push(' ');
+ }
+ in_whitespace = false;
+ collapsed.push(character);
+ }
+ if collapsed.chars().count() <= max_chars {
+ return collapsed;
+ }
+ let mut clipped: String = collapsed
+ .chars()
+ .take(max_chars.saturating_sub(1))
+ .collect();
+ clipped.push('…');
+ clipped
+}
+
+#[cfg(test)]
+mod tests {
+ use std::fs;
+
+ use super::super::{handle_request, AppState, JsonRpcError};
+ use super::*;
+ use crate::sessions;
+ use serde_json::json;
+
+ /// One host state with a single notification channel, so every event the
+ /// calls below emit lands in one ordered stream.
+ struct Harness {
+ state: Arc<Mutex<AppState>>,
+ tx: mpsc::UnboundedSender<String>,
+ rx: mpsc::UnboundedReceiver<String>,
+ _data_dir: tempfile::TempDir,
+ }
+
+ impl Harness {
+ fn new() -> Self {
+ let data_dir = tempfile::tempdir().unwrap();
+ fs::create_dir_all(data_dir.path().join("project")).unwrap();
+ let mut app_state = AppState::open(data_dir.path()).unwrap();
+ app_state.handshook = true;
+ let (tx, rx) = mpsc::unbounded_channel();
+ Self {
+ state: Arc::new(Mutex::new(app_state)),
+ tx,
+ rx,
+ _data_dir: data_dir,
+ }
+ }
+
+ async fn call(&self, method: &str, params: Value) -> Result<Value, JsonRpcError> {
+ handle_request(self.state.clone(), method, params, self.tx.clone()).await
+ }
+
+ async fn session(&self, mode: &str) -> String {
+ let st = self.state.lock().await;
+ sessions::create_session(
+ &st.db,
+ Some("todos".into()),
+ Some(mode.into()),
+ None,
+ None,
+ None,
+ )
+ .unwrap()
+ .id
+ }
+
+ async fn begin_turn(&self, session_id: &str) -> String {
+ let st = self.state.lock().await;
+ sessions::begin_turn(&st.db, session_id, None, None).unwrap()
+ }
+
+ async fn snapshot(&self, session_id: &str) -> Value {
+ self.call("todos.get", json!({ "sessionId": session_id }))
+ .await
+ .unwrap()
+ }
+
+ /// Every notification emitted since the last drain.
+ fn events(&mut self) -> Vec<Value> {
+ let mut seen = Vec::new();
+ while let Ok(raw) = self.rx.try_recv() {
+ seen.push(serde_json::from_str(&raw).unwrap());
+ }
+ seen
+ }
+ }
+
+ fn write_call(session_id: &str, turn_id: &str, args: Value) -> Value {
+ json!({
+ "sessionId": session_id,
+ "turnId": turn_id,
+ "toolCallId": "todo-1",
+ "toolName": "TodoWrite",
+ "args": args,
+ "mode": "agent"
+ })
+ }
+
+ fn items(contents: &[&str]) -> Value {
+ json!({
+ "todos": contents
+ .iter()
+ .map(|content| json!({"content": content, "status": "pending"}))
+ .collect::<Vec<_>>()
+ })
+ }
+
+ fn assert_refused(result: &Value, code: &str) {
+ assert_eq!(result["ok"], json!(false), "{result}");
+ assert_eq!(result["isError"], json!(true), "{result}");
+ assert_eq!(result["errorCode"], json!(code), "{result}");
+ }
+
+ #[tokio::test]
+ async fn todo_write_commits_and_emits_the_committed_snapshot_once() {
+ let mut harness = Harness::new();
+ let session_id = harness.session("agent").await;
+ let turn_id = harness.begin_turn(&session_id).await;
+
+ let result = harness
+ .call(
+ "tools.execute",
+ write_call(
+ &session_id,
+ &turn_id,
+ json!({"todos": [
+ {"content": "done", "status": "completed"},
+ {"content": "now", "status": "in_progress", "priority": "high"},
+ {"content": "dropped", "status": "cancelled"}
+ ]}),
+ ),
+ )
+ .await
+ .unwrap();
+ assert_eq!(result["ok"], json!(true), "{result}");
+ assert!(result.get("isError").is_none(), "{result}");
+ assert_eq!(result["content"]["revision"], json!(1));
+ assert_eq!(
+ result["content"]["summary"],
+ json!({"completed": 1, "total": 2, "inProgress": 1, "cancelled": 1})
+ );
+ assert_eq!(result["content"]["warnings"], json!([]));
+ let text = result["content"]["text"].as_str().unwrap();
+ assert!(text.contains("1/2 completed"), "{text}");
+ assert!(text.contains("current: now"), "{text}");
+ // The result carries a summary, never the whole checklist.
+ assert!(!text.contains("dropped"), "{text}");
+
+ let emitted = harness.events();
+ assert_eq!(emitted.len(), 1, "{emitted:?}");
+ assert_eq!(emitted[0]["method"], json!("todos.changed"));
+ assert_eq!(emitted[0]["params"]["sessionId"], json!(session_id));
+ assert_eq!(emitted[0]["params"]["revision"], json!(1));
+ assert_eq!(emitted[0]["params"]["todos"].as_array().unwrap().len(), 3);
+ assert!(emitted[0]["params"]["updatedAt"].as_i64().unwrap() > 0);
+
+ // The event is exactly the committed snapshot: the read path agrees.
+ assert_eq!(harness.snapshot(&session_id).await, emitted[0]["params"]);
+
+ // A full replacement of the same list still advances the revision, so
+ // a consumer can tell the two writes apart.
+ let replaced = harness
+ .call(
+ "tools.execute",
+ write_call(
+ &session_id,
+ &turn_id,
+ json!({"todos": [{"content": "done", "status": "completed"}]}),
+ ),
+ )
+ .await
+ .unwrap();
+ assert_eq!(replaced["content"]["revision"], json!(2));
+ assert_eq!(
+ replaced["content"]["summary"],
+ json!({"completed": 1, "total": 1, "inProgress": 0, "cancelled": 0})
+ );
+ assert_eq!(harness.events().len(), 1);
+ }
+
+ #[tokio::test]
+ async fn todo_write_reports_truncation_and_demotion_warnings() {
+ let mut harness = Harness::new();
+ let session_id = harness.session("agent").await;
+ let turn_id = harness.begin_turn(&session_id).await;
+ let long = "日".repeat(todos::MAX_TODO_CONTENT_CHARS + 5);
+
+ let result = harness
+ .call(
+ "tools.execute",
+ write_call(
+ &session_id,
+ &turn_id,
+ json!({"todos": [
+ {"content": long, "status": "in_progress"},
+ {"content": "multiline\nlater", "status": "in_progress"}
+ ]}),
+ ),
+ )
+ .await
+ .unwrap();
+ assert_eq!(result["ok"], json!(true), "{result}");
+ let warnings = result["content"]["warnings"].as_array().unwrap();
+ assert_eq!(warnings.len(), 2, "{warnings:?}");
+ assert!(warnings[0].as_str().unwrap().contains("truncated"));
+ assert!(warnings[1].as_str().unwrap().contains("pending"));
+ let text = result["content"]["text"].as_str().unwrap();
+ assert!(!text.contains('\n'), "{text}");
+ assert!(text.chars().count() < 400, "bounded text: {text}");
+
+ let emitted = harness.events();
+ assert_eq!(emitted.len(), 1);
+ let stored = emitted[0]["params"]["todos"].as_array().unwrap();
+ assert_eq!(
+ stored[0]["content"].as_str().unwrap().chars().count(),
+ todos::MAX_TODO_CONTENT_CHARS
+ );
+ assert_eq!(stored[1]["status"], json!("pending"));
+ // Stored content keeps its own line breaks after trimming; only the
+ // tool result text is collapsed to one line.
+ assert_eq!(stored[1]["content"], json!("multiline\nlater"));
+ }
+
+ #[tokio::test]
+ async fn refusals_never_mutate_and_never_emit() {
+ let mut harness = Harness::new();
+ let session_id = harness.session("agent").await;
+ let turn_id = harness.begin_turn(&session_id).await;
+
+ let first = harness
+ .call(
+ "tools.execute",
+ write_call(&session_id, &turn_id, items(&["kept"])),
+ )
+ .await
+ .unwrap();
+ assert_eq!(first["ok"], json!(true), "{first}");
+ assert_eq!(harness.events().len(), 1);
+ let baseline = harness.snapshot(&session_id).await;
+
+ // Invalid payloads are refused before anything is read or written.
+ for args in [
+ json!({"todos": [{"content": "x", "status": "nope"}]}),
+ json!({"todos": [{"content": "x", "status": "pending", "priority": 1}]}),
+ json!({"todos": [{"content": "x", "status": "pending", "priority": null}]}),
+ json!({"todos": [{"content": " ", "status": "pending"}]}),
+ json!({"todos": [], "sessionId": "other-session"}),
+ json!({"todos": vec![json!({"content": "x", "status": "pending"});
+ todos::MAX_TODOS + 1]}),
+ ] {
+ let result = harness
+ .call("tools.execute", write_call(&session_id, &turn_id, args))
+ .await
+ .unwrap();
+ assert_refused(&result, "INVALID_ARGUMENT");
+ assert!(harness.events().is_empty(), "a refusal emits nothing");
+ assert_eq!(harness.snapshot(&session_id).await, baseline);
+ }
+ }
+
+ #[tokio::test]
+ async fn the_checklist_requires_agent_mode_and_an_owned_running_turn() {
+ let mut harness = Harness::new();
+ let session_id = harness.session("agent").await;
+ let turn_id = harness.begin_turn(&session_id).await;
+
+ // A missing, unknown, foreign, or ended turn is refused.
+ let mut missing = write_call(&session_id, "", items(&["x"]));
+ missing.as_object_mut().unwrap().remove("turnId");
+ assert_refused(
+ &harness.call("tools.execute", missing).await.unwrap(),
+ "TOOL_TURN_CANCELLED",
+ );
+ for turn in ["unknown-turn", "another-turn"] {
+ assert_refused(
+ &harness
+ .call(
+ "tools.execute",
+ write_call(&session_id, turn, items(&["x"])),
+ )
+ .await
+ .unwrap(),
+ "TOOL_TURN_CANCELLED",
+ );
+ }
+ let ended = harness.session("agent").await;
+ let ended_turn = harness.begin_turn(&ended).await;
+ {
+ let st = harness.state.lock().await;
+ sessions::end_turn(&st.db, &ended_turn, "completed", None, None, false).unwrap();
+ }
+ assert_refused(
+ &harness
+ .call(
+ "tools.execute",
+ write_call(&ended, &ended_turn, items(&["x"])),
+ )
+ .await
+ .unwrap(),
+ "TOOL_TURN_CANCELLED",
+ );
+ // Another session's running turn cannot be borrowed.
+ let other = harness.session("agent").await;
+ let other_turn = harness.begin_turn(&other).await;
+ assert_refused(
+ &harness
+ .call(
+ "tools.execute",
+ write_call(&session_id, &other_turn, items(&["x"])),
+ )
+ .await
+ .unwrap(),
+ "TOOL_TURN_CANCELLED",
+ );
+ assert!(harness.events().is_empty(), "no refusal emitted an event");
+ assert_eq!(harness.snapshot(&session_id).await["revision"], json!(0));
+
+ // A delegated call carries a permission scope, `inherit` included.
+ for scope in ["inherit", "auto", "ask"] {
+ let mut delegated = write_call(&session_id, &turn_id, items(&["x"]));
+ delegated["permissionScope"] = json!(scope);
+ assert_refused(
+ &harness.call("tools.execute", delegated).await.unwrap(),
+ "TOOL_DENIED",
+ );
+ }
+ assert!(harness.events().is_empty());
+
+ // Plan and Goal are denied no matter the permission mode, until the
+ // approved session switches to agent.
+ for mode in ["plan", "goal"] {
+ let contract = harness.session(mode).await;
+ assert_refused(
+ &harness
+ .call(
+ "tools.execute",
+ write_call(&contract, "contract-turn", items(&["x"])),
+ )
+ .await
+ .unwrap(),
+ "TOOL_DISABLED_IN_PLAN",
+ );
+ assert!(harness.events().is_empty(), "no event in {mode}");
+
+ {
+ let st = harness.state.lock().await;
+ sessions::configure_session_with_thinking(
+ &st.db,
+ &contract,
+ "agent",
+ None,
+ None,
+ None,
+ Some("auto"),
+ )
+ .unwrap();
+ }
+ let switched_turn = harness.begin_turn(&contract).await;
+ let allowed = harness
+ .call(
+ "tools.execute",
+ write_call(&contract, &switched_turn, items(&["approved"])),
+ )
+ .await
+ .unwrap();
+ assert_eq!(allowed["ok"], json!(true), "{allowed}");
+ assert_eq!(harness.events().len(), 1, "the switch is observable");
+ }
+
+ // A running agent turn still commits.
+ let committed = harness
+ .call(
+ "tools.execute",
+ write_call(&session_id, &turn_id, items(&["real"])),
+ )
+ .await
+ .unwrap();
+ assert_eq!(committed["ok"], json!(true), "{committed}");
+ }
+
+ #[tokio::test]
+ async fn todos_get_rejects_unknown_deleted_and_native_sessions() {
+ let harness = Harness::new();
+ let session_id = harness.session("agent").await;
+
+ let unknown = harness
+ .call("todos.get", json!({"sessionId": "missing"}))
+ .await
+ .unwrap_err();
+ assert_eq!(unknown.data.unwrap()["errorCode"], "NOT_FOUND");
+
+ for invalid in ["", " "] {
+ let empty = harness
+ .call("todos.get", json!({"sessionId": invalid}))
+ .await
+ .unwrap_err();
+ assert_eq!(empty.data.unwrap()["errorCode"], "INVALID_ARGUMENT");
+ }
+
+ let native = harness
+ .call("todos.get", json!({"sessionId": "native-pi:abc"}))
+ .await
+ .unwrap_err();
+ assert_eq!(native.data.unwrap()["errorCode"], "INVALID_ARGUMENT");
+
+ {
+ let st = harness.state.lock().await;
+ st.db
+ .conn()
+ .execute(
+ "UPDATE sessions SET deleted_at = 1 WHERE id = ?1",
+ [session_id.as_str()],
+ )
+ .unwrap();
+ }
+ let deleted = harness
+ .call("todos.get", json!({"sessionId": session_id}))
+ .await
+ .unwrap_err();
+ assert_eq!(deleted.data.unwrap()["errorCode"], "NOT_FOUND");
+
+ // A live session that never wrote one reports an empty list at
+ // revision zero.
+ let fresh = harness.session("agent").await;
+ let fetched = harness.snapshot(&fresh).await;
+ assert_eq!(fetched["todos"], json!([]));
+ assert_eq!(fetched["revision"], json!(0));
+ assert_eq!(fetched["updatedAt"], json!(0));
+ }
+
+ #[tokio::test]
+ async fn the_checklist_is_session_scoped_and_has_no_public_setter() {
+ let mut harness = Harness::new();
+ let first = harness.session("agent").await;
+ let first_turn = harness.begin_turn(&first).await;
+ let second = harness.session("agent").await;
+ let second_turn = harness.begin_turn(&second).await;
+ for (session, turn, content) in [
+ (first.clone(), first_turn, "first item"),
+ (second.clone(), second_turn, "second item"),
+ ] {
+ let result = harness
+ .call(
+ "tools.execute",
+ write_call(&session, &turn, items(&[content])),
+ )
+ .await
+ .unwrap();
+ assert_eq!(result["ok"], json!(true), "{result}");
+ }
+ let first_snapshot = harness.snapshot(&first).await;
+ assert_eq!(first_snapshot["todos"][0]["content"], json!("first item"));
+ assert_eq!(first_snapshot["revision"], json!(1));
+ let second_snapshot = harness.snapshot(&second).await;
+ assert_eq!(second_snapshot["todos"][0]["content"], json!("second item"));
+
+ // `todos.set` was never registered: the only writer is the tool.
+ let set = harness
+ .call("todos.set", json!({"sessionId": second, "todos": []}))
+ .await
+ .unwrap_err();
+ assert_eq!(set.code, -32601);
+ assert_eq!(set.data.unwrap()["errorCode"], "NOT_FOUND");
+ // Drain the two committed snapshots, then prove the unknown method
+ // added nothing.
+ assert_eq!(harness.events().len(), 2);
+ assert!(harness.events().is_empty());
+
+ // `tools.list` advertises the tool with the low-risk declaration and
+ // a strictly bounded argument object.
+ let listed = harness.call("tools.list", json!({})).await.unwrap();
+ let todo = listed["tools"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|tool| tool["name"] == json!("TodoWrite"))
+ .expect("TodoWrite is advertised");
+ assert_eq!(todo["risk"], json!("low"));
+ assert_eq!(todo["parameters"]["required"], json!(["todos"]));
+ assert_eq!(todo["parameters"]["additionalProperties"], json!(false));
+ assert_eq!(
+ todo["parameters"]["properties"]["todos"]["maxItems"],
+ json!(50)
+ );
+ }
+}
diff --git a/crates/host-core/src/todos.rs b/crates/host-core/src/todos.rs
new file mode 100644
index 000000000..bf10b37f6
--- /dev/null
+++ b/crates/host-core/src/todos.rs
@@ -0,0 +1,763 @@
+//! Session checklist: validation, storage, and the single write path.
+//!
+//! `session_todo` rows plus the `sessions.todo_revision` / `todo_updated_at`
+//! stamps are the authoritative checklist; host-core SQLite is the only
+//! writer. `TodoWrite` replaces the whole list in one transaction, so no
+//! reader can observe a half-applied list, and an empty list still advances
+//! the revision so a clear stays distinguishable from "nothing happened".
+
+use anyhow::{anyhow, Result};
+use rusqlite::{params, OptionalExtension, Transaction};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use crate::db::{now_ms, Database};
+
+/// Hard cap on one checklist, mirrored by the `session_todo` CHECK.
+pub const MAX_TODOS: usize = 50;
+/// Longest accepted item content in Unicode scalar values. Longer content is
+/// truncated with a warning instead of rejected: a model that writes a
+/// paragraph should still make progress, while the stored row stays bounded.
+pub const MAX_TODO_CONTENT_CHARS: usize = 500;
+
+pub const STATUS_PENDING: &str = "pending";
+pub const STATUS_IN_PROGRESS: &str = "in_progress";
+pub const STATUS_COMPLETED: &str = "completed";
+pub const STATUS_CANCELLED: &str = "cancelled";
+
+pub const PRIORITY_HIGH: &str = "high";
+pub const PRIORITY_MEDIUM: &str = "medium";
+pub const PRIORITY_LOW: &str = "low";
+
+/// Keep in sync with the `session_todo` CHECK constraints in
+/// `crate::db::schema::SESSION_TODO_DDL`.
+pub const TODO_STATUSES: [&str; 4] = [
+ STATUS_PENDING,
+ STATUS_IN_PROGRESS,
+ STATUS_COMPLETED,
+ STATUS_CANCELLED,
+];
+pub const TODO_PRIORITIES: [&str; 3] = [PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW];
+
+/// The only argument `TodoWrite` accepts. The owner session and turn come
+/// from the transport, so anything else — `sessionId` included — is refused
+/// rather than ignored.
+const TODOS_ARG: &str = "todos";
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct TodoItem {
+ pub content: String,
+ pub status: String,
+ pub priority: String,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct TodoSnapshot {
+ pub session_id: String,
+ pub todos: Vec<TodoItem>,
+ /// Monotonic per-session counter; `0` means the session never wrote one.
+ pub revision: i64,
+ /// Epoch ms of the last successful write, `0` before the first write.
+ pub updated_at: i64,
+}
+
+#[derive(Debug, Clone)]
+pub struct NormalizedTodos {
+ pub items: Vec<TodoItem>,
+ /// Bounded, single-line notes for the model and the tool result. They
+ /// never carry a whole checklist, only what was changed about the input.
+ pub warnings: Vec<String>,
+}
+
+/// Why a `TodoWrite` must not commit. The RPC layer maps each variant to one
+/// wire `errorCode`; a refusal never mutates and never emits an event.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TodoRefusal {
+ /// Unknown session, or a row already marked deleted.
+ SessionNotFound,
+ /// The durable mode is not `agent` (Plan/Goal never own a checklist).
+ SessionNotAgent,
+ /// The call carried no `turnId`.
+ TurnMissing,
+ /// The turn is unknown, belongs to another session, or is no longer
+ /// running.
+ TurnNotRunning,
+}
+
+#[derive(Debug)]
+pub enum TodoWriteError {
+ Refused(TodoRefusal),
+ Internal(anyhow::Error),
+}
+
+impl std::fmt::Display for TodoWriteError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Refused(refusal) => write!(f, "{refusal:?}"),
+ Self::Internal(error) => write!(f, "{error}"),
+ }
+ }
+}
+
+impl From<rusqlite::Error> for TodoWriteError {
+ fn from(error: rusqlite::Error) -> Self {
+ Self::Internal(error.into())
+ }
+}
+
+/// Validate and normalize one `TodoWrite` payload.
+///
+/// Rejections are total: nothing here touches the database, so an invalid
+/// payload can never leave a partial replacement behind. Content is trimmed,
+/// must be non-empty, must not contain NUL, and is truncated to
+/// [`MAX_TODO_CONTENT_CHARS`] with a warning. Only the first `in_progress`
+/// item survives; later ones are demoted to `pending`.
+pub fn normalize_input(value: &Value) -> Result<NormalizedTodos> {
+ let object = value
+ .as_object()
+ .ok_or_else(|| anyhow!("TodoWrite arguments must be an object"))?;
+ if let Some(unknown) = object.keys().find(|key| key.as_str() != TODOS_ARG) {
+ return Err(anyhow!(
+ "TodoWrite does not accept the `{unknown}` argument; the owner session and turn come from the transport"
+ ));
+ }
+ let todos = object
+ .get(TODOS_ARG)
+ .ok_or_else(|| anyhow!("TodoWrite requires a todos array"))?
+ .as_array()
+ .ok_or_else(|| anyhow!("TodoWrite.todos must be an array"))?;
+ if todos.len() > MAX_TODOS {
+ return Err(anyhow!(
+ "TodoWrite accepts at most {MAX_TODOS} items, got {}",
+ todos.len()
+ ));
+ }
+
+ let mut truncated = 0usize;
+ let mut items = Vec::with_capacity(todos.len());
+ for (index, item) in todos.iter().enumerate() {
+ let (item, was_truncated) = normalize_item(item, index)?;
+ if was_truncated {
+ truncated += 1;
+ }
+ items.push(item);
+ }
+
+ let mut warnings = Vec::new();
+ if truncated > 0 {
+ warnings.push(format!(
+ "{truncated} item(s) were truncated to {MAX_TODO_CONTENT_CHARS} characters"
+ ));
+ }
+ if let Some(first) = items
+ .iter()
+ .position(|item| item.status == STATUS_IN_PROGRESS)
+ {
+ let mut demoted = false;
+ for item in items.iter_mut().skip(first + 1) {
+ if item.status == STATUS_IN_PROGRESS {
+ item.status = STATUS_PENDING.to_string();
+ demoted = true;
+ }
+ }
+ if demoted {
+ warnings.push(
+ "only the first in_progress item is kept; later ones became pending".to_string(),
+ );
+ }
+ }
+
+ Ok(NormalizedTodos { items, warnings })
+}
+
+fn normalize_item(value: &Value, index: usize) -> Result<(TodoItem, bool)> {
+ let object = value
+ .as_object()
+ .ok_or_else(|| anyhow!("todos[{index}] must be an object"))?;
+ let content = object
+ .get("content")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("todos[{index}].content must be a string"))?
+ .trim();
+ if content.is_empty() {
+ return Err(anyhow!("todos[{index}].content must not be empty"));
+ }
+ if content.contains('\0') {
+ return Err(anyhow!(
+ "todos[{index}].content must not contain NUL characters"
+ ));
+ }
+ let (content, truncated) = if content.chars().count() > MAX_TODO_CONTENT_CHARS {
+ let clipped: String = content.chars().take(MAX_TODO_CONTENT_CHARS).collect();
+ (clipped, true)
+ } else {
+ (content.to_string(), false)
+ };
+
+ let status = object
+ .get("status")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("todos[{index}].status must be a string"))?;
+ if !TODO_STATUSES.contains(&status) {
+ return Err(anyhow!(
+ "todos[{index}].status must be one of {}",
+ TODO_STATUSES.join(", ")
+ ));
+ }
+
+ // A missing priority defaults to medium; an explicitly non-string or
+ // unknown priority is a mistake the model can fix, not something to
+ // silently repair.
+ let priority = match object.get("priority") {
+ None => PRIORITY_MEDIUM,
+ Some(Value::String(priority)) if TODO_PRIORITIES.contains(&priority.as_str()) => {
+ priority.as_str()
+ }
+ Some(_) => {
+ return Err(anyhow!(
+ "todos[{index}].priority must be one of {}",
+ TODO_PRIORITIES.join(", ")
+ ));
+ }
+ };
+
+ Ok((
+ TodoItem {
+ content,
+ status: status.to_string(),
+ priority: priority.to_string(),
+ },
+ truncated,
+ ))
+}
+
+/// Read the committed snapshot for a live session. `None` covers both an
+/// unknown id and a row already marked deleted; the caller decides which wire
+/// error that is.
+pub fn get(db: &Database, session_id: &str) -> Result<Option<TodoSnapshot>> {
+ let tx = db.conn().unchecked_transaction()?;
+ let snapshot = read_tx(&tx, session_id)?;
+ // A deferred read transaction holds one snapshot across the revision row
+ // and the item rows, so a concurrent replace cannot pair an old list with
+ // a new revision.
+ drop(tx);
+ Ok(snapshot)
+}
+
+fn read_tx(tx: &Transaction<'_>, session_id: &str) -> Result<Option<TodoSnapshot>> {
+ let session: Option<(i64, Option<i64>)> = tx
+ .query_row(
+ "SELECT todo_revision, todo_updated_at FROM sessions
+ WHERE id = ?1 AND deleted_at IS NULL",
+ params![session_id],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .optional()?;
+ let Some((revision, updated_at)) = session else {
+ return Ok(None);
+ };
+ let mut stmt = tx.prepare(
+ "SELECT content, status, priority FROM session_todo
+ WHERE session_id = ?1 ORDER BY position ASC",
+ )?;
+ let todos = stmt
+ .query_map(params![session_id], |row| {
+ Ok(TodoItem {
+ content: row.get(0)?,
+ status: row.get(1)?,
+ priority: row.get(2)?,
+ })
+ })?
+ .collect::<rusqlite::Result<Vec<_>>>()?;
+ Ok(Some(TodoSnapshot {
+ session_id: session_id.to_string(),
+ todos,
+ revision,
+ updated_at: updated_at.unwrap_or(0),
+ }))
+}
+
+/// Replace a session's checklist from one `TodoWrite` call.
+///
+/// The session's live state, its durable `agent` mode, and the owning running
+/// turn are re-read *inside* the writing transaction. Permission evaluation,
+/// the user's approval, and tool admission all await between the RPC entry
+/// point and this call, so anything that authorized the call may have moved
+/// on: a soft-deleted session, a switched mode, or an ended turn must not
+/// still be able to write.
+///
+/// The item replacement and the `todo_revision` / `todo_updated_at` bump share
+/// one transaction, so a failed write cannot advance the revision.
+pub fn replace_for_turn(
+ db: &Database,
+ session_id: &str,
+ turn_id: Option<&str>,
+ normalized: &NormalizedTodos,
+) -> Result<TodoSnapshot, TodoWriteError> {
+ let tx = db.conn().unchecked_transaction()?;
+ let snapshot = replace_tx(&tx, session_id, turn_id, normalized)?;
+ tx.commit()?;
+ Ok(snapshot)
+}
+
+fn replace_tx(
+ tx: &Transaction<'_>,
+ session_id: &str,
+ turn_id: Option<&str>,
+ normalized: &NormalizedTodos,
+) -> Result<TodoSnapshot, TodoWriteError> {
+ let session: Option<(String, Option<i64>)> = tx
+ .query_row(
+ "SELECT mode, deleted_at FROM sessions WHERE id = ?1",
+ params![session_id],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .optional()?;
+ let Some((mode, deleted_at)) = session else {
+ return Err(TodoWriteError::Refused(TodoRefusal::SessionNotFound));
+ };
+ if deleted_at.is_some() {
+ return Err(TodoWriteError::Refused(TodoRefusal::SessionNotFound));
+ }
+ if crate::sessions::normalize_mode(Some(&mode)) != "agent" {
+ return Err(TodoWriteError::Refused(TodoRefusal::SessionNotAgent));
+ }
+
+ let Some(turn_id) = turn_id else {
+ return Err(TodoWriteError::Refused(TodoRefusal::TurnMissing));
+ };
+ let turn_status: Option<String> = tx
+ .query_row(
+ "SELECT status FROM turns WHERE id = ?1 AND session_id = ?2",
+ params![turn_id, session_id],
+ |row| row.get(0),
+ )
+ .optional()?;
+ if turn_status.as_deref() != Some("running") {
+ return Err(TodoWriteError::Refused(TodoRefusal::TurnNotRunning));
+ }
+
+ let now = now_ms();
+ let revision: i64 = tx.query_row(
+ "UPDATE sessions SET todo_revision = todo_revision + 1, todo_updated_at = ?2
+ WHERE id = ?1 RETURNING todo_revision",
+ params![session_id, now],
+ |row| row.get(0),
+ )?;
+ tx.execute(
+ "DELETE FROM session_todo WHERE session_id = ?1",
+ params![session_id],
+ )?;
+ for (position, item) in normalized.items.iter().enumerate() {
+ tx.execute(
+ "INSERT INTO session_todo
+ (session_id, position, content, status, priority, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
+ params![
+ session_id,
+ position as i64,
+ item.content,
+ item.status,
+ item.priority,
+ now
+ ],
+ )?;
+ }
+ Ok(TodoSnapshot {
+ session_id: session_id.to_string(),
+ todos: normalized.items.clone(),
+ revision,
+ updated_at: now,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::sessions;
+ use serde_json::json;
+
+ fn db() -> Database {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.keep().join("pi.sqlite");
+ Database::open(&path).unwrap()
+ }
+
+ fn session(db: &Database) -> String {
+ sessions::create_session(db, Some("todos".into()), None, None, None, None)
+ .unwrap()
+ .id
+ }
+
+ fn normalized(value: Value) -> NormalizedTodos {
+ normalize_input(&value).unwrap()
+ }
+
+ fn write(db: &Database, session_id: &str, value: Value) -> TodoSnapshot {
+ let turn = sessions::begin_turn(db, session_id, None, None).unwrap();
+ let snapshot = replace_for_turn(db, session_id, Some(&turn), &normalized(value)).unwrap();
+ sessions::end_turn(db, &turn, "completed", None, None, false).unwrap();
+ snapshot
+ }
+
+ #[test]
+ fn normalization_trims_defaults_priority_and_keeps_only_one_active_item() {
+ let normalized = normalize_input(&json!({
+ "todos": [
+ {"content": " first ", "status": "in_progress"},
+ {"content": "second", "status": "in_progress", "priority": "high"}
+ ]
+ }))
+ .unwrap();
+ assert_eq!(normalized.items[0].content, "first");
+ assert_eq!(normalized.items[0].priority, PRIORITY_MEDIUM);
+ assert_eq!(normalized.items[1].status, STATUS_PENDING);
+ assert_eq!(normalized.items[1].priority, PRIORITY_HIGH);
+ assert_eq!(normalized.warnings.len(), 1);
+ assert!(normalized.warnings[0].contains("in_progress"));
+ }
+
+ #[test]
+ fn normalization_truncates_over_long_unicode_content_with_a_warning() {
+ let over = "日".repeat(MAX_TODO_CONTENT_CHARS + 1);
+ let normalized = normalize_input(&json!({
+ "todos": [{"content": over, "status": "pending"}]
+ }))
+ .unwrap();
+ assert_eq!(
+ normalized.items[0].content.chars().count(),
+ MAX_TODO_CONTENT_CHARS
+ );
+ assert_eq!(normalized.warnings.len(), 1);
+ assert!(normalized.warnings[0].contains("truncated"));
+
+ // The boundary itself is kept verbatim: exactly 500 characters is not
+ // over the limit.
+ let exact = "日".repeat(MAX_TODO_CONTENT_CHARS);
+ let normalized = normalize_input(&json!({
+ "todos": [{"content": exact, "status": "pending"}]
+ }))
+ .unwrap();
+ assert_eq!(
+ normalized.items[0].content.chars().count(),
+ MAX_TODO_CONTENT_CHARS
+ );
+ assert!(normalized.warnings.is_empty());
+ // Multi-byte content must not be measured in bytes.
+ assert_eq!(normalized.items[0].content, exact);
+ }
+
+ #[test]
+ fn normalization_rejects_invalid_payloads_without_a_partial_list() {
+ for value in [
+ json!({}),
+ json!({"todos": "nope"}),
+ json!({"todos": [{"content": " ", "status": "pending"}]}),
+ json!({"todos": [{"content": "nul\0here", "status": "pending"}]}),
+ json!({"todos": [{"content": 7, "status": "pending"}]}),
+ json!({"todos": [{"content": "x"}]}),
+ json!({"todos": [{"content": "x", "status": "doing"}]}),
+ json!({"todos": [{"content": "x", "status": "pending", "priority": null}]}),
+ json!({"todos": [{"content": "x", "status": "pending", "priority": 3}]}),
+ json!({"todos": [{"content": "x", "status": "pending", "priority": "urgent"}]}),
+ ] {
+ assert!(
+ normalize_input(&value).is_err(),
+ "payload must be rejected: {value}"
+ );
+ }
+
+ // Arguments the transport owns are refused instead of ignored.
+ for value in [
+ json!({"todos": [], "sessionId": "other"}),
+ json!({"todos": [], "turnId": "other"}),
+ ] {
+ let error = normalize_input(&value).unwrap_err().to_string();
+ assert!(error.contains("does not accept"), "{error}");
+ }
+
+ // 51 items is over the cap; 50 items is exactly the cap.
+ let item = json!({"content": "task", "status": "pending"});
+ let over = json!({"todos": vec![item.clone(); MAX_TODOS + 1]});
+ assert!(normalize_input(&over).is_err());
+ let at_cap = json!({"todos": vec![item; MAX_TODOS]});
+ assert_eq!(normalize_input(&at_cap).unwrap().items.len(), MAX_TODOS);
+ }
+
+ #[test]
+ fn replace_preserves_order_and_clearing_advances_the_revision() {
+ let db = db();
+ let session_id = session(&db);
+ let snapshot = write(
+ &db,
+ &session_id,
+ json!({"todos": [
+ {"content": "one", "status": "pending"},
+ {"content": "two", "status": "in_progress"},
+ {"content": "three", "status": "cancelled", "priority": "low"}
+ ]}),
+ );
+ assert_eq!(snapshot.revision, 1);
+ assert!(snapshot.updated_at > 0);
+ let stored = get(&db, &session_id).unwrap().unwrap();
+ assert_eq!(
+ stored
+ .todos
+ .iter()
+ .map(|item| item.content.as_str())
+ .collect::<Vec<_>>(),
+ vec!["one", "two", "three"]
+ );
+ assert_eq!(stored.todos[2].priority, PRIORITY_LOW);
+
+ let cleared = write(&db, &session_id, json!({"todos": []}));
+ assert_eq!(cleared.revision, 2);
+ assert!(cleared.todos.is_empty());
+ assert!(get(&db, &session_id).unwrap().unwrap().todos.is_empty());
+
+ let replaced = write(
+ &db,
+ &session_id,
+ json!({"todos": [{"content": "only", "status": "pending"}]}),
+ );
+ assert_eq!(replaced.revision, 3);
+ assert_eq!(get(&db, &session_id).unwrap().unwrap().todos.len(), 1);
+ }
+
+ #[test]
+ fn checklist_survives_a_restart() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("pi.sqlite");
+ let session_id = {
+ let db = Database::open(&path).unwrap();
+ let session_id = session(&db);
+ write(
+ &db,
+ &session_id,
+ json!({"todos": [{"content": "durable", "status": "completed"}]}),
+ );
+ session_id
+ };
+ let reopened = Database::open(&path).unwrap();
+ let stored = get(&reopened, &session_id).unwrap().unwrap();
+ assert_eq!(stored.revision, 1);
+ assert_eq!(stored.todos[0].content, "durable");
+ assert_eq!(stored.todos[0].status, STATUS_COMPLETED);
+ }
+
+ #[test]
+ fn a_failure_inside_the_transaction_rolls_back_items_and_revision() {
+ let db = db();
+ let session_id = session(&db);
+ write(
+ &db,
+ &session_id,
+ json!({"todos": [{"content": "keep", "status": "pending"}]}),
+ );
+ // Injected mid-transaction failure: the second inserted row aborts, so
+ // the delete, the revision bump, and the first insert must all roll
+ // back together.
+ db.conn()
+ .execute_batch(
+ "CREATE TRIGGER fail_second_item BEFORE INSERT ON session_todo
+ WHEN NEW.position = 1
+ BEGIN SELECT RAISE(ABORT, 'injected failure'); END;",
+ )
+ .unwrap();
+ let turn = sessions::begin_turn(&db, &session_id, None, None).unwrap();
+ let error = replace_for_turn(
+ &db,
+ &session_id,
+ Some(&turn),
+ &normalized(json!({"todos": [
+ {"content": "first", "status": "pending"},
+ {"content": "second", "status": "pending"}
+ ]})),
+ )
+ .unwrap_err();
+ assert!(matches!(error, TodoWriteError::Internal(_)), "{error}");
+ db.conn()
+ .execute_batch("DROP TRIGGER fail_second_item")
+ .unwrap();
+
+ let stored = get(&db, &session_id).unwrap().unwrap();
+ assert_eq!(stored.revision, 1);
+ assert_eq!(stored.todos.len(), 1);
+ assert_eq!(stored.todos[0].content, "keep");
+ }
+
+ #[test]
+ fn deleting_a_session_cascades_its_checklist_and_spares_its_neighbour() {
+ let db = db();
+ let first = session(&db);
+ let second = session(&db);
+ write(
+ &db,
+ &first,
+ json!({"todos": [{"content": "first", "status": "pending"}]}),
+ );
+ write(
+ &db,
+ &second,
+ json!({"todos": [{"content": "second", "status": "pending"}]}),
+ );
+
+ assert!(sessions::delete_session(&db, &first).unwrap());
+ assert!(get(&db, &first).unwrap().is_none());
+ let stored = get(&db, &second).unwrap().unwrap();
+ assert_eq!(stored.todos.len(), 1);
+ assert_eq!(stored.todos[0].content, "second");
+ for orphan in ["session_todo", "turns"] {
+ let count: i64 = db
+ .conn()
+ .query_row(&format!("SELECT COUNT(*) FROM {orphan}"), [], |row| {
+ row.get(0)
+ })
+ .unwrap();
+ assert_eq!(count, 1, "{orphan} kept exactly the surviving session");
+ }
+ }
+
+ #[test]
+ fn a_forked_session_starts_empty_at_revision_zero() {
+ let db = db();
+ let source = session(&db);
+ write(
+ &db,
+ &source,
+ json!({"todos": [{"content": "source item", "status": "pending"}]}),
+ );
+ let sessions::ForkSessionResult::Created(child) =
+ sessions::fork_session_through(&db, &source, None, None).unwrap()
+ else {
+ panic!("expected a forked session");
+ };
+
+ let fork = get(&db, &child.summary.id).unwrap().unwrap();
+ assert!(fork.todos.is_empty());
+ assert_eq!(fork.revision, 0);
+ assert_eq!(fork.updated_at, 0);
+ // The source keeps its own list and revision.
+ assert_eq!(get(&db, &source).unwrap().unwrap().revision, 1);
+ }
+
+ /// The refusal behind a failed write. `TodoWriteError` carries an
+ /// `anyhow::Error`, which is not comparable, so tests compare the
+ /// authorization outcome instead.
+ fn refusal(error: TodoWriteError) -> TodoRefusal {
+ match error {
+ TodoWriteError::Refused(refusal) => refusal,
+ TodoWriteError::Internal(error) => panic!("expected a refusal, got {error}"),
+ }
+ }
+
+ #[test]
+ fn writes_are_refused_for_ineligible_sessions_and_turns() {
+ let db = db();
+ let agent = session(&db);
+ let turn = sessions::begin_turn(&db, &agent, None, None).unwrap();
+ let payload = normalized(json!({"todos": [{"content": "x", "status": "pending"}]}));
+
+ // Unknown session.
+ assert_eq!(
+ refusal(replace_for_turn(&db, "missing", Some(&turn), &payload).unwrap_err()),
+ TodoRefusal::SessionNotFound
+ );
+ // Plan and Goal never write a checklist.
+ for mode in ["plan", "goal"] {
+ let planned = sessions::create_session(
+ &db,
+ Some("plan".into()),
+ Some(mode.into()),
+ None,
+ None,
+ None,
+ )
+ .unwrap();
+ let planned_turn = sessions::begin_turn(&db, &planned.id, None, None).unwrap();
+ assert_eq!(
+ refusal(
+ replace_for_turn(&db, &planned.id, Some(&planned_turn), &payload).unwrap_err()
+ ),
+ TodoRefusal::SessionNotAgent
+ );
+ }
+ // Missing, unknown, foreign, and ended turns are all refusals.
+ assert_eq!(
+ refusal(replace_for_turn(&db, &agent, None, &payload).unwrap_err()),
+ TodoRefusal::TurnMissing
+ );
+ assert_eq!(
+ refusal(replace_for_turn(&db, &agent, Some("unknown-turn"), &payload).unwrap_err()),
+ TodoRefusal::TurnNotRunning
+ );
+ let other = session(&db);
+ let other_turn = sessions::begin_turn(&db, &other, None, None).unwrap();
+ assert_eq!(
+ refusal(replace_for_turn(&db, &agent, Some(&other_turn), &payload).unwrap_err()),
+ TodoRefusal::TurnNotRunning
+ );
+ sessions::end_turn(&db, &turn, "completed", None, None, false).unwrap();
+ assert_eq!(
+ refusal(replace_for_turn(&db, &agent, Some(&turn), &payload).unwrap_err()),
+ TodoRefusal::TurnNotRunning
+ );
+ // Nothing above mutated anything.
+ assert!(get(&db, &agent).unwrap().unwrap().todos.is_empty());
+ assert_eq!(get(&db, &agent).unwrap().unwrap().revision, 0);
+
+ // A soft-deleted session is as unavailable as an unknown one.
+ db.conn()
+ .execute(
+ "UPDATE sessions SET deleted_at = ?2 WHERE id = ?1",
+ params![other, now_ms()],
+ )
+ .unwrap();
+ assert!(get(&db, &other).unwrap().is_none());
+ assert_eq!(
+ refusal(replace_for_turn(&db, &other, Some(&other_turn), &payload).unwrap_err()),
+ TodoRefusal::SessionNotFound
+ );
+ }
+
+ #[test]
+ fn the_database_rejects_out_of_contract_rows() {
+ let db = db();
+ let session_id = session(&db);
+ let insert = |content: &str, position: i64, status: &str, priority: &str| {
+ db.conn()
+ .execute(
+ "INSERT INTO session_todo
+ (session_id, position, content, status, priority, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, 1)",
+ params![session_id, position, content, status, priority],
+ )
+ .map(|_| ())
+ };
+ assert!(insert("ok", 0, "pending", "medium").is_ok());
+ assert!(insert("", 1, "pending", "medium").is_err());
+ assert!(insert("nul\0byte", 2, "pending", "medium").is_err());
+ assert!(insert(
+ &"x".repeat(MAX_TODO_CONTENT_CHARS + 1),
+ 3,
+ "pending",
+ "medium"
+ )
+ .is_err());
+ assert!(insert("x", -1, "pending", "medium").is_err());
+ assert!(insert("x", MAX_TODOS as i64, "pending", "medium").is_err());
+ assert!(insert("x", 4, "done", "medium").is_err());
+ assert!(insert("x", 5, "pending", "urgent").is_err());
+ // The partial unique index keeps a single active item even for a write
+ // that never went through normalization.
+ assert!(insert("active", 6, "in_progress", "medium").is_ok());
+ assert!(insert("second active", 7, "in_progress", "medium").is_err());
+ let count: i64 = db
+ .conn()
+ .query_row("SELECT COUNT(*) FROM session_todo", [], |row| row.get(0))
+ .unwrap();
+ assert_eq!(count, 2);
+ }
+}
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rs
index 3ff3d7d57..b5dd7a5ce 100644
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@ -2802,6 +2802,35 @@ pub fn builtin_tool_defs() -> Value {
"required": ["pattern"]
}
},
+ {
+ "name": "TodoWrite",
+ "description": "Replace the current session's task checklist in display order, so the user can follow multi-step work. \
+ Send `{ todos: [...] }`; every call replaces the whole list (at most 50 items) and an empty array clears it. \
+ At most one item may be `in_progress` — later ones become `pending`; content is trimmed, must be non-empty, and is truncated at 500 characters. \
+ The owner session and turn come from the transport, so any other argument is rejected.",
+ "risk": "low",
+ "parameters": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "todos": {
+ "type": "array",
+ "maxItems": 50,
+ "description": "The full checklist in display order",
+ "items": {
+ "type": "object",
+ "properties": {
+ "content": { "type": "string", "minLength": 1, "maxLength": 500 },
+ "status": { "type": "string", "enum": ["pending", "in_progress", "completed", "cancelled"] },
+ "priority": { "type": "string", "enum": ["high", "medium", "low"], "description": "Defaults to medium" }
+ },
+ "required": ["content", "status"]
+ }
+ }
+ },
+ "required": ["todos"]
+ }
+ },
{
"name": "Write",
"description": "Create or overwrite a file inside the workspace or the session scratch directory. Strips a pasted `[path#TAG]` header and `N:` line prefixes. Returns the post-write `tag` so a following Edit needs no extra Read.",
diff --git a/crates/host-core/src/turn_queue.rs b/crates/host-core/src/turn_queue.rs
index 91d3b2546..83d1278dd 100644
--- a/crates/host-core/src/turn_queue.rs
+++ b/crates/host-core/src/turn_queue.rs
@@ -492,7 +492,7 @@ mod tests {
assert_eq!(entries[0].content, "existing");
assert!(entries[0].user_message_id.is_none());
assert!(entries[0].voice_origin.is_none());
- assert_eq!(crate::db::SCHEMA_VERSION, 20);
+ assert_eq!(crate::db::SCHEMA_VERSION, 21);
}
#[test]
diff --git a/docs/adr/0312-session-scoped-todo-checklist.md b/docs/adr/0312-session-scoped-todo-checklist.md
new file mode 100644
index 000000000..2ddaca72b
--- /dev/null
+++ b/docs/adr/0312-session-scoped-todo-checklist.md
@@ -0,0 +1,49 @@
+# ADR 0312: Session-scoped Todo checklist
+
+- Status: Accepted for implementation
+- Date: 2026-09-29
+- Deciders: PI-Desktop maintainers
+- Related: Issue #1177
+
+## Context
+
+Multi-step Agent work needs a durable, session-scoped progress checklist that can
+be shown to the user without making the renderer a second source of truth. The
+checklist must remain ordered, survive restart, and be isolated from Plan/Goal
+contract negotiation and delegated subagent calls.
+
+## Decision
+
+`TodoWrite` is an Agent-only builtin tool. Its arguments contain the complete
+ordered checklist and are validated by host-core. The host owns persistence in
+SQLite schema v21: `session_todo` stores the rows, while `sessions.todo_revision`
+and `sessions.todo_updated_at` order both populated and empty snapshots. Each
+write replaces the rows and increments the revision in one transaction.
+
+The tool call is authorized against the calling session and its running turn
+inside that transaction. The host emits `todos.changed` only after commit and
+serves the complete committed snapshot through `todos.get`. Electron Main
+forwards the notification through the existing IPC bridge, and the renderer
+keeps snapshots keyed by session id while rejecting stale revisions.
+
+The Composer TodoDock is a non-focusing, session-aware presentation surface.
+It shows bounded progress and at most eight ordered rows. Remote RACP sessions
+remain local-only for this vertical slice because RACP v1 has no Todo snapshot
+operation; the renderer skips local recovery for those session ids rather than
+reading the local database.
+
+## Consequences
+
+- Empty checklist writes remain observable through revision advancement.
+- Session deletion cascades checklist rows; forks start with an empty checklist.
+- Plan, Goal, delegated, plugin, and MCP execution paths cannot write the
+ checklist through this contract.
+- Context-compaction injection is deliberately deferred to a follow-up change.
+- Remote Todo parity requires an additive RACP contract in a later change.
+
+## Verification
+
+Host-core tests cover migration, validation, transaction rollback, restart,
+revision ordering, fork isolation, cascade deletion, and RPC authorization.
+Renderer type checks and TodoDock interaction tests cover revision filtering,
+remote-session degradation, session switching, expansion, and bounded display.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 8f773020e..881c2b2cd 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -342,6 +342,7 @@ Each ADR includes:
| 0309 | [Remove bundled macOS first-launch guidance](0309-remove-macos-first-launch-artifacts.md) | Accepted (D634; amends D457 / ADR 0296) |
| 0310 | [Keep local permission approvals pending until resolved](0310-local-permission-approvals-without-deadline.md) | Accepted for implementation |
| 0311 | [Recheck Live Work workspace identity at Host admission](0311-live-work-workspace-admission-guard.md) | Implemented candidate |
+| 0312 | [Session-scoped Todo checklist](0312-session-scoped-todo-checklist.md) | Accepted for implementation |
| turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |
| provider-display-order | [Provider display order](provider-display-order.md) | Accepted |
| registry-header-variable-spelling | [Remote header variables accept the registry's `{name}` spelling](registry-header-variable-spelling.md) | Proposed |
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index c787cc578..f693070d9 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -40,6 +40,7 @@ Let the agent get things done, but stay under control by default.
| `Edit` | high | Modify files through line-anchored ops against a verified `tag` ([18](18-line-anchored-edit-contract.md)) |
| `Bash` | high | Execute commands |
| `asktool` | low | Ask one or more user questions and return the submitted answers as tool output |
+| `TodoWrite` | low | Replace the current Agent session checklist; host validates and persists the full ordered snapshot |
> Names may be fine-tuned during implementation, but semantics stay consistent.
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index 89539f836..6cb98bfae 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -704,6 +704,32 @@ CREATE UNIQUE INDEX idx_turn_queue_idempotency
until a controller attaches, and drains one entry after the active turn's
terminal event. Deleting the session cascades to its entries.
+**Session Todo checklist — schema v21**
+
+```sql
+CREATE TABLE session_todo (
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
+ position INTEGER NOT NULL CHECK (position >= 0 AND position < 50),
+ content TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('pending', 'in_progress', 'completed', 'cancelled')),
+ priority TEXT NOT NULL DEFAULT 'medium' CHECK (priority IN ('high', 'medium', 'low')),
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY (session_id, position)
+);
+```
+
+`sessions.todo_revision` and `sessions.todo_updated_at` retain ordering metadata
+even when the checklist is empty. A host transaction updates those fields,
+deletes the prior rows, and inserts the normalized replacement. The revision
+advances for every successful write, including a clear. A unique partial
+`in_progress` index enforces the single active item invariant at the database
+boundary. Forks begin with revision zero and no rows; session deletion cascades
+the rows.
+
+The row content is bounded at 500 Unicode scalar values, contains no NUL, and
+is trimmed before storage. TodoWrite is the only writer; renderer and sidecar
+code access this state through host RPC.
+
### 4.6c session collaboration ledger — Host-owned delivery state (schema v16)
```sql
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index b53f7f1b4..64b4e79a6 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -489,6 +489,28 @@ oversized/deep payloads. Tool values are sanitized for host-reserved keys. The
per-plugin rolling limits are 10 single imports, 5 batch imports, and 20
deletes per 60 seconds. P2/P3 methods are not present in protocol v11.
+### Session Todo checklist
+
+- `todos.get({ sessionId })` returns the committed checklist snapshot for a live
+ Desktop session: `{ sessionId, todos, revision, updatedAt }`. Unknown or
+ soft-deleted sessions return `NOT_FOUND`; native Pi sessions and blank ids are
+ rejected as `INVALID_ARGUMENT`.
+- `tools.execute` with `toolName: "TodoWrite"` accepts only `{ todos }` and
+ replaces the complete ordered checklist. The host trims content, defaults
+ priority to `medium`, truncates overlong Unicode content at 500 characters
+ with a warning, demotes later `in_progress` items to `pending`, and rejects
+ more than 50 items or malformed values. The owner session and running turn
+ come from the trusted transport fields, never from tool arguments.
+- TodoWrite is allowed only for an Agent session's own running turn. Plan/Goal,
+ delegated, plugin, and MCP calls receive a tool result error and do not mutate
+ storage. A successful replacement advances the session revision even when
+ `todos` is empty and emits `todos.changed` after the transaction commits.
+ The event payload is the same complete snapshot returned by `todos.get`.
+- SQLite ownership is host-core only. The renderer receives snapshots through
+ Electron Main IPC, keeps them by session id, and ignores revisions older than
+ or equal to the cached revision. Remote RACP sessions are local-only for this
+ vertical slice because RACP v1 has no Todo snapshot operation.
+
### Stats
- `stats.getTokenUsageHistory` — roll up completed `turns` token columns and
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index e01df056a..955c034a4 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -2830,6 +2830,23 @@ reasoning-level control.
file-reference names), expose independent Remove and Send now actions, and
increase the dock height measured by `--composer-dock-height`.
+### 11.3a Session TodoDock
+
+- The Composer stack places TodoDock above Plan/Goal approval surfaces when the
+ active session has a non-empty host-owned checklist. An empty checklist does
+ not reserve layout space.
+- The collapsed header shows completed/active progress and the current
+ `in_progress` content. A checklist whose items are all cancelled has a clear
+ cancelled label instead of a misleading `0/0 completed` count.
+- The disclosure is keyboard accessible, does not take focus on updates, resets
+ closed when the active session changes, and shows at most eight ordered rows.
+ Each status symbol has a localized accessible name and each row renders plain
+ text content.
+- Renderer snapshots are keyed by session id. A `todos.changed` event with an
+ older or equal revision is ignored. The initial `todos.get` recovery is
+ skipped for `remote:` sessions because remote Todo parity is deferred until an
+ additive RACP contract exists.
+
### 11.4 States
| State | Appearance | Actions |
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index d1a3fc9c9..e79aa62e0 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8862,10 +8862,39 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
`pnpm test:e2e:settings-scroll`; full renderer-driven password persistence
assertions and checkpoint-level local recovery fault injection remain.
+**E2E-CHAT-session-todo-checklist: TodoWrite to session-aware TodoDock**
+
+- **Preconditions**: An isolated local Electron profile with a deterministic
+ Agent/host fixture, two Desktop sessions, and no real provider or paid API.
+- **Steps**: Start a multi-step Agent turn that calls `TodoWrite` with ordered
+ pending and `in_progress` items. Observe the TodoDock above the Composer,
+ expand it, switch sessions, and confirm the checklist stays session-scoped.
+ Complete and cancel items, confirm the bounded eight-row display and the
+ all-cancelled label, then clear the checklist and reload/restart the host.
+ Deliver an out-of-order older `todos.changed` event and confirm it cannot
+ replace the newer snapshot. Exercise invalid payload, Plan/Goal, delegated,
+ and remote-session paths.
+- **Expected**: Host SQLite is authoritative; each successful full replacement
+ advances revision, including clear, and emits one committed `todos.changed`
+ snapshot. Invalid or unauthorized writes do not mutate or emit. TodoDock
+ renders plain text, does not take focus, resets expansion on session changes,
+ rejects stale events, and skips local recovery for `remote:` sessions because
+ RACP v1 has no Todo snapshot operation.
+- **Specs**: `03-runtime/03-tools-and-permissions.md`,
+ `03-runtime/04-data-storage.md`, `03-runtime/06-host-rpc-protocol.md`,
+ `04-ux/08-component-spec.md`, ADR 0310.
+- **Acceptance**: C / E / F / Quality / Security.
+- **Milestone**: M6+.
+- **Status**: Targeted automated coverage is present in host-core and
+ `apps/desktop/test/todo-dock-rendering.test.mjs` plus
+ `todo-events.test.mjs`. Full Electron process/restart journey remains a
+ candidate validation gate.
+
## 8. Traceability Matrix
| Acceptance | Scenarios |
|---|---|
+| C / E / F / Quality / Security — Session Todo checklist | E2E-CHAT-session-todo-checklist |
| C / F — Hourly task updates | E2E-SCHEDULED-manual-to-hourly |
| C / F / Quality — Saved project isolation | E2E-SCHEDULED-manual-workspace-binding |
| C / F / Quality — Desktop automations | E2E-SCHEDULED-desktop-automation-lifecycle |
diff --git a/docs/zh-CN/adr/index.md b/docs/zh-CN/adr/index.md
index bfc3906e4..b9ebb811e 100644
--- a/docs/zh-CN/adr/index.md
+++ b/docs/zh-CN/adr/index.md
@@ -306,7 +306,9 @@ ADR 记录那些不应被静默改变的架构选择。中文入口与英文索
| 0298 | [应用不再随包发布任何字体](/adr/0298-remove-bundled-fonts) | 已接受(D598;修订 ADR 0083 / D232) |
| 0308 | [移除拉取请求页面与列表工具](/adr/0308-remove-pull-requests-destination) | 已接受 |
| 0309 | [移除 macOS 首次启动辅助文件](/adr/0309-remove-macos-first-launch-artifacts) | 已接受(D634;修订 D457 / ADR 0296) |
+| 0310 | [保持本地权限批准一直待解决](/adr/0310-local-permission-approvals-without-deadline) | 已接受实施 |
| 0311 | [在 Host 受理时重新核验 Live Work 工作空间身份](/adr/0311-live-work-workspace-admission-guard) | 已实现候选 |
+| 0312 | [会话级 Todo 清单](/adr/0312-session-scoped-todo-checklist) | 已接受实施 |
| registry-header-variable-spelling | [Remote header variables accept the registry's `{name}` spelling](/adr/registry-header-variable-spelling) | Proposed |
## 什么时候看 ADR
diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
index d7916aeb0..86c7aac57 100644
--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
@@ -43,6 +43,7 @@
| `Edit` | 高 | 通过针对已校验 `tag` 的行锚定操作修改文件([18](18-line-anchored-edit-contract.md)) |
| `Bash` | 高 | 执行命令 |
| `asktool` | 低 | 询问一个或多个用户问题并将提交的答案作为工具输出返回 |
+| `TodoWrite` | 低 | 替换当前 Agent 会话清单;由主机校验并持久化完整有序快照 |
> 名称可以在实现过程中进行微调,但语义保持一致。
diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.md
index fd210ac79..01323ff6a 100644
--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md
+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md
@@ -591,6 +591,28 @@ CREATE UNIQUE INDEX idx_turn_queue_idempotency
- 重启后模块列出全部条目,把每个会话的队列挂起到 controller 接入,并在活动回合终止事件
之后释放一条。删除会话会级联删除其条目。
+**会话 Todo 清单——存储架构 v21**
+
+```sql
+CREATE TABLE session_todo (
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
+ position INTEGER NOT NULL CHECK (position >= 0 AND position < 50),
+ content TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('pending', 'in_progress', 'completed', 'cancelled')),
+ priority TEXT NOT NULL DEFAULT 'medium' CHECK (priority IN ('high', 'medium', 'low')),
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY (session_id, position)
+);
+```
+
+`sessions.todo_revision` 和 `sessions.todo_updated_at` 即使清单为空也保留顺序元数据。
+主机事务会更新这些字段、删除旧行并插入归一化后的替换清单;每次成功写入都会推进
+revision,包括清空。唯一的部分 `in_progress` 索引在数据库边界保证只有一个活动项。
+分叉会话从 revision 0 和空清单开始;删除会话会级联删除清单行。
+
+行内容在存储前会裁剪空白,限制为 500 个 Unicode 标量值且不得包含 NUL。
+TodoWrite 是唯一写入方;渲染器和 sidecar 只能通过 host RPC 访问该状态。
+
### 4.6c 会话协作 ledger —— 宿主拥有的投递状态(架构 v16)
```sql
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.md
index 242668a2b..1e0d5d4ad 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
@@ -336,6 +336,20 @@ ids 和非负 `tokensBefore`;它不会插入 message/search 行
工具值会清理主机保留键。每个插件每 60 秒最多 10 次单条导入、5 次批量导入和
20 次删除。P2/P3 方法不在协议 v11 中。
+**会话 Todo 清单**
+- `todos.get({ sessionId })` 返回活动 Desktop 会话已提交的完整清单快照:
+ `{ sessionId, todos, revision, updatedAt }`。未知或软删除会话返回 `NOT_FOUND`;
+ 原生 Pi 会话和空 id 返回 `INVALID_ARGUMENT`。
+- `tools.execute` 的 `toolName: "TodoWrite"` 只接受 `{ todos }`,并替换整个有序清单。
+ 主机会裁剪内容、将 priority 默认设为 `medium`,把超长 Unicode 内容限制在 500 个字符并
+ 返回警告,把后续 `in_progress` 降级为 `pending`,并拒绝超过 50 项或格式错误的值。
+ 所属 session 和运行中的 turn 来自可信传输字段,不来自工具参数。
+- TodoWrite 只允许 Agent 会话自己的运行 turn。Plan/Goal、委托、插件和 MCP 调用会返回工具错误,
+ 不会修改存储。成功替换即使 `todos` 为空也会推进 revision,并且只在事务提交后发出
+ `todos.changed`;事件负载与 `todos.get` 返回的完整快照一致。
+- SQLite 只由 host-core 拥有。渲染器通过 Electron Main IPC 接收快照,按 session id 保存并忽略
+ 更旧或相同 revision。远程 RACP 会话在这条垂直切片中保持 local-only,因为 RACP v1 尚无 Todo 快照操作。
+
### Plan 和 Goal 状态和批准
两种合约类型共享这些方法;可选的 `kind`
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index 4b1e3e1c1..9ff84e2ea 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -2000,8 +2000,14 @@ MainChat 底部的输入区域,用于撰写和发送提示。支持多行输
不再绑定焦点、草稿或 IME 状态的计时器。可见文案通过带 key 的透明度渐变切换,
同时保留 textarea 原生 `placeholder` 值以支持辅助技术。
-### 11.4 状态
+**11.3a 会话 TodoDock**
+
+- 当活动会话拥有非空的主机清单时,TodoDock 位于 Composer 栈中并显示在 Plan/Goal 批准表面上方;空清单不占布局空间。
+- 收起标题显示完成/活动进度和当前 `in_progress` 内容;全部取消时显示明确的取消状态,不显示误导性的 `0/0 completed`。
+- 展开控件可键盘操作,不因更新抢焦点;切换活动会话时保持收起,最多显示八条有序行。每个状态符号都有本地化辅助名称,行内容按纯文本渲染。
+- 渲染器按 session id 保存快照并忽略旧或相同 revision。对于 `remote:` 会话跳过本地 `todos.get` 恢复,远程 Todo 对等能力留待新增 RACP 契约。
+### 11.4 状态
| 状态 | 外观 | 行动 |
|---|---|---|
| 闲置(无模型) | 文本区域处于活动状态,发送按钮已禁用 + 工具提示“首先配置模型” | 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.md
index b18bd949c..32ccffe22 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
@@ -5400,15 +5400,20 @@ eleven-tool-round desktop paths are verified by
确认来源仍为 Responses 和原别名,副本保存了 Anthropic Messages 与新
别名。未测试携带凭据的网络发现、外部模型请求及 OpenCode Go UI 分支。
-## 8. 可追溯性矩阵
-
-
-
-
+**E2E-CHAT-session-todo-checklist:TodoWrite 到按会话显示的 TodoDock**
+- **前提:** 隔离的本地 Electron 配置、确定性的 Agent/Host fixture、两个 Desktop 会话,不使用真实 Provider 或付费 API。
+- **步骤:** 启动调用 `TodoWrite` 的多步骤 Agent 回合,观察 Composer 上方的 TodoDock,展开后切换会话并确认清单隔离。完成和取消条目,确认最多显示八条以及全部取消状态;清空清单后重载/重启 Host。发送乱序旧 `todos.changed` 事件,确认它不能覆盖新快照;再覆盖非法参数、Plan/Goal、委托和远程会话路径。
+- **预期:** Host SQLite 是权威状态;每次成功全量替换(包括清空)都会推进 revision 并只发出一次已提交的 `todos.changed`。非法或未授权写入既不修改也不发事件。TodoDock 渲染纯文本、不抢焦点、切换会话时收起、拒绝旧事件,并对 `remote:` 会话跳过本地恢复,因为 RACP v1 没有 Todo 快照操作。
+- **链接规格:** `03-runtime/03-tools-and-permissions.md`、`03-runtime/04-data-storage.md`、`03-runtime/06-host-rpc-protocol.md`、`04-ux/08-component-spec.md`、ADR 0310。
+- **验收:** C / E / F / Quality / Security。
+- **里程碑:** M6+。
+- **状态:** Host-core、`apps/desktop/test/todo-dock-rendering.test.mjs` 和 `todo-events.test.mjs` 已有定向自动化覆盖;完整 Electron 进程/重启旅程仍是候选验证门。
+## 8. 可追溯性矩阵
| 验收 | 应用场景 |
|---|---|
+| C / E / F / Quality / Security — Session Todo checklist | E2E-CHAT-session-todo-checklist |
| C / F — Hourly task updates | E2E-SCHEDULED-manual-to-hourly |
| C / F / Quality — Saved project isolation | E2E-SCHEDULED-manual-workspace-binding |
| C / F / Quality — 桌面定时任务 | E2E-SCHEDULED-desktop-automation-lifecycle |
diff --git a/packages/agent-runtime/src/mode-prompts.ts b/packages/agent-runtime/src/mode-prompts.ts
index 332fb0680..7dbac8aac 100644
--- a/packages/agent-runtime/src/mode-prompts.ts
+++ b/packages/agent-runtime/src/mode-prompts.ts
@@ -31,6 +31,7 @@ export const GOAL_MODE_SYSTEM_PROMPT = [
export const AGENT_MODE_SYSTEM_PROMPT = [
"You are operating in Agent mode. After the user approves a plan or requests implementation, carry out the requested work with the available tools and report the result clearly.",
+ "For multi-step work, keep the user's session checklist current with TodoWrite. Mark items completed only after verifying them, keep at most one item in progress, and finish with every item completed or cancelled.",
].join("\n");
export function composeModeSystemPrompt(
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 27bc3a9e2..8d68bf294 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -2927,6 +2927,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
return `Replace, insert, or delete lines in an existing file. Names positions and supplies new content only — never old_string. Required: path, tag (4 hex from the latest Read/Grep/Write/Edit), ops. Ops: PUT N.=M: replace inclusive lines N–M; PUT <N: insert before N; PUT >N: insert after N; PUT >$: append; CUT N.=M delete; REM delete the file; MV DEST rename after other ops. Body rows are + plus the final line text. Every PUT with body rows must include the trailing colon, for example PUT 48.=48:; PUT 48.=48 followed by + rows is invalid. A colonless PUT is only for a register paste such as PUT <1 @name. No -old or context rows. Ranges name only the lines being changed. Re-ground on the tag returned by every successful write. After one failed Edit, classify the error: Read the live file for a stale tag or unseen lines (or retry unchanged on a complete EDIT_LINES_UNSEEN reveal), but correct syntax or range errors directly; do not guess. Do not edit the same path concurrently.${scratchPathHint}${externalPathHint}`;
case "Bash":
return `${commandShellToolDescription(this.commandShell, this.scratchDir)} Use Edit or Write instead of apply_patch, git apply, or patch; do not retry a failed shell patch command repeatedly.`;
+ case "TodoWrite":
+ return "Write the task checklist for the current session so the user can see progress on multi-step work. Use for work that needs 3+ distinct steps or spans multiple files/subsystems; do not use for a single-step action, a question, a read, or a review. Every call replaces the full list in display order. States are pending, in_progress, completed, and cancelled; only one item may be in_progress. Keep items short and concrete, update the list as work starts and finishes, and never leave pending items when the task is done.";
case ASK_TOOL_NAME:
return "Ask the user one or more questions. Use Markdown in question text and option labels when formatting helps (for example, emphasis, inline code, or lists); the desktop card renders it safely. Plain strings and existing `{ label, description? }` options are accepted; descriptions remain plain text and answers return the selected source label. The card always provides a custom user-input option.";
case "PluginScaffold":
@@ -2943,6 +2945,22 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// stopped being readable.
const parameters: Record<string, Parameters<typeof Type.Object>[0]> = {
GenerateImages: imageGenerationParameters,
+ TodoWrite: {
+ todos: Type.Array(
+ Type.Object({
+ content: Type.String({ minLength: 1, maxLength: 500 }),
+ status: Type.Union([
+ Type.Literal("pending"),
+ Type.Literal("in_progress"),
+ Type.Literal("completed"),
+ Type.Literal("cancelled"),
+ ]),
+ priority: Type.Optional(
+ Type.Union([Type.Literal("high"), Type.Literal("medium"), Type.Literal("low")]),
+ ),
+ }),
+ ),
+ },
Read: {
path: pathParam(
"Existing regular file only, never a directory; workspace-relative or explicitly approved.",
@@ -3407,6 +3425,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
"Grep",
"BrowserPreview",
"PluginCheck",
+ "TodoWrite",
]
: ["Read", "Glob", "Grep", "BrowserPreview", "Bash", "Write", "Edit"];
if (this.mode === "agent") {
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 4eb19be50..2c2fa8b92 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -274,6 +274,15 @@ export const de = {
"fileTruncated": "Das erste wird angezeigt 8000 passende Dateien",
"acHint": "↑↓ auswählen · Eingabe bestätigen · Esc schließen",
"send": "Senden",
+ "todo": {
+ "progress": "{{completed}}/{{total}} erledigt",
+ "current": "{{completed}}/{{total}} · Aktuell: {{content}}",
+ "completed": "{{completed}}/{{total}} erledigt",
+ "more": "{{count}} weitere Elemente",
+ "updated": "Checkliste aktualisiert",
+ "updating": "Checkliste wird aktualisiert",
+ "status": { "pending": "Offen", "in_progress": "In Bearbeitung", "completed": "Erledigt", "cancelled": "Abgebrochen" }
+ },
"queuedPrompts": "Nachrichten in der Warteschlange",
"queuedPromptEmpty": "Nachricht in der Warteschlange",
"removeQueuedPrompt": "Nachricht in der Warteschlange entfernen",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 40491d471..3bfd21b9d 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -281,6 +281,20 @@ export const en = {
fileTruncated: "Showing the first 8000 matching files",
acHint: "↑↓ select · Enter confirm · Esc close",
send: "Send",
+ todo: {
+ progress: "{{completed}}/{{total}} completed",
+ current: "{{completed}}/{{total}} · Current: {{content}}",
+ completed: "{{completed}}/{{total}} completed",
+ more: "{{count}} more items",
+ updated: "Checklist updated",
+ updating: "Updating checklist",
+ status: {
+ pending: "Pending",
+ in_progress: "In progress",
+ completed: "Completed",
+ cancelled: "Cancelled",
+ },
+ },
queuedPrompts: "Queued messages",
queuedPromptEmpty: "Queued message",
removeQueuedPrompt: "Remove queued message",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 194b74a04..fdf61f608 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -274,6 +274,15 @@ export const es = {
"fileTruncated": "Mostrando el primero 8000 archivos coincidentes",
"acHint": "↑↓ seleccionar · Ingresar confirmar · Esc cerrar",
"send": "Enviar",
+ "todo": {
+ "progress": "{{completed}}/{{total}} completadas",
+ "current": "{{completed}}/{{total}} · Actual: {{content}}",
+ "completed": "{{completed}}/{{total}} completadas",
+ "more": "{{count}} elementos más",
+ "updated": "Lista actualizada",
+ "updating": "Actualizando lista",
+ "status": { "pending": "Pendiente", "in_progress": "En curso", "completed": "Completada", "cancelled": "Cancelada" }
+ },
"queuedPrompts": "Mensajes en cola",
"queuedPromptEmpty": "Mensaje en cola",
"removeQueuedPrompt": "Eliminar mensaje en cola",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 4c1bc9e26..29b7ad572 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -274,6 +274,15 @@ export const fr = {
"fileTruncated": "Afficher le premier 8000 fichiers correspondants",
"acHint": "↑↓ sélectionner · Entrer confirmer · Esc fermer",
"send": "Envoyer",
+ "todo": {
+ "progress": "{{completed}}/{{total}} terminées",
+ "current": "{{completed}}/{{total}} · Actuelle : {{content}}",
+ "completed": "{{completed}}/{{total}} terminées",
+ "more": "{{count}} éléments supplémentaires",
+ "updated": "Liste mise à jour",
+ "updating": "Mise à jour de la liste",
+ "status": { "pending": "En attente", "in_progress": "En cours", "completed": "Terminée", "cancelled": "Annulée" }
+ },
"queuedPrompts": "Messages en file d'attente",
"queuedPromptEmpty": "Message en file d'attente",
"removeQueuedPrompt": "Supprimer le message en file d'attente",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 5be9fa2e6..0cf07418e 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -283,6 +283,15 @@ export const ko = {
fileTruncated: "일치하는 파일 중 처음 8000개 표시",
acHint: "↑↓ 선택 · Enter 확인 · Esc 닫기",
send: "보내기",
+ todo: {
+ progress: "{{completed}}/{{total}} 완료",
+ current: "{{completed}}/{{total}} · 현재: {{content}}",
+ completed: "{{completed}}/{{total}} 완료",
+ more: "{{count}}개 더 있음",
+ updated: "체크리스트 업데이트됨",
+ updating: "체크리스트 업데이트 중",
+ status: { pending: "대기", in_progress: "진행 중", completed: "완료", cancelled: "취소됨" },
+ },
queuedPrompts: "대기 중인 메시지",
queuedPromptEmpty: "대기 중인 메시지",
removeQueuedPrompt: "대기 중인 메시지 제거",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 2dc240116..eaf7eb827 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -273,6 +273,15 @@ export const ptBR = {
fileTruncated: "Exibindo os primeiros 8.000 arquivos correspondentes",
acHint: "↑↓ para selecionar · Enter para confirmar · Esc para fechar",
send: "Enviar",
+ todo: {
+ progress: "{{completed}}/{{total}} concluídos",
+ current: "{{completed}}/{{total}} · Atual: {{content}}",
+ completed: "{{completed}}/{{total}} concluídos",
+ more: "Mais {{count}} itens",
+ updated: "Checklist atualizado",
+ updating: "Atualizando checklist",
+ status: { pending: "Pendente", in_progress: "Em andamento", completed: "Concluído", cancelled: "Cancelado" },
+ },
queuedPrompts: "Mensagens na fila",
queuedPromptEmpty: "Mensagem na fila",
removeQueuedPrompt: "Remover prompt da fila",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 8c2053253..94cb8af7b 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -283,6 +283,15 @@ export const tr = {
fileTruncated: "İlk 8000 eşleşen dosya gösteriliyor",
acHint: "↑↓ seç · Enter onayla · Esc kapat",
send: "Gönder",
+ todo: {
+ progress: "{{completed}}/{{total}} tamamlandı",
+ current: "{{completed}}/{{total}} · Geçerli: {{content}}",
+ completed: "{{completed}}/{{total}} tamamlandı",
+ more: "{{count}} öğe daha",
+ updated: "Kontrol listesi güncellendi",
+ updating: "Kontrol listesi güncelleniyor",
+ status: { pending: "Bekliyor", in_progress: "Devam ediyor", completed: "Tamamlandı", cancelled: "İptal edildi" },
+ },
queuedPrompts: "Kuyruktaki iletiler",
queuedPromptEmpty: "Kuyruktaki ileti",
removeQueuedPrompt: "Kuyruktaki iletiyi kaldır",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 42cd4193d..4d38cea1f 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -276,6 +276,15 @@ export const zhCN = {
fileTruncated: "仅显示前 8000 个匹配文件",
acHint: "↑↓ 选择 · Enter 确认 · Esc 关闭",
send: "发送",
+ todo: {
+ progress: "已完成 {{completed}}/{{total}}",
+ current: "{{completed}}/{{total}} · 当前:{{content}}",
+ completed: "已完成 {{completed}}/{{total}}",
+ more: "还有 {{count}} 项",
+ updated: "清单已更新",
+ updating: "正在更新清单",
+ status: { pending: "待办", in_progress: "进行中", completed: "已完成", cancelled: "已取消" },
+ },
queuedPrompts: "待发送消息",
queuedPromptEmpty: "待发送消息",
removeQueuedPrompt: "移除待发送消息",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 2575742fa..99a8fad41 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -276,6 +276,15 @@ export const zhTW = {
fileTruncated: "僅顯示前 8000 個匹配檔案",
acHint: "↑↓ 選擇 · Enter 確認 · Esc 關閉",
send: "傳送",
+ todo: {
+ progress: "已完成 {{completed}}/{{total}}",
+ current: "{{completed}}/{{total}} · 目前:{{content}}",
+ completed: "已完成 {{completed}}/{{total}}",
+ more: "還有 {{count}} 項",
+ updated: "清單已更新",
+ updating: "正在更新清單",
+ status: { pending: "待辦", in_progress: "進行中", completed: "已完成", cancelled: "已取消" },
+ },
queuedPrompts: "待發送訊息",
queuedPromptEmpty: "待發送訊息",
removeQueuedPrompt: "移除待發送訊息",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 6d8ac89ad..c044de255 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -69,3 +69,5 @@ export * from "./prompt-enhancement.js";
export * from "./native-web-search.js";
export * from "./native-web-search-transport.js";
export * from "./header-value.js";
+
+export * from "./session-todos.js";
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index 47caebb17..c19de1c7c 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -185,6 +185,7 @@ export const IPC = {
scheduledExecute: "pi-desktop/scheduled/execute",
scheduledListRuns: "pi-desktop/scheduled/listRuns",
toolResolvePermission: "pi-desktop/tool/resolvePermission",
+ todosGet: "pi-desktop/todos/get",
askToolResolve: "pi-desktop/agent/askTool/resolve",
plansPending: "pi-desktop/plans/pending",
plansResolve: "pi-desktop/plans/resolve",
@@ -394,6 +395,7 @@ export const IPC = {
notificationActivated: "pi-desktop/notification/event/activated",
notificationSound: "pi-desktop/notification/event/sound",
plansChanged: "pi-desktop/plans/event/changed",
+ todosChanged: "pi-desktop/todos/event/changed",
providersOauth: "pi-desktop/providers/oauth/event",
mcpOauth: "pi-desktop/mcp/oauth/event",
updatesState: "pi-desktop/updates/event/state",
diff --git a/packages/shared/src/session-todos.ts b/packages/shared/src/session-todos.ts
new file mode 100644
index 000000000..3cd06489f
--- /dev/null
+++ b/packages/shared/src/session-todos.ts
@@ -0,0 +1,22 @@
+export const TODO_STATUSES = [
+ "pending",
+ "in_progress",
+ "completed",
+ "cancelled",
+] as const;
+
+export type TodoStatus = (typeof TODO_STATUSES)[number];
+export type TodoPriority = "high" | "medium" | "low";
+
+export type SessionTodo = {
+ content: string;
+ status: TodoStatus;
+ priority: TodoPriority;
+};
+
+export type SessionTodoSnapshot = {
+ sessionId: string;
+ todos: SessionTodo[];
+ revision: number;
+ updatedAt: number;
+};
diff --git a/packages/shared/src/subagent-definition.ts b/packages/shared/src/subagent-definition.ts
index a44d0db85..54bbb4e4f 100644
--- a/packages/shared/src/subagent-definition.ts
+++ b/packages/shared/src/subagent-definition.ts
@@ -113,6 +113,7 @@ export const SUBAGENT_INHERIT_DENY_TOOLS: readonly string[] = [
"TaskStop",
"EnterPlanMode",
"EnterGoalMode",
+ "TodoWrite",
"asktool",
"new_context",
"ToolSearch",