Skip to content

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

chore(subagents): integrate latest main for stop controls

zszz38145730ab40c
diff --cc apps/desktop/electron/main/ipc/agent-ipc.ts
index 44595a490,60f8e04f6..0ea9a6ef3
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@@ -1,8 -1,7 +1,7 @@@
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 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 { 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 VoiceOrigin } 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 VoiceOrigin } 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";
+ import { expandSlashInvocation, visionFromModelConfig, type ComposerTemplate } from "@pi-desktop/agent-runtime";
import { appendPromptFallbackPaths, durableUserMessageId, preparePromptAttachments, type PreparedPromptAttachment } from "../prompt-attachments";
import { resolveSessionReferences } from "../session-references";
import { executionFromResponse, resolveSessionMessageInput } from "@pi-desktop/host-runtime";
diff --cc apps/desktop/src/lib/api.ts
index da924672a,b2814171e..8b68cad3f
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@@ -18,11 -16,7 +16,9 @@@ import type
SpeechSynthesizeRequest,
SpeechSynthesizeResult,
SpeechTranscribeRequest,
- SessionSummarizeTitleRequest,
- SessionSummarizeTitleResponse,
AgentStopResponse,
+ AgentStopSubagentsRequest,
+ AgentStopSubagentsResponse,
AgentQueueChangedEvent,
AgentQueuePushRequest,
QueuedTurnSummary,
diff --cc crates/host-core/src/sessions.rs
index 810943853,5d028bb86..8e84bc07b
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@@ -1971,18 -2149,26 +2149,27 @@@ pub fn append_message
&& message.status.as_deref() != Some("streaming")
&& streaming_assistant_indexed(db, session_id, &record.id)?
{
- invalidate_transcript_layout(session_id);
- if !transcripts::update_message(db.data_dir(), session_id, &record)? {
- return Err(anyhow!(
- "streaming assistant is missing from its transcript"
- ));
+ let stamped = "UPDATE messages SET text = ?3, is_error = ?4, streaming = 0
+ WHERE session_id = ?1 AND id = ?2";
+ if transcripts::update_message(db.data_dir(), session_id, &record)? {
+ db.conn().execute(
+ stamped,
+ params![session_id, record.id, text, record.is_error],
+ )?;
+ } else {
+ // The index knows this id but the transcript does not. A device
+ // that lost a provisional row's bytes leaves exactly this shape,
+ // and the caller is delivering the settled row for it: appending
+ // keeps the file the source of truth instead of failing a reply
+ // whose only other copy is the checkpoint.
+ transcripts::append_message(db.data_dir(), session_id, &session_created, &record)?;
+ db.conn().execute(
+ stamped,
+ params![session_id, record.id, text, record.is_error],
+ )?;
}
- db.conn().execute(
- "UPDATE messages SET text = ?3, is_error = ?4 WHERE session_id = ?1 AND id = ?2",
- params![session_id, record.id, text, record.is_error],
- )?;
} else {
+ update_delegation_snapshot(db, session_id, &record)?;
return Ok(());
}
} else {
@@@ -2196,25 -2375,44 +2377,49 @@@ fn rebuild_session_message_index
Ok(())
}
+ /// Whether the last copy of `message_id` is a provisional, streaming assistant
+ /// row.
+ ///
+ /// The index row mirrors that copy: it is inserted with the row, the append that
+ /// lands the terminal snapshot re-stamps it, and an index rebuild recomputes it
+ /// from the transcript. So this is one indexed lookup instead of a backwards walk
+ /// over the transcript's message lines, 64 lines per window — the shape that cost
+ /// 46 ms on a 104 MB transcript once the target sat 512 lines from the tail, and
+ /// a read of every byte of the file when it sat further, twice per turn.
+ ///
+ /// A NULL row is a message written before the column existed; those still answer
+ /// from the transcript, which is why an unrebuilt database behaves exactly as it
+ /// did before the cache. No row at all means the id has no index entry, which
+ /// agrees with the transcript's own "the id is not in the file" answer.
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")
- }),
- )
+ let indexed: Option<(String, Option<i64>)> = db
+ .conn()
+ .prepare_cached("SELECT role, streaming FROM messages WHERE id = ?1 AND session_id = ?2")?
+ .query_row(params![message_id, session_id], |row| {
+ Ok((row.get(0)?, row.get(1)?))
+ })
+ .optional()?;
+ match indexed {
+ Some((role, Some(streaming))) => Ok(role == "assistant" && streaming != 0),
+ Some((_, None)) => streaming_assistant_in_transcript(db, session_id, message_id),
+ None => Ok(false),
+ }
+ }
+
-/// The same question answered from the transcript: walk backwards from the tail
-/// 64 message lines at a time and stop at the last copy of the id. This is the
-/// fallback for a message the index cannot answer for, which is a row written
-/// before the cached column existed.
+ fn streaming_assistant_in_transcript(
+ db: &Database,
+ session_id: &str,
+ message_id: &str,
+ ) -> Result<bool> {
++ Ok(indexed_message_record(db, session_id, message_id)?
++ .is_some_and(|record| record_is_streaming(&record)))
+}
+
+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 {
diff --cc docs/spec/06-delivery/04-e2e-test-plan.md
index 96ba50a4f,0144091f1..9ad3ef5e7
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@@ -16805,15 -17068,61 +17068,74 @@@ host-created files. The full app's file
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.
++
+ ## BOM-marked UTF-16 text tools
+
+ - Create a UTF-16LE PowerShell build log with a BOM and CRLF, then ask the agent
+ to Read it. The tool and the next model request contain readable log lines.
+ - Edit a displayed line. The original BOM, endian and CRLF bytes are preserved.
+ - Repeat with UTF-16BE Chinese text. Ordinary binary files remain rejected.
+ - Automated coverage: `read_powershell_utf16le_log`,
+ `read_and_edit_utf16be_chinese_text`, and the existing binary/CRLF tool tests.
+
+
+ ## Delegate mutation recovery isolation
+
+ - Start two Task delegates editing the same file. Delegate A produces text and
+ fails three Edits; B fails twice and then completes. A is failed with
+ `MUTATION_RETRY_BUDGET_EXHAUSTED`, B completes, and the parent has no mutation
+ error. Resume A with a corrected task and verify successful completion.
+ - Run the same flow with failing shell patch commands. Repeat with one delegate
+ to prove that text preceding exhaustion does not become a completed report.
+ - While a delegate continues, a new parent prompt resets only the parent's
+ recovery counters. Both default and explicit delegate permissions retain the
+ same isolation.
+ - Automated provider-boundary flow: `node scripts/e2e-subagent-edit-isolation.mjs`
+ with optional `--single` and `--patch`; runtime tests cover parent restart.
+
+
+ ## Mutation recovery file aliases
+
+ - Retry a failing Edit using relative, absolute, `.`/`..`, directory-link and
+ Windows case-alias spellings of the same existing file. The third counted
+ failure terminates; changing spelling does not grant another recoverable-code
+ grace. Distinct files retain independent budgets.
+ - Successfully Edit or Write through an alias and retry: the count and grace
+ reset. Removing the file through a linked path clears its pre-mutation identity.
+ - Repeat relative/absolute aliases in a temporary session: its scratch root is
+ the relative base. Probe the directory's actual case sensitivity: distinct
+ case-sensitive files remain separate, while case aliases share an identity.
+ - Automated filesystem/runtime boundary coverage: `runtime.test.ts` and
+ `mutation-recovery.test.ts`; no UI, production profile or real provider is used.
+
+ ## Regenerate archival during quit
+
+ - Regenerate a completed answer and quit as soon as the terminal event arrives.
+ Restart the isolated profile: both revisions and their final messages remain
+ readable, and no `host-core disposed` archival failure appears in the logs.
+ - Hold the archive RPC while requesting quit. Host disposal waits for successful
+ archival; storage errors are logged. An unresponsive archive warns and allows
+ quit after the existing two-second bounded wait.
+ - Automated coverage: `shutdown-regenerate-persistence.test.mjs` and
+ `node scripts/e2e-regenerate-quit.mjs` (built Desktop, sidecar and host required;
+ Playwright can be supplied through `PI_TEST_PLAYWRIGHT`). Only the model server
+ is simulated in the Electron flow. The fixture profile and screenshots stay
+ under `.artifacts/` for inspection; no user profile or paid model is used.
+
+ ### E2E-COMPOSER-configured-context-window
+
+ - **Steps:** Save a 500K user context limit for a model whose catalog publishes 1M. Open the Composer model list, then send a short message and inspect context usage. Repeat with a catalog-owned limit and with discovery unavailable.
+ - **Expected:** The user-configured row and context inspector show 500K; a catalog-owned row follows the published limit; a configured model without discovery retains its saved context label. Model selection remains unchanged.
+ - **Status:** Automated unit regression in `apps/desktop/test/composer-models.test.mjs` covers user overrides, catalog inheritance, and missing discovery; the full save → picker → message → context-inspector path remains a manual validation scenario.