Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(subagents): add direct stop controls to delegation cards
zszz317459704c682
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex ddab84553..44595a490 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -1,5 +1,5 @@import { expandMcpInvocation } from "../composer-mcp";-import { IPC, ErrorCodes, compactionRecordId, findSkillMentions, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PendingInteractiveRequests, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, type VoiceOrigin, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";+import { IPC, ErrorCodes, compactionRecordId, findSkillMentions, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AgentStopSubagentsRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PendingInteractiveRequests, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, type VoiceOrigin, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";import type { FinishTurn } from "../runtime/plans";import { expandSlashInvocation, enhancePromptDraft, summarizeSessionTitle, visionFromModelConfig, type ComposerTemplate, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";@@ -812,6 +812,18 @@ export function registerAgentIpc({}});+ handle(IPC.invoke.agentStopSubagents, async (req: AgentStopSubagentsRequest) => {+ if (!req || typeof req.sessionId !== "string" || !req.sessionId.trim() ||+ (req.delegationIds !== undefined && (!Array.isArray(req.delegationIds) ||+ req.delegationIds.length === 0 || req.delegationIds.length > 100 ||+ req.delegationIds.some(id => typeof id !== "string" || !id.trim())))) {+ throw new Error("Invalid subagent stop request");+ }+ rejectNativeAgentOperation(req.sessionId);+ if (!sidecar) throw new Error("sidecar unavailable");+ return sidecar.call("agent.stopSubagents", req);+ });+handle(IPC.invoke.agentStop, async (req: AgentStopRequest) => {if (!sidecar) throw new Error("sidecar unavailable");const activeTurnId = activeTurns.get(req.sessionId);diff --git a/apps/desktop/src/components/workpanel/SubagentTranscriptTab.tsx b/apps/desktop/src/components/workpanel/SubagentTranscriptTab.tsxindex 8df9a8e06..f4a16444e 100644--- a/apps/desktop/src/components/workpanel/SubagentTranscriptTab.tsx+++ b/apps/desktop/src/components/workpanel/SubagentTranscriptTab.tsx@@ -1,3 +1,6 @@+import { toolResultPayload } from "../../lib/tool-presentation";+import { SubagentStopButton } from "../../features/chat/transcript/SubagentStopButton";+import { collectDelegationStatuses, subagentOutcome } from "../../lib/subagent-topology";import { Fragment, useLayoutEffect, useMemo } from "react";import { useTranslation } from "react-i18next";import { useAppStore } from "../../stores/app-store";@@ -29,7 +32,7 @@ import { Markdown } from "../Markdown";* on the same delegation append further turns, so a resumed delegate reads as* one continuing user/assistant exchange.*- * The tab is display-only: the composer at the foot is a disabled textarea+ * The tab allows explicit cancellation; the composer at the foot is a disabled textarea* whose placeholder says the delegate is driven by the main agent. There is* deliberately no send path.*/@@ -48,6 +51,18 @@ function SubagentTranscriptSurface({ delegationId }: { delegationId: string }) {// the empty key keeps the hook's contract while nothing is active.const transcript = useTranscriptView(activeSessionId ?? "");const { messages } = transcript;+ const delegateRunning = useMemo(() => {+ const items = messages+ .filter(message => message.role === "tool")+ .map(message => ({ kind: "tool" as const, message }));+ const statuses = collectDelegationStatuses(items);+ return items.some(({ message }) => {+ const payload = toolResultPayload(message);+ return payload && typeof payload === "object" &&+ "delegationId" in payload && payload.delegationId === delegationId &&+ subagentOutcome(message, statuses) === "running";+ });+ }, [messages, delegationId]);const isRunning = useAppStore((state) => (activeSessionId ? state.runningSessions[activeSessionId] ?? false : false),);@@ -99,6 +114,11 @@ function SubagentTranscriptSurface({ delegationId }: { delegationId: string }) {return (<DisclosureAnchorContext.Provider value={disclosureAnchorNotifier}><div className="subagent-transcript-tab" data-testid="subagent-transcript-tab">+ {delegateRunning ? (+ <div className="subagent-transcript-actions">+ <SubagentStopButton delegationId={delegationId} running />+ </div>+ ) : null}<divref={scrollRef}data-scroll-owner="follow"diff --git a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsxindex 8b725b69c..6d9a2de3f 100644--- a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx+++ b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx@@ -1,3 +1,4 @@+import { SubagentStopButton } from "./SubagentStopButton";import { activityTimingInputs, cachedVisibleActivityItems } from "../../../lib/transcript-activity-summary";import { reuseReferences } from "../../../lib/transcript-summary";import { ActivityItems } from "./ActivityItems";@@ -358,6 +359,7 @@ export const ActivityGroup = memo(function ActivityGroup({runtimeActivity ? ` phase-${runtimeActivity.phase}` : ""}`}>+ <div className="subagent-activity-header"><buttonref={titleRef}className="tool-activity-header"@@ -395,6 +397,8 @@ export const ActivityGroup = memo(function ActivityGroup({<IconChevronRight size={12} /></span></button>+ <SubagentStopButton running={topologyLive} />+ </div>{tail ? (<div className="tool-activity-preview" aria-hidden>{tail}diff --git a/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsx b/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsxnew file mode 100644index 000000000..216a3a61c--- /dev/null+++ b/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsx@@ -0,0 +1,84 @@+import { useEffect } from "react";+import { create } from "zustand";+import { useTranslation } from "react-i18next";+import { Button } from "../../../components/ui";+import { IconStop } from "../../../components/icons";+import { api } from "../../../lib/api";+import { useAppStore } from "../../../stores/app-store";++// Shared by topology cards and the detail panel to prevent duplicate requests.+const useStops = create<{+ busy: Record<string, { delegationId?: string } | undefined>;+ pending: Record<string, string[]>;+}>(() => ({ busy: {}, pending: {} }));++export function SubagentStopButton({+ delegationId,+ running,+ name,+}: {+ delegationId?: string;+ running: boolean;+ name?: string;+}) {+ const { t } = useTranslation();+ const sessionId = useAppStore(state => state.activeSessionId);+ const source = useAppStore(state => state.sessions.find(session => session.id === state.activeSessionId)?.source);+ const busy = useStops(state => sessionId ? state.busy[sessionId] : undefined);+ const pending = useStops(state => sessionId ? state.pending[sessionId] : undefined);+ const stopping = delegationId ? pending?.includes(delegationId) : false;+ const stoppingRequest = busy && (!delegationId || !busy.delegationId || busy.delegationId === delegationId);+ useEffect(() => {+ if (running || !sessionId || !delegationId || !stopping) return;+ useStops.setState(state => ({ pending: {+ ...state.pending,+ [sessionId]: (state.pending[sessionId] ?? []).filter(id => id !== delegationId),+ } }));+ }, [running, sessionId, delegationId, stopping]);+ if (!running || !sessionId || source === "remote" || source === "pi-native") return null;++ const stop = async () => {+ if (useStops.getState().busy[sessionId]) return;+ useStops.setState(state => ({ busy: { ...state.busy, [sessionId]: { delegationId } } }));+ try {+ const result = await api.stopSubagents({ sessionId, ...(delegationId ? { delegationIds: [delegationId] } : {}) });+ if (result.pending.length > 0) {+ useStops.setState(state => ({ pending: {+ ...state.pending,+ [sessionId]: [...new Set([...(state.pending[sessionId] ?? []), ...result.pending])],+ } }));+ }+ } catch (error) {+ useAppStore.getState().showToast(error instanceof Error ? error.message : String(error), { variant: "error" });+ } finally {+ useStops.setState(state => {+ const busy = { ...state.busy };+ delete busy[sessionId];+ return { busy };+ });+ }+ };+ const label = stoppingRequest || stopping+ ? t("chat.stoppingSubagents")+ : delegationId+ ? t("chat.stopSubagentNamed", { name: name ?? t("chat.subagentUnnamed") })+ : t("chat.stopAllSubagents");+ return (+ <Button+ className="subagent-stop-button"+ variant="secondary"+ size="sm"+ title={label}+ aria-label={label}+ disabled={!!busy || stopping}+ onClick={() => void stop()}+ >+ {stoppingRequest || stopping+ ? <span className="tool-spinner" aria-hidden />+ : <IconStop size={9} />}+ <span>{stoppingRequest || stopping+ ? t("chat.stoppingSubagents")+ : t(delegationId ? "chat.stopSubagent" : "chat.stopAllSubagentsShort")}</span>+ </Button>+ );+}diff --git a/apps/desktop/src/features/chat/transcript/ToolRow.tsx b/apps/desktop/src/features/chat/transcript/ToolRow.tsxindex f2fd8d17c..6e2220dc0 100644--- a/apps/desktop/src/features/chat/transcript/ToolRow.tsx+++ b/apps/desktop/src/features/chat/transcript/ToolRow.tsx@@ -1,3 +1,4 @@+import { SubagentStopButton } from "./SubagentStopButton";import { PlanHistoryCard } from "./PlanHistoryCard";import { planSubmission } from "../../../lib/plan-history";import { GeneratedImages } from "./GeneratedImages";@@ -399,6 +400,7 @@ function HostToolRow({aria-label={`${t("chat.toolCall")}: ${rawName}${agentName ? `, ${agentName}` : ""}${modelLabel ? `, ${modelLabel}` : ""}${statusLabel ? `, ${statusLabel}` : ""}`}>{variant === "topology" ? (+ <div className="subagent-topology-node-actions"><buttonclassName="subagent-topology-node-header"aria-expanded={panelOpen}@@ -436,7 +438,8 @@ function HostToolRow({title={modelLabel}aria-label={modelLabel}>- {modelLabel}+ <span className="subagent-topology-node-model-name">{modelId}</span>+ {thinkingLabel ? <span className="subagent-topology-node-thinking"> {thinkingLabel}</span> : null}</span>) : null}<span className="subagent-topology-node-status">@@ -459,6 +462,8 @@ function HostToolRow({<span className="tool-spinner" aria-label={t("chat.running")} />) : null}</button>+ {typeof delegationId === "string" && <SubagentStopButton delegationId={delegationId} running={outcome === "running" && !creating} name={agentName} />}+ </div>) : (<div className={`tool-row-head${runHead ? " is-run" : ""}`}><buttondiff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 1cc3ef44e..da924672a 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -21,6 +21,8 @@ import type {SessionSummarizeTitleRequest,SessionSummarizeTitleResponse,AgentStopResponse,+ AgentStopSubagentsRequest,+ AgentStopSubagentsResponse,AgentQueueChangedEvent,AgentQueuePushRequest,QueuedTurnSummary,@@ -947,6 +949,8 @@ export const api = {invoke<AgentCompactResponse>(IPC.invoke.agentCompact, req),abort: (sessionId: string) =>invoke(IPC.invoke.agentAbort, { sessionId }),+ stopSubagents: (req: AgentStopSubagentsRequest) =>+ invoke<AgentStopSubagentsResponse>(IPC.invoke.agentStopSubagents, req),stop: (sessionId: string, turnId?: string) =>invoke<AgentStopResponse>(IPC.invoke.agentStop, { sessionId, ...(turnId ? { turnId } : {}) }),queuePrompt: (req: AgentQueuePushRequest) =>diff --git a/apps/desktop/src/styles/messages.css b/apps/desktop/src/styles/messages.cssindex be6c3d3cf..9ab9cf85d 100644--- a/apps/desktop/src/styles/messages.css+++ b/apps/desktop/src/styles/messages.css@@ -2231,6 +2231,46 @@content: "";}+.subagent-stop-button {+ display: inline-flex;+ flex: none;+ align-items: center;+ gap: 5px;+ white-space: nowrap;+}++.subagent-activity-header {+ display: flex;+ align-items: center;+ padding-right: 10px;+}++.subagent-activity-header > .tool-activity-header {+ flex: 1;+}++.tool-activity-group.open > .subagent-activity-header > .tool-activity-header > .tool-activity-caret {+ transform: rotate(90deg);+}++.subagent-topology-node-actions {+ position: relative;+}++.subagent-topology-node-actions > .subagent-stop-button {+ position: absolute;+ right: 10px;+ bottom: 10px;+}++.subagent-topology-node-actions:has(> .subagent-stop-button) .subagent-topology-node-header {+ min-height: 88px;+}++.subagent-topology-node-actions:has(> .subagent-stop-button) :is(.subagent-topology-node-summary, .subagent-topology-node-steps) {+ padding-right: 100px;+}+.subagent-topology-node-header {display: flex;width: 100%;@@ -2351,16 +2391,27 @@}.subagent-topology-node-model {+ display: inline-flex;min-width: 0;- max-width: 38%;- overflow: hidden;+ max-width: 100%;+ flex: 0 1 auto;color: var(--ds-text-muted);font-family: var(--font-mono);font-size: var(--text-2xs);- text-overflow: ellipsis;white-space: nowrap;}+.subagent-topology-node-model-name {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+}++.subagent-topology-node-thinking {+ flex: none;+ white-space: pre;+}+.subagent-topology-node-status {flex: none;color: var(--ds-text-muted);diff --git a/apps/desktop/src/styles/work-panel.css b/apps/desktop/src/styles/work-panel.cssindex 8164d8fe8..56f33cc8d 100644--- a/apps/desktop/src/styles/work-panel.css+++ b/apps/desktop/src/styles/work-panel.css@@ -374,6 +374,12 @@* column (scroll area above a read-only composer) and the composer itself.* The scroll area owns the only scrollbar; the composer never scrolls.*/+.subagent-transcript-actions {+ display: flex;+ justify-content: flex-end;+ padding: 8px 12px;+}+.subagent-transcript-tab {display: flex;min-width: 0;diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 8cc084a6a..810943853 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -1982,6 +1982,7 @@ pub fn append_message(params![session_id, record.id, text, record.is_error],)?;} else {+ update_delegation_snapshot(db, session_id, &record)?;return Ok(());}} else {@@ -1990,6 +1991,7 @@ pub fn append_message(let original_id = record.id.clone();record.id = namespaced_message_id(session_id, &record.id);if message_indexed(db, session_id, &record.id)? {+ update_delegation_snapshot(db, session_id, &record)?;return Ok(());}// Old hosts wrote JSONL then failed UNIQUE. Replaying that@@ -2195,6 +2197,24 @@ fn rebuild_session_message_index(}fn streaming_assistant_indexed(db: &Database, session_id: &str, message_id: &str) -> Result<bool> {+ Ok(+ indexed_message_record(db, session_id, message_id)?.is_some_and(|record| {+ record.role == "assistant"+ && record+ .meta+ .as_ref()+ .and_then(|meta| meta.get("status"))+ .and_then(Value::as_str)+ == Some("streaming")+ }),+ )+}++fn indexed_message_record(+ db: &Database,+ session_id: &str,+ message_id: &str,+) -> Result<Option<MessageRecord>> {let layout = session_layout(db, session_id)?;let mut end = layout.message_count();while end > 0 {@@ -2208,21 +2228,73 @@ fn streaming_assistant_indexed(db: &Database, session_id: &str, message_id: &str)?;if let Some(record) = window.messages- .iter()+ .into_iter().rev().find(|record| record.id == message_id){- return Ok(record.role == "assistant"- && record- .meta- .as_ref()- .and_then(|meta| meta.get("status"))- .and_then(Value::as_str)- == Some("streaming"));+ return Ok(Some(record));}end = start;}- Ok(false)+ Ok(None)+}++/// Task is already a completed tool call while its delegated work is running.+/// Only its matching terminal result may replace that provisional result; replay+/// must neither reopen a settled delegate nor overwrite another call's metadata.+fn update_delegation_snapshot(+ db: &Database,+ session_id: &str,+ incoming: &MessageRecord,+) -> Result<()> {+ if incoming.role != "tool" || incoming.tool_name.as_deref() != Some("Task") {+ return Ok(());+ }+ let Some(next) = incoming+ .blocks+ .as_array()+ .and_then(|blocks| blocks.iter().find(|block| block["type"] == "tool_call"))+ else {+ return Ok(());+ };+ let details = &next["result"]["details"];+ if !matches!(+ details["status"].as_str(),+ Some("completed" | "stopped" | "aborted" | "failed" | "timed_out")+ ) {+ return Ok(());+ }+ let Some(id) = details["delegationId"].as_str().filter(|id| !id.is_empty()) else {+ return Ok(());+ };+ let Some(mut existing) = indexed_message_record(db, session_id, &incoming.id)? else {+ return Ok(());+ };+ if existing.role != "tool" || existing.tool_name.as_deref() != Some("Task") {+ return Ok(());+ }+ let Some(block) = existing+ .blocks+ .as_array_mut()+ .and_then(|blocks| blocks.iter_mut().find(|block| block["type"] == "tool_call"))+ else {+ return Ok(());+ };+ if block["callId"] != next["callId"]+ || block["result"]["details"]["delegationId"].as_str() != Some(id)+ || block["result"]["details"]["status"] != "running"+ {+ return Ok(());+ }+ block["result"] = next["result"].clone();+ block["text"] = next["text"].clone();+ invalidate_transcript_layout(session_id);+ if !transcripts::update_message(db.data_dir(), session_id, &existing)? {+ return Err(anyhow!(+ "delegation snapshot is missing from its transcript"+ ));+ }+ Ok(())}/// Append one canonical record: transcript line first, then the index row.@@ -4739,6 +4811,42 @@ mod tests {assert_eq!(last_seq, 2);}+ #[test]+ fn delegation_settlement_updates_only_its_running_snapshot() {+ let db = test_db();+ let first = create_session(&db, None, None, None, None, None).unwrap();+ let second = create_session(&db, None, None, None, None, None).unwrap();+ let mut task = user_msg("task-shared-id", "partial", "2026-10-05T00:00:00Z");+ task.role = "tool".into();+ task.tool_name = Some("Task".into());+ task.tool_call_id = Some(task.id.clone());+ task.tool_args = Some(json!({"agent": "explorer"}));+ task.tool_result =+ Some(json!({"details": {"delegationId": "delegate-A", "status": "running"}}));+ append_message(&db, &first.id, &task, None).unwrap();+ append_message(&db, &second.id, &task, None).unwrap();+ let mut stopped = task.clone();+ stopped.tool_result =+ Some(json!({"details": {"delegationId": "delegate-A", "status": "stopped"}}));+ stopped.tool_args = Some(json!({"agent": "changed"}));+ append_message(&db, &second.id, &stopped, None).unwrap();+ // Late replay cannot reopen a settled delegation, including namespaced IDs.+ append_message(&db, &second.id, &task, None).unwrap();+ let read = |id: &str| get_session(&db, id).unwrap().unwrap().messages;+ assert_eq!(read(&second.id).len(), 1);+ assert_eq!(read(&second.id)[0].tool_result, stopped.tool_result);+ assert_eq!(read(&second.id)[0].tool_args, task.tool_args);+ assert_eq!(read(&first.id)[0].tool_result, task.tool_result);+ let mut foreign = stopped.clone();+ foreign.tool_result =+ Some(json!({"details": {"delegationId": "different", "status": "stopped"}}));+ append_message(&db, &first.id, &foreign, None).unwrap();+ assert_eq!(read(&first.id)[0].tool_result, task.tool_result);+ append_message(&db, &first.id, &stopped, None).unwrap();+ append_message(&db, &first.id, &task, None).unwrap();+ assert_eq!(read(&first.id)[0].tool_result, stopped.tool_result);+ }+#[test]fn append_message_remaps_ids_owned_by_another_session() {let db = test_db();diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 9f550e223..917588211 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -49,6 +49,7 @@ Examples:- `pi-desktop/agent/prompt`- `pi-desktop/agent/steer`- `pi-desktop/agent/stop`+- `pi-desktop/agent/stop-subagents`- `pi-desktop/agent/abort`- `pi-desktop/agent/event/message`- `pi-desktop/agent/askTool/resolve`@@ -298,6 +299,21 @@ The renderer owns the removable, in-memory queued-prompt list per session. Itcalls this channel only for a queued item's **Send now** action and releasesthat item through the ordinary `agent/prompt` flow after the terminal event.+### 5.2a stop-subagents++`pi-desktop/agent/stop-subagents` accepts `{ sessionId, delegationIds? }` and+returns `{ pending: string[] }`. Omitting IDs selects all currently running+delegates in that session; an explicitly empty or malformed selection is+rejected. The local Desktop route forwards to `agent.stopSubagents` on the+existing sidecar runtime and never starts a runtime or prompts the model.+Native/remote session controls are not exposed by this local route.++It reuses `TaskStop` cancellation, waiting up to five seconds for termination.+Unconfirmed IDs are returned in `pending`; their durable status stays running+until settlement. The parent and unselected delegates remain active. Existing+terminal Task snapshots carry settlement through the normal persistence and+renderer event path; no synthetic tool call is added to model history.+### 5.3 abort```tsdiff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 7c3c07fc6..dd094e915 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -922,6 +922,13 @@ core set rather than the on-demand catalog of §7.1:waits for each abort to settle, then persists `status: "stopped"` with`completedAt` on `details.stopped[]`. Stopped delegations read as `stopped`.+**Explicit desktop cancellation.** A running delegate can be stopped from its+card or detail panel. The subagent group header also offers session-wide stop-all.+These controls call the same cancellation routine as `TaskStop` without a model+round trip. Cancellation is cooperative: the UI shows a pending state until+termination is confirmed, preserving partial output and existing parent Stop+semantics. A completed delegate is not relabeled by a late stop request.+**Live settlement.** When a delegate settles, the runtime refreshes its original`Task` transcript row with the terminal delegation summary (`status`,`completedAt`, counters, and failure details when present), using the existingdiff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 7411cafb3..5cdd7a25b 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -47,6 +47,17 @@ their path-scoped memory and filesystem instructions remain readable.hash, and size; the existing approval row also carries execution fields.Startup interruption is the process-epoch fence and no work is replayed.+### Delegation settlement snapshots++A completed `Task` tool call may still describe a running delegate. A later+terminal snapshot with the same session, message/call ID and delegation ID+replaces only that tool result and its display text. Existing metadata, message+order and index identity are preserved, including namespaced IDs after a+cross-session tool-call collision. A stale running replay, another delegation's+result or a later terminal replay cannot overwrite the settled snapshot. Other+duplicate appends retain their existing idempotent behavior. No schema migration+or transcript format change is required.+## 2. File layout### User-selected storage location (issue #1213)diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 1518021fd..635241b57 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -2563,6 +2563,12 @@ as a conversation:state (`running`, `error`, `denied`, `success`). Clicking the node expands theexisting brief/report/counters and nested rows; the report remains printedexactly once.+- Local Desktop running nodes with a delegation handle expose a separate Stop+ button; the delegate detail panel exposes the same action. The group header+ offers Stop all subagents for the current session. These actions do not open+ a model turn or stop the coordinator. Pending cancellation disables duplicate+ submission and reads Stopping; terminal nodes have no Stop action. Existing+ output remains readable, including partial output from stopped delegates.- A topology that first appears while the turn is active opens once so progressis visible, then closes when its activity settles if the user has notinteracted with the card. Reloaded history remains collapsed by default. Adiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 0f9b353dd..96ba50a4f 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -16803,3 +16803,17 @@ host-created files. The full app's file-preview viewer is covered separately.image model selection and provider configuration remain available.- Coverage: recent-models.test.mjs, recent-model-flow.test.mjs,default-model-picker.test.mjs, and scripts/e2e-composer-model-selection.mjs.+++#### E2E-CHAT-subagent-direct-stop++- Environment: isolated Desktop profile, real Main/sidecar/Host and a local+ streaming provider fixture; no real API account or user data.+- Start two delegates, open A's detail panel and stop A. Verify B and the parent+ remain active, A's partial output remains readable, and no model request was+ needed. Stop all from the group header; B stops and the parent remains active.+- Terminal cards remove their Stop controls and persisted Task snapshots record+ `stopped`. An empty explicit ID list is rejected rather than stopping all.+- Run `node scripts/e2e-subagent-stop.mjs`. Runtime tests additionally cover+ cross-session isolation and uncooperative cancellation remaining pending;+ `e2e-subagent-parent-error.mjs` covers explicit cancellation/resume semantics.diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 36a27d146..63e9b5b9d 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -7811,7 +7811,37 @@ describe("DesktopAgentRuntime subagents", () => {await runtime.dispose();});- it("returns a pending cancellation instead of hanging when a delegate ignores abort", async () => {+ it("scopes direct cancellation to selected IDs and the owning session", async () => {+ const runtime = createRuntime({ subagents: [explorer] });+ const other = createRuntime({ subagents: [explorer] });+ subagentRuns.deferred = true;+ subagentRuns.instances.length = 0;+ try {+ const start = async (owner: typeof runtime, callId: string) => {+ const result = await taskTool(owner).execute(callId, { agent: "explorer", task: callId });+ return String(result.details.delegationId);+ };+ const first = await start(runtime, "direct-A");+ const second = await start(runtime, "direct-B");+ const foreign = await start(other, "other-session");+ const stopped = await runtime.stopSubagents([first, first, foreign]);+ expect(stopped.details.stopped).toMatchObject([{ delegationId: first, status: "stopped" }]);+ expect((await runtime.stopSubagents([first])).details.stopped).toEqual([]);+ // Both remaining delegates must still be running to be selected by stop-all.+ expect((await runtime.stopSubagents()).details.stopped).toMatchObject([+ { delegationId: second, status: "stopped" },+ ]);+ expect((await other.stopSubagents()).details.stopped).toMatchObject([+ { delegationId: foreign, status: "stopped" },+ ]);+ } finally {+ subagentRuns.deferred = false;+ await runtime.dispose();+ await other.dispose();+ }+ });++ it.each(["tool", "desktop"])("returns pending cancellation when a delegate ignores %s stop", async (entry) => {const runtime = createRuntime({ subagents: [explorer] });subagentRuns.calls.length = 0;subagentRuns.instances.length = 0;@@ -7830,9 +7860,9 @@ describe("DesktopAgentRuntime subagents", () => {vi.useFakeTimers();try {- const stopping = stop.execute("stop-unresponsive", {- delegationIds: [delegationId],- });+ const stopping = entry === "desktop"+ ? runtime.stopSubagents([delegationId])+ : stop.execute("stop-unresponsive", { delegationIds: [delegationId] });await vi.advanceTimersByTimeAsync(5_000);const result = await stopping;expect(result.content[0].text).toContain("remain running");diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 4286d505a..67bc1cd52 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -5404,6 +5404,58 @@ Do not invent objections or turn speculative risks into blockers. Stop when the};}+ /** Shared cancellation path for TaskStop and explicit desktop controls. */+ async stopSubagents(ids: string[] = []) {+ const targets = ids.length+ ? [...new Set(ids)]+ .map((id) => this.delegations.get(id))+ .filter(+ (record): record is DelegationRecord =>+ record !== undefined && record.status === "running",+ )+ : this.runningDelegations();+ for (const record of targets) {+ record.stopRequested = true;+ record.abort();+ }+ // Cancellation is cooperative: bound the wait so a worker that ignores+ // abort cannot wedge the caller. Still-running workers are+ // explicitly returned as pending, never mislabeled as stopped.+ let stopTimeout: ReturnType<typeof setTimeout> | undefined;+ await Promise.race([+ Promise.all(targets.map((record) => record.completion)),+ new Promise<void>((resolve) => {+ stopTimeout = setTimeout(resolve, 5_000);+ }),+ ]);+ if (stopTimeout !== undefined) clearTimeout(stopTimeout);+ const pending = targets.filter((record) => record.status === "running");+ const stopped = targets.filter((record) => record.status === "stopped");+ const settled = targets.filter(+ (record) => record.status !== "running" && record.status !== "stopped",+ );+ const text =+ targets.length === 0+ ? "No matching running subagents to stop."+ : pending.length > 0+ ? `Cancellation requested for ${targets.length} subagent${targets.length === 1 ? "" : "s"}; ${pending.length} have not confirmed termination and remain running.`+ : settled.length > 0+ ? `Cancellation settled for ${targets.length} subagent${targets.length === 1 ? "" : "s"}: ${stopped.length} stopped and ${settled.length} had already finished.`+ : `Stopped ${stopped.length} subagent${stopped.length === 1 ? "" : "s"}.`;+ return {+ content: [{ type: "text" as const, text }],+ details: {+ stopped: stopped.map(delegationSummary),+ ...(pending.length > 0+ ? { stopPending: pending.map(delegationSummary) }+ : {}),+ ...(settled.length > 0+ ? { settled: settled.map(delegationSummary) }+ : {}),+ },+ };+ }+/** `TaskStop`: stop running delegations (ADR 0089). */private buildSubagentStopTool(): AgentTool {return {@@ -5425,54 +5477,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theisRecord(params) && Array.isArray(params.delegationIds)? params.delegationIds.map(String): [];- const targets = ids.length- ? ids- .map((id) => this.delegations.get(id))- .filter(- (record): record is DelegationRecord =>- record !== undefined && record.status === "running",- )- : this.runningDelegations();- for (const record of targets) {- record.stopRequested = true;- record.abort();- }- // Cancellation is cooperative: bound the wait so a worker that ignores- // abort cannot wedge the parent tool call. Still-running workers are- // explicitly returned as pending, never mislabeled as stopped.- let stopTimeout: ReturnType<typeof setTimeout> | undefined;- await Promise.race([- Promise.all(targets.map((record) => record.completion)),- new Promise<void>((resolve) => {- stopTimeout = setTimeout(resolve, 5_000);- }),- ]);- if (stopTimeout !== undefined) clearTimeout(stopTimeout);- const pending = targets.filter((record) => record.status === "running");- const stopped = targets.filter((record) => record.status === "stopped");- const settled = targets.filter(- (record) => record.status !== "running" && record.status !== "stopped",- );- const text =- targets.length === 0- ? "No matching running subagents to stop."- : pending.length > 0- ? `Cancellation requested for ${targets.length} subagent${targets.length === 1 ? "" : "s"}; ${pending.length} have not confirmed termination and remain running.`- : settled.length > 0- ? `Cancellation settled for ${targets.length} subagent${targets.length === 1 ? "" : "s"}: ${stopped.length} stopped and ${settled.length} had already finished.`- : `Stopped ${stopped.length} subagent${stopped.length === 1 ? "" : "s"}.`;- return {- content: [{ type: "text", text }],- details: {- stopped: stopped.map(delegationSummary),- ...(pending.length > 0- ? { stopPending: pending.map(delegationSummary) }- : {}),- ...(settled.length > 0- ? { settled: settled.map(delegationSummary) }- : {}),- },- };+ return this.stopSubagents(ids);},};}diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.tsindex cb40b97fc..1933854dd 100644--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@ -527,6 +527,16 @@ async function handle(method: string, params: any): Promise<unknown> {}return { ok: true };}+ case "agent.stopSubagents": {+ const runtime = runtimes.get(String(params.sessionId));+ if (!runtime) throw new Error("No active runtime for this session");+ const ids = params.delegationIds;+ if (ids !== undefined && (!Array.isArray(ids) || ids.length === 0 || ids.length > 100 || ids.some(id => typeof id !== "string" || !id.trim()))) {+ throw new Error("Invalid delegation IDs");+ }+ const result = await runtime.stopSubagents(ids as string[] | undefined);+ return { pending: result.details.stopPending?.flatMap(record => typeof record.delegationId === "string" ? [record.delegationId] : []) ?? [] };+ }case "agent.stop": {const sessionId = String(params.sessionId);const turnId = typeof params.turnId === "string" ? params.turnId : undefined;diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 5e5cedde7..5c592bcd8 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -467,6 +467,11 @@ export const de = {"subagentWorkUnnamed": "Was der Subagent getan hat","subagentProcess": "Aktivität","subagentUnnamed": "Unbenannter Subagent",+ stopSubagent: "Stoppen",+ stopAllSubagentsShort: "Alle stoppen",+ stopSubagentNamed: "{{name}} stoppen",+ stopAllSubagents: "Alle Unteragenten stoppen",+ stoppingSubagents: "Wird gestoppt…","subagentCoordinator": "Hauptagent","subagentCoordinating_one": "Koordinieren von {{count}} delegierten Aufgaben","subagentCoordinating_other": "Koordinieren von {{count}} delegierten Aufgaben",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex fff8171ff..883662836 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -479,6 +479,11 @@ export const en = {subagentWorkUnnamed: "What the subagent did",subagentProcess: "Activity",subagentUnnamed: "Unnamed subagent",+ stopSubagent: "Stop",+ stopAllSubagentsShort: "Stop all",+ stopSubagentNamed: "Stop {{name}}",+ stopAllSubagents: "Stop all subagents",+ stoppingSubagents: "Stopping…",subagentCoordinator: "Main agent",subagentCoordinating_one: "Coordinating {{count}} delegated task",subagentCoordinating_other: "Coordinating {{count}} delegated tasks",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 88ecbd6c8..c064b7fb1 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -467,6 +467,11 @@ export const es = {"subagentWorkUnnamed": "Qué hizo el subagente","subagentProcess": "Actividad","subagentUnnamed": "Subagente sin nombre",+ stopSubagent: "Detener",+ stopAllSubagentsShort: "Detener todos",+ stopSubagentNamed: "Detener {{name}}",+ stopAllSubagents: "Detener todos los subagentes",+ stoppingSubagents: "Deteniendo…","subagentCoordinator": "Agente principal","subagentCoordinating_one": "Coordinando {{count}} tarea delegada","subagentCoordinating_other": "Coordinando {{count}} tareas delegadas",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex e7296977c..ca102e1a2 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -467,6 +467,11 @@ export const fr = {"subagentWorkUnnamed": "Qu'est-ce que le sous-agent a fait","subagentProcess": "Activité","subagentUnnamed": "Sous-agent sans nom",+ stopSubagent: "Arrêter",+ stopAllSubagentsShort: "Tout arrêter",+ stopSubagentNamed: "Arrêter {{name}}",+ stopAllSubagents: "Arrêter tous les sous-agents",+ stoppingSubagents: "Arrêt en cours…","subagentCoordinator": "Agent principal","subagentCoordinating_one": "Coordonner {{count}} tâche déléguée","subagentCoordinating_other": "Coordonner {{count}} tâches déléguées",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 46df6c31a..cf265a7d8 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -476,6 +476,11 @@ export const ko = {subagentWorkUnnamed: "서브에이전트가 한 작업",subagentProcess: "활동",subagentUnnamed: "이름 없는 서브에이전트",+ stopSubagent: "중지",+ stopAllSubagentsShort: "모두 중지",+ stopSubagentNamed: "{{name}} 중지",+ stopAllSubagents: "모든 하위 에이전트 중지",+ stoppingSubagents: "중지 중…",subagentCoordinator: "메인 에이전트",subagentCoordinating_one: "위임된 작업 {{count}}개 조정 중",subagentCoordinating_other: "위임된 작업 {{count}}개 조정 중",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 4e1e0050c..e2d0bd242 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -465,6 +465,11 @@ export const ptBR = {subagentWorkUnnamed: "Trabalho do subagente sem nome",subagentProcess: "Atividade",subagentUnnamed: "Subagente sem nome",+ stopSubagent: "Parar",+ stopAllSubagentsShort: "Parar todos",+ stopSubagentNamed: "Parar {{name}}",+ stopAllSubagents: "Parar todos os subagentes",+ stoppingSubagents: "Parando…",subagentCoordinator: "Agente principal",subagentCoordinating_one: "Coordenando {{count}} tarefa delegada",subagentCoordinating_other: "Coordenando {{count}} tarefas delegadas",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 9e289f0d3..f3ede81cd 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -476,6 +476,11 @@ export const tr = {subagentWorkUnnamed: "Alt ajanın yaptıkları",subagentProcess: "Etkinlik",subagentUnnamed: "Adsız alt ajan",+ stopSubagent: "Durdur",+ stopAllSubagentsShort: "Tümünü durdur",+ stopSubagentNamed: "{{name}} durdur",+ stopAllSubagents: "Tüm alt ajanları durdur",+ stoppingSubagents: "Durduruluyor…",subagentCoordinator: "Ana ajan",subagentCoordinating_one: "{{count}} devredilmiş görev koordine ediliyor",subagentCoordinating_other: "{{count}} devredilmiş görev koordine ediliyor",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 4592e6edd..16b2e37ea 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -468,6 +468,11 @@ export const zhCN = {subagentWorkUnnamed: "子智能体的工作过程",subagentProcess: "工作过程",subagentUnnamed: "未命名子智能体",+ stopSubagent: "停止",+ stopAllSubagentsShort: "停止全部",+ stopSubagentNamed: "停止 {{name}}",+ stopAllSubagents: "停止全部子智能体",+ stoppingSubagents: "正在停止…",subagentCoordinator: "主 Agent",subagentCoordinating_one: "正在协调 {{count}} 个委派任务",subagentCoordinating_other: "正在协调 {{count}} 个委派任务",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 89f35eca0..69aad6b64 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -468,6 +468,11 @@ export const zhTW = {subagentWorkUnnamed: "子智慧體的工作過程",subagentProcess: "工作過程",subagentUnnamed: "未命名子智慧體",+ stopSubagent: "停止",+ stopAllSubagentsShort: "停止全部",+ stopSubagentNamed: "停止 {{name}}",+ stopAllSubagents: "停止全部子智慧體",+ stoppingSubagents: "正在停止…",subagentCoordinator: "主 Agent",subagentCoordinating_one: "正在協調 {{count}} 個委派任務",subagentCoordinating_other: "正在協調 {{count}} 個委派任務",diff --git a/packages/shared/src/changelog-de.ts b/packages/shared/src/changelog-de.tsindex e0c77ad95..117fb0d5c 100644--- a/packages/shared/src/changelog-de.ts+++ b/packages/shared/src/changelog-de.ts@@ -5,6 +5,7 @@ export const deEntries: ChangelogEntry[] = ["version": "0.16.1","date": "2026-10-04","highlights": [+ "Laufende Unteragenten lassen sich direkt in ihrer Karte oder Detailansicht stoppen, einzeln oder für die aktuelle Sitzung, ohne den Hauptagenten zu stoppen.","Wählen Sie in den Einstellungen einen eigenen Datenspeicherort, verfolgen Sie eine geprüfte Kaltmigration und leeren Sie nur neu erzeugbare Caches.","Geplante Aufgaben können im Intervall laufen: alle 5 Minuten bis zu 24 Stunden, gezählt ab dem Zeitpunkt, an dem die Aufgabe aktiviert wurde.","Die Seite „Geplant“ verbindet die Aufgabenliste mit der ausgewählten Aufgabe: letztes Ergebnis, nächste Ausführung, Anweisung und Ausführungsverlauf.",diff --git a/packages/shared/src/changelog-en.ts b/packages/shared/src/changelog-en.tsindex cff6c6b9b..c840ff39f 100644--- a/packages/shared/src/changelog-en.ts+++ b/packages/shared/src/changelog-en.ts@@ -5,6 +5,7 @@ export const enEntries: ChangelogEntry[] = [version: "0.16.1",date: "2026-10-04",highlights: [+ "Stop a running subagent directly from its card or detail panel, or stop all subagents in the current session without stopping the coordinator.","Choose a custom data location in Settings, follow a verified cold migration, and clean only rebuildable caches.","Scheduled tasks can run on an interval cadence: every 5 minutes up to 24 hours, counted from when the task was armed.","The Scheduled page pairs the task list with the selected task: its last outcome, next run, instruction and run history.",diff --git a/packages/shared/src/changelog-es.ts b/packages/shared/src/changelog-es.tsindex 608a0124f..1440574f8 100644--- a/packages/shared/src/changelog-es.ts+++ b/packages/shared/src/changelog-es.ts@@ -5,6 +5,7 @@ export const esEntries: ChangelogEntry[] = ["version": "0.16.1","date": "2026-10-04","highlights": [+ "Detén un subagente desde su tarjeta o panel de detalles, o todos los subagentes de la sesión actual, sin detener al coordinador.","Elige una ubicación personalizada de datos en Ajustes, sigue una migración en frío verificada y limpia solo las cachés que se pueden reconstruir.","Las tareas programadas pueden ejecutarse por intervalos: cada 5 minutos hasta 24 horas, contados desde que la tarea se activó.","La página de tareas programadas empareja la lista de tareas con la tarea seleccionada: su último resultado, la próxima ejecución, la instrucción y el historial de ejecuciones.",diff --git a/packages/shared/src/changelog-fr.ts b/packages/shared/src/changelog-fr.tsindex 427ffba2f..bf28cab5f 100644--- a/packages/shared/src/changelog-fr.ts+++ b/packages/shared/src/changelog-fr.ts@@ -5,6 +5,7 @@ export const frEntries: ChangelogEntry[] = ["version": "0.16.1","date": "2026-10-04","highlights": [+ "Arrêtez un sous-agent depuis sa carte ou ses détails, ou tous ceux de la session en cours, sans arrêter le coordinateur.","Choisissez un emplacement de données personnalisé dans les paramètres, suivez une migration à froid vérifiée et ne nettoyez que les caches régénérables.","Les tâches planifiées peuvent s’exécuter par intervalle : de 5 minutes à 24 heures, compté à partir du moment où la tâche a été activée.","La page des tâches planifiées associe la liste des tâches à la tâche sélectionnée : dernier résultat, prochaine exécution, instruction et historique des exécutions.",diff --git a/packages/shared/src/changelog-ko.ts b/packages/shared/src/changelog-ko.tsindex 0c03254f8..11d4f4ad3 100644--- a/packages/shared/src/changelog-ko.ts+++ b/packages/shared/src/changelog-ko.ts@@ -5,6 +5,7 @@ export const koEntries: ChangelogEntry[] = ["version": "0.16.1","date": "2026-10-04","highlights": [+ "카드나 상세 패널에서 개별 하위 에이전트 또는 현재 세션의 모든 하위 에이전트를 중지해도 주 에이전트는 계속 실행됩니다.","설정에서 사용자 지정 데이터 위치를 선택하고 검증된 콜드 마이그레이션을 진행하며 다시 생성할 수 있는 캐시만 정리하세요.","예약 작업을 간격 주기로 실행할 수 있습니다. 작업이 설정된 시점부터 5분에서 24시간까지입니다.","예약 페이지에서 작업 목록과 선택한 작업을 함께 보여 줍니다. 마지막 결과, 다음 실행, 지시문과 실행 기록입니다.",diff --git a/packages/shared/src/changelog-pt-BR.ts b/packages/shared/src/changelog-pt-BR.tsindex 02c7a2d3f..0336b5bb9 100644--- a/packages/shared/src/changelog-pt-BR.ts+++ b/packages/shared/src/changelog-pt-BR.ts@@ -5,6 +5,7 @@ export const ptBREntries: ChangelogEntry[] = ["version": "0.16.1","date": "2026-10-04","highlights": [+ "Pare um subagente pelo cartão ou painel de detalhes, ou todos os subagentes da sessão atual, sem parar o coordenador.","Escolha um local de dados personalizado nas Configurações, acompanhe uma migração a frio verificada e limpe apenas os caches que podem ser recriados.","As tarefas agendadas podem rodar em cadência de intervalo: de 5 minutos a 24 horas, contadas a partir do momento em que a tarefa foi armada.","A página Agendados combina a lista de tarefas com a tarefa selecionada: último resultado, próxima execução, instrução e histórico de execuções.",diff --git a/packages/shared/src/changelog-tr.ts b/packages/shared/src/changelog-tr.tsindex 34cf98ec6..648198774 100644--- a/packages/shared/src/changelog-tr.ts+++ b/packages/shared/src/changelog-tr.ts@@ -5,6 +5,7 @@ export const trEntries: ChangelogEntry[] = ["version": "0.16.1","date": "2026-10-04","highlights": [+ "Çalışan bir alt ajanı kartından veya ayrıntı panelinden ya da geçerli oturumdaki tüm alt ajanları koordinatörü durdurmadan durdurabilirsiniz.","Ayarlar'dan özel bir veri konumu seçin, doğrulanmış soğuk taşımayı izleyin ve yalnızca yeniden oluşturulabilir önbellekleri temizleyin.","Zamanlanmış görevler aralık temposunda çalışabilir: görev kurulduktan sonra 5 dakikadan 24 saate kadar.","Zamanlanmış sayfası görev listesini seçili görevle birlikte sunar: son sonucu, sonraki çalışmayı, talimatı ve çalışma geçmişini.",diff --git a/packages/shared/src/changelog-zh-CN.ts b/packages/shared/src/changelog-zh-CN.tsindex eef77dd6a..0c77ae00a 100644--- a/packages/shared/src/changelog-zh-CN.ts+++ b/packages/shared/src/changelog-zh-CN.ts@@ -5,6 +5,7 @@ export const zhCNEntries: ChangelogEntry[] = [version: "0.16.1",date: "2026-10-04",highlights: [+ "可从卡片或详情直接停止单个子智能体,也可停止当前会话的全部子智能体,主智能体继续运行。","可在设置中选择自定义数据保存目录,按验证过的冷迁移流程迁移,并只清理可重新生成的缓存。","计划任务新增按间隔执行的节奏:从启用时起算,最短 5 分钟、最长 24 小时。","「计划任务」页面把任务列表与所选任务配对显示:最近结果、下次运行、指令与运行记录。",diff --git a/packages/shared/src/changelog-zh-TW.ts b/packages/shared/src/changelog-zh-TW.tsindex 672bff7ab..d7ce128b0 100644--- a/packages/shared/src/changelog-zh-TW.ts+++ b/packages/shared/src/changelog-zh-TW.ts@@ -5,6 +5,7 @@ export const zhTWEntries: ChangelogEntry[] = [version: "0.16.1",date: "2026-10-04",highlights: [+ "可從卡片或詳情直接停止單個子智能體,也可停止目前工作階段的全部子智能體,主智能體繼續執行。","可在設定中選擇自訂資料儲存目錄,依驗證過的冷遷移流程遷移,並只清理可重新產生的快取。","排程工作新增間隔節奏:從啟用時起算,最短 5 分鐘、最長 24 小時。","「排程」頁面把工作清單與所選工作配對顯示:最近結果、下次執行、指令與執行紀錄。",diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 6814f18ac..56abb7aeb 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -116,6 +116,7 @@ export const IPC = {liveVoiceWidgetVisibility: "pi-desktop/voice/live/widget/visibility",agentCompact: "pi-desktop/agent/compact",agentAbort: "pi-desktop/agent/abort",+ agentStopSubagents: "pi-desktop/agent/stop-subagents",agentStop: "pi-desktop/agent/stop",agentQueuePush: "pi-desktop/agent/queue/push",agentQueueList: "pi-desktop/agent/queue/list",diff --git a/packages/shared/src/types/agent.ts b/packages/shared/src/types/agent.tsindex b747fab5e..77d6bd0d5 100644--- a/packages/shared/src/types/agent.ts+++ b/packages/shared/src/types/agent.ts@@ -343,3 +343,13 @@ export type AgentEventEnvelope = {/** Definition name of the emitting subagent. */agentName?: string;};++/** Explicit user cancellation; omitted IDs select this session's running delegates. */+export type AgentStopSubagentsRequest = {+ sessionId: string;+ delegationIds?: string[];+};++export type AgentStopSubagentsResponse = {+ pending: string[];+};diff --git a/scripts/e2e-subagent-parent-error.mjs b/scripts/e2e-subagent-parent-error.mjsindex ff17d2a39..207c80d14 100644--- a/scripts/e2e-subagent-parent-error.mjs+++ b/scripts/e2e-subagent-parent-error.mjs@@ -103,7 +103,7 @@ const provider = (modelId) => ({ id: "fixture", name: "Fixture", modelId, baseUrconst projectPath = mkdtempSync(join(tmpdir(), "pi-subagent-parent-error-"));const results = [];try {- for (const mode of ["error", "abort", "stop"]) {+ for (const mode of ["error", "abort", "stop", "direct"]) {const s = scenario = { mode, ids: new Map(), settled: new Map(), waiting: new Set(),errors: [], replayed: [], rejected: [], parentErrors: [] };const runtime = new DesktopAgentRuntime({@@ -139,12 +139,24 @@ try {await until(() => s.parentWaiting);await runtime.abort();}+ if (mode === "direct") {+ await until(() => s.parentWaiting);+ const first = await runtime.stopSubagents([s.ids.get("task_A")]);+ assert.equal(first.details.stopped.length, 1);+ await until(() => s.settled.has("task_A") && s.waiting.size === 1);+ assert.equal(s.settled.has("task_B"), false, "the sibling must remain running");+ assert.equal(runtime.getStatus().isRunning, true, "direct stop must not abort the parent");+ assert.equal((await runtime.stopSubagents()).details.stopped.length, 1);+ await until(() => s.settled.has("task_B"));+ assert.equal(runtime.getStatus().isRunning, true, "stop-all only targets delegates");+ await runtime.abort();+ }await running;await until(() => ["task_A", "task_B"].every((id) => s.settled.has(id)));assert.equal(runtime.getStatus().isRunning, false);assert.equal(s.ids.size, 2);for (const id of ["task_A", "task_B"]) {- assert.equal(s.settled.get(id).status, mode === "error" ? "failed" : mode === "stop" ? "stopped" : "aborted");+ assert.equal(s.settled.get(id).status, mode === "error" ? "failed" : ["stop", "direct"].includes(mode) ? "stopped" : "aborted");if (mode === "error") assert.equal(s.settled.get(id).error.code, "SUBAGENT_PARENT_FAILED");}if (mode === "error") assert.equal(s.parentErrors.length, 1);diff --git a/scripts/e2e-subagent-stop.mjs b/scripts/e2e-subagent-stop.mjsnew file mode 100644index 000000000..897e5995b--- /dev/null+++ b/scripts/e2e-subagent-stop.mjs@@ -0,0 +1,186 @@+// Real Desktop IPC/sidecar cancellation with a local streaming provider.+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createServer } from "node:http";+import { createServer as createNetServer } from "node:net";+import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";+import { resolveHostBinary } from "./e2e/host.mjs";++const root = repositoryRoot();+const show = process.argv.includes("--show");+const scratch = await mkdtemp(join(tmpdir(), "pi-subagent-stop-"));+const workspace = join(scratch, "workspace");+await mkdir(workspace);+await mkdir(join(scratch, "home"));+const workers = new Map();+const parents = new Set();+let sequence = 0;+const requests = [];+const server = createServer(async (req, res) => {+ try {+ let raw = "";+ for await (const chunk of req) raw += chunk;+ const body = JSON.parse(raw);+ requests.push(body);+ const users = body.messages.filter(message => message.role === "user");+ const input = JSON.stringify(users.at(-1)?.content);+ const label = input.includes("Fixture worker A") ? "A" : input.includes("Fixture worker B") ? "B" : null;+ res.writeHead(200, { "content-type": "text/event-stream" });+ const delta = (value, finish = null) => res.write(`data: ${JSON.stringify({ id: `fixture-${++sequence}`, object: "chat.completion.chunk", created: 1, model: body.model, choices: [{ index: 0, delta: value, finish_reason: finish }] })}\n\n`);+ if (label) {+ workers.set(label, res);+ res.on("close", () => { if (workers.get(label) === res) workers.delete(label); });+ delta({ role: "assistant", content: `Partial output from worker ${label}. Waiting for cancellation.` });+ return;+ }+ const tools = body.messages.filter(message => message.role === "tool");+ if (tools.some(message => message.tool_call_id?.startsWith("task_"))) {+ parents.add(res);+ res.on("close", () => parents.delete(res));+ res.write(": coordinator still working\n\n");+ return;+ }+ const calls = body.tools?.some(tool => tool.function?.name === "Task")+ ? ["A", "B"].map(label => ({ id: `task_${label}`, name: "Task", arguments: { agent: "explorer", task: `Fixture worker ${label}`, description: `Worker ${label}` } }))+ : [{ id: "discover", name: "ToolSearch", arguments: { query: "Task" } }];+ delta({ role: "assistant", tool_calls: calls.map((call, index) => ({ index, id: call.id, type: "function", function: { name: call.name, arguments: JSON.stringify(call.arguments) } })) });+ delta({}, "tool_calls");+ res.end("data: [DONE]\n\n");+ } catch (error) { res.end(String(error)); }+});+await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));+async function freePort() {+ const server = createNetServer();+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));+ const port = server.address().port;+ await new Promise(resolve => server.close(resolve));+ return port;+}+async function until(check, message = "condition") {+ const deadline = Date.now() + 30_000;+ while (Date.now() < deadline) {+ const value = await check();+ if (value) return value;+ await new Promise(resolve => setTimeout(resolve, 50));+ }+ throw new Error(`Timed out: ${message}\n${output.slice(-2500)}`);+}+async function connect(port, type) {+ const target = await until(async () => {+ try { return (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()).find(target => target.type === type && (type !== "page" || target.url.includes("/out/renderer/index.html") && !target.url.includes("surface="))); }+ catch { return null; }+ }, `CDP ${type}`);+ const ws = new WebSocket(target.webSocketDebuggerUrl);+ await new Promise(resolve => ws.addEventListener("open", resolve, { once: true }));+ const pending = new Map();+ ws.addEventListener("message", ({ data }) => {+ const packet = JSON.parse(String(data));+ if (packet.id && pending.has(packet.id)) {+ const { resolve, reject, timer } = pending.get(packet.id);+ clearTimeout(timer);+ pending.delete(packet.id);+ packet.error ? reject(new Error(JSON.stringify(packet.error))) : resolve(packet.result);+ }+ });+ const call = (method, params) => new Promise((resolve, reject) => {+ const id = ++sequence;+ const timer = setTimeout(() => { pending.delete(id); reject(new Error(`CDP timeout: ${method}`)); }, 30_000);+ pending.set(id, { resolve, reject, timer });+ ws.send(JSON.stringify({ id, method, params }));+ });+ return { ws, call, evaluate: async expression => {+ const result = await call("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });+ if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));+ return result.result.value;+ } };+}+const ports = [await freePort(), await freePort()];+const env = { ...process.env, HOME: join(scratch, "home"), PI_DESKTOP_DATA_DIR: join(scratch, "data"), PI_DESKTOP_HOST_BIN: resolveHostBinary(), PI_DESKTOP_PLAN_UI_PROBE: "1", PI_DESKTOP_TEST_API_KEY: "local-fixture", PI_DESKTOP_TEST_BASE_URL: `http://127.0.0.1:${server.address().port}/v1`, PI_DESKTOP_TEST_MODEL: "deepseek-flash", ELECTRON_RENDERER_URL: "", PI_DESKTOP_START_MAXIMIZED: "0" };+delete env.ELECTRON_RUN_AS_NODE;+const child = spawn(resolveElectronBinary(root).electronBinary, [`--remote-debugging-port=${ports[0]}`, `--inspect=${ports[1]}`, `--user-data-dir=${join(scratch, "profile")}`, "."], { cwd: join(root, "apps/desktop"), env, stdio: ["ignore", "pipe", "pipe"] });+let output = "";+child.stdout.on("data", chunk => { output += chunk; });+child.stderr.on("data", chunk => { output += chunk; });+let main, page;+try {+ main = await connect(ports[1], "node");+ page = await connect(ports[0], "page");+ await page.call("Runtime.enable", {});+ page.ws.addEventListener("message", ({data}) => {+ const event = JSON.parse(String(data));+ if (event.method === "Runtime.exceptionThrown") console.error(JSON.stringify(event.params));+ });+ await until(() => page.evaluate("!!window.piDesktop"), "preload startup");+ await until(() => page.evaluate("!!window.__PI_DESKTOP__"), "renderer startup");+ await until(() => main.evaluate("typeof globalThis.__PI_DESKTOP_PLAN_UI_PROBE === 'function'"), "main probe startup");+ const setup = await main.evaluate(`globalThis.__PI_DESKTOP_PLAN_UI_PROBE({operation:'liveSetup',workspace:${JSON.stringify(workspace)}})`);+ assert.equal(setup.ok, true, JSON.stringify(setup));+ const invoke = (key, ...input) => page.evaluate(`piDesktop.invoke(piDesktop.channels.invoke[${JSON.stringify(key)}],...${JSON.stringify(input)})`);+ assert.equal((await invoke("providersUpdate", { id: setup.providerId, models: [{ id: setup.modelId, contextWindow: 128000, maxTokens: 8192, thinkingLevels: ["off", "medium"], defaultThinkingLevel: "medium" }] })).ok, true);+ assert.equal((await invoke("sessionConfigure", setup.sessionId, { mode: "agent", providerId: setup.providerId, modelId: setup.modelId, thinkingLevel: "medium" })).ok, true);+ await invoke("sessionRename", setup.sessionId, "Subagent stop controls · local fixture");+ await page.evaluate(`window.__PI_DESKTOP__.refreshProviders().then(() => window.__PI_DESKTOP__.selectSession(${JSON.stringify(setup.sessionId)}))`);+ assert.equal((await invoke("agentPrompt", { sessionId: setup.sessionId, content: "Start two fixture workers for the stop controls demo." })).ok, true);+ await until(() => workers.size === 2 && parents.size > 0, "two real delegates and coordinator");+ const buttons = () => page.evaluate(`Array.from(document.querySelectorAll('.subagent-topology-node-actions .subagent-stop-button')).map(b=>({text:b.textContent,disabled:b.disabled}))`);+ await until(async () => (await buttons()).length === 2, "two stop buttons");+ await page.evaluate(`document.querySelector('.subagent-topology-node-header').click()`);+ await until(() => page.evaluate(`!!document.querySelector('.subagent-transcript-actions .subagent-stop-button')`), "detail stop control");+ await until(() => page.evaluate(`document.body.innerText.includes('Partial output from worker A')`), "worker A partial output rendered");+ const layout = await page.evaluate(`({+ models: [...document.querySelectorAll('.subagent-topology-node-model')].map(e => ({+ text: e.textContent,+ clipped: e.scrollWidth > e.clientWidth + 1,+ ellipsis: getComputedStyle(e).textOverflow === 'ellipsis'+ })),+ stops: [...document.querySelectorAll('.subagent-topology-node-actions .subagent-stop-button')].map(e => ({+ text: e.innerText.trim(), opacity: getComputedStyle(e).opacity,+ rightGap: e.parentElement.getBoundingClientRect().right - e.getBoundingClientRect().right,+ bottomGap: e.parentElement.getBoundingClientRect().bottom - e.getBoundingClientRect().bottom+ }))+ })`);+ assert.ok(layout.models.length === 2 && layout.models.every(m => m.text === "deepseek-flash medium" && !m.clipped && !m.ellipsis), `model and thinking labels remain readable with the detail panel open: ${JSON.stringify(layout.models)}`);+ assert.ok(layout.stops.length === 2 && layout.stops.every(b => b.text && b.opacity === "1" && Math.abs(b.rightGap - 10) < 1 && Math.abs(b.bottomGap - 10) < 1), "stop actions have visible text without hovering");+ const before = requests.length;+ await page.evaluate(`document.querySelector('.subagent-transcript-actions .subagent-stop-button').click()`);+ await until(() => !workers.has("A") && workers.has("B"), "only worker A cancelled");+ await until(async () => (await buttons()).length === 1, "terminal card removes stop");+ assert.equal(parents.size, 1, "coordinator stays running");+ assert.equal(requests.length, before, "stop sends no model request");+ await until(() => page.evaluate(`document.body.innerText.includes('Partial output from worker A')`), "partial delegate output survives");+ await page.evaluate(`document.querySelector('.subagent-activity-header > .subagent-stop-button').click()`);+ await until(() => workers.size === 0, "stop-all cancels remaining delegates");+ assert.equal(parents.size, 1, "stop-all preserves coordinator");+ await until(async () => (await buttons()).length === 0, "all terminal controls disappear");+ const invalid = await invoke("agentStopSubagents", { sessionId: setup.sessionId, delegationIds: [] });+ assert.equal(invalid.ok, false, "empty selection must not mean stop-all");+ await until(async () => {+ const session = await invoke("sessionGet", { id: setup.sessionId });+ const taskRows = session.data.session.messages.filter(message => message.toolName === "Task");+ return taskRows.length === 2 && taskRows.every(message => message.toolResult?.details?.status === "stopped");+ }, "terminal statuses persisted");+ console.log("PASS Desktop card/detail stop, session stop-all, parent isolation, partial output, persistence and invalid selection");+ await invoke("agentAbort", { sessionId: setup.sessionId });+ if (show) {+ const demo = await invoke("sessionCreate", { title: "子智能体停止演示 · 本地模拟模型", mode: "agent", providerId: setup.providerId, modelId: setup.modelId, projectPath: workspace });+ const demoId = demo.data.session.id;+ assert.equal((await invoke("sessionConfigure", demoId, { mode: "agent", providerId: setup.providerId, modelId: setup.modelId, thinkingLevel: "medium" })).ok, true);+ await page.evaluate(`window.__PI_DESKTOP__.selectSession(${JSON.stringify(demoId)})`);+ await invoke("agentPrompt", { sessionId: demoId, content: "这是本地模拟模型演示:启动两个子智能体,可以分别停止,或停止全部。主智能体继续运行。" });+ await until(() => workers.size === 2 && parents.size > 0, "demo ready");+ const shot = await page.call("Page.captureScreenshot", { format: "png" });+ await writeFile(join(scratch, "demo.png"), Buffer.from(shot.data, "base64"));+ console.log(`DEMO ${JSON.stringify({ scratch, ports, pid: child.pid })}`);+ main.ws.close();+ await new Promise(resolve => child.once("exit", resolve));+ }+} finally {+ main?.ws.close(); page?.ws.close();+ child.kill("SIGTERM");+ server.closeAllConnections();+ await new Promise(resolve => server.close(resolve));+ if (!show) await rm(scratch, { recursive: true, force: true });+}