Skip to content

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

feat(composer): surface active subagents above the input

v_wyxgwang15ad98b13d6f
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index 9a6456f9c..0209b8757 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -308,6 +308,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
});
registerSettingsIpc({
registrar,
+ sendToRenderer,
getHost,
getSidecar,
dataDir,
diff --git a/apps/desktop/electron/main/ipc/settings-ipc.ts b/apps/desktop/electron/main/ipc/settings-ipc.ts
index 6e9d2ed0e..19b5b10c3 100644
--- a/apps/desktop/electron/main/ipc/settings-ipc.ts
+++ b/apps/desktop/electron/main/ipc/settings-ipc.ts
@@ -1,4 +1,4 @@
-import { IPC, type UpdatePreference } from "@pi-desktop/shared";
+import { IPC, isSubagentStyle, type UpdatePreference } from "@pi-desktop/shared";
import type { AgentSidecar } from "../agent-sidecar";
import type { HostProcess } from "../host-process";
import type { IpcRegistrar } from "./types";
@@ -8,6 +8,7 @@ import { currentSystemProxyRelayUrl } from "../network-proxy";
export type SettingsIpcDependencies = {
registrar: IpcRegistrar;
+ sendToRenderer: (channel: string, payload: unknown) => void;
getHost: () => HostProcess | null;
getSidecar: () => AgentSidecar | null;
dataDir: string;
@@ -34,6 +35,7 @@ export type SettingsIpcDependencies = {
/** Register app settings and command-shell channels. */
export function registerSettingsIpc({
registrar,
+ sendToRenderer,
getHost,
getSidecar,
dataDir,
@@ -81,6 +83,9 @@ export function registerSettingsIpc({
let result: AppSettings;
try {
result = await host.call<AppSettings>("settings.set", validatedSettings);
+ if (isSubagentStyle(result.subagentStyle) && result.subagentStyle !== currentSettings.subagentStyle) {
+ sendToRenderer(IPC.event.settingsChanged, { subagentStyle: result.subagentStyle });
+ }
await liveCallService?.settingsWritten(result);
} finally {
releaseSettingsWrite?.();
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index ef36f4d32..8df03df79 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -33,6 +33,7 @@ import { ComposerAutocomplete } from "./ComposerAutocomplete";
import { AskToolCard } from "./AskToolCard";
import { PlanApprovalBar } from "./PlanApprovalBar";
import { TaskDock } from "./TaskDock";
+import { ComposerSubagents } from "../features/chat/composer/ComposerSubagents";
import { ModeRunStatusBar } from "../features/modes/ModeRunStatusBar";
import {
COMPOSER_MAX_VISIBLE_ROWS,
@@ -585,6 +586,9 @@ export function Composer({
onDragLeave={onComposerDragLeave}
onDrop={onComposerDrop}
>
+ {settings?.subagentStyle === "bar" && activeSessionId && localToolsAllowed && !nativeSession ? (
+ <ComposerSubagents key={activeSessionId} sessionId={activeSessionId} />
+ ) : null}
{inputFocused ? (
<ComposerAutocomplete
anchorRef={composerShellRef}
diff --git a/apps/desktop/src/components/SubagentPresenceBar.tsx b/apps/desktop/src/components/SubagentPresenceBar.tsx
new file mode 100644
index 000000000..439674465
--- /dev/null
+++ b/apps/desktop/src/components/SubagentPresenceBar.tsx
@@ -0,0 +1,107 @@
+import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "./ui";
+import { portalToBody } from "../lib/portal-visibility";
+import { isActiveDelegate, presenceMetrics, type SubagentPresenceItem as Item } from "../lib/subagent-presence";
+import { formatToolDuration } from "../lib/tool-display";
+import "../styles/subagent-presence.css";
+
+type Props = { items: readonly Item[]; onOpen: (item: Item) => void; onStop: (items: readonly Item[]) => void };
+type Popup = { id: string | null; anchor: HTMLButtonElement };
+const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
+const tokens = (n: number | null) => n === null ? "—" : compact.format(n).toLowerCase();
+const initials = (item: Item) => Array.from(item.agent.split("-").at(-1) || item.agent).slice(0,2).join("").toUpperCase();
+
+export function SubagentPresenceBar({ items, onOpen, onStop }: Props) {
+ const { t } = useTranslation();
+ const panelId = useId();
+ const [popup, setPopup] = useState<Popup | null>(null);
+ const [now, setNow] = useState(Date.now);
+ const panel = useRef<HTMLDivElement>(null);
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const suppressed = useRef(false);
+ const cancel = () => clearTimeout(timer.current);
+ const close = () => { cancel(); setPopup(null); };
+ const leave = () => { cancel(); timer.current = setTimeout(close, 160); };
+ const select = (id: string | null, anchor: HTMLButtonElement, immediate = false) => {
+ cancel();
+ if (suppressed.current) return;
+ const show = () => { setNow(Date.now()); setPopup({ id, anchor }); };
+ if (immediate) show(); else timer.current = setTimeout(show, 120);
+ };
+ useEffect(() => () => clearTimeout(timer.current), []);
+ useLayoutEffect(() => {
+ if (!popup) return;
+ const tick = setInterval(() => setNow(Date.now()), 1000);
+ const escape = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ event.stopPropagation(); close();
+ if (panel.current?.contains(document.activeElement)) {
+ suppressed.current = true; popup.anchor.focus(); suppressed.current = false;
+ }
+ };
+ const outside = (event: PointerEvent) => {
+ if (event.target instanceof Node && !panel.current?.contains(event.target) && !popup.anchor.contains(event.target)) close();
+ };
+ document.addEventListener("keydown", escape, true);
+ document.addEventListener("pointerdown", outside);
+ return () => { clearInterval(tick); document.removeEventListener("keydown", escape, true); document.removeEventListener("pointerdown", outside); };
+ }, [popup]);
+ const item = popup && items.find(row => row.id === popup.id);
+ const roster = !!popup && popup.id === null && items.length > 6;
+ useLayoutEffect(() => {
+ if (!popup) return;
+ const layer = panel.current;
+ if (!layer || !popup.anchor.isConnected) { close(); return; }
+ const place = () => {
+ const a = popup.anchor.getBoundingClientRect(), h = layer.offsetHeight;
+ layer.style.left = `${Math.max(8, Math.min(a.left, innerWidth - layer.offsetWidth - 8))}px`;
+ layer.style.top = `${Math.max(8, a.top - h >= 14 ? a.top - h - 6 : Math.min(a.bottom + 6, innerHeight - h - 8))}px`;
+ };
+ place();
+ const observer = new ResizeObserver(place); observer.observe(layer); observer.observe(popup.anchor);
+ window.addEventListener("scroll", place, true); window.addEventListener("resize", place);
+ return () => { observer.disconnect(); window.removeEventListener("scroll", place, true); window.removeEventListener("resize", place); };
+ }, [popup, item?.id, roster]);
+ const active = items.filter(isActiveDelegate);
+ if (!active.length) return null;
+ const name = (row: Item) => row.agent || t("chat.subagentUnnamed");
+ const status = (row: Item) => row.status === "queued" ? t("chat.subagentCreating") : t(`chat.subagentStatus.${row.status}`);
+ const metrics = (row: Item) => {
+ const { elapsed, speed } = presenceMetrics(row, now);
+ return { time: elapsed === null ? "—" : formatToolDuration(elapsed / 1000), turns: t("chat.presenceTurns", { n: row.turns ?? "—" }), usage: `↑${tokens(row.inputTokens)} ↓${tokens(row.outputTokens)}`, speed: speed === null ? "—" : t("chat.usageThroughput", {count: Math.round(speed)}) };
+ };
+ const trigger = (row?: Item) => {
+ const id = row?.id ?? null, expanded = popup?.id === id;
+ return <button type="button" key={id ?? 'overflow'} className={row ? 'presence-avatar' : 'presence-more'} data-status={row?.status}
+ aria-label={row ? `${name(row)} · ${status(row)}` : t("chat.subagentCount", {count: items.length})}
+ aria-haspopup="dialog" aria-expanded={expanded} aria-controls={expanded ? panelId : undefined}
+ onPointerEnter={e => select(id, e.currentTarget)} onPointerLeave={leave}
+ onFocus={e => select(id, e.currentTarget)} onBlur={leave} onClick={e => select(id, e.currentTarget, true)}
+ onKeyDown={e => { if (expanded && (e.key === 'ArrowDown' || (e.key === 'Tab' && !e.shiftKey))) { e.preventDefault(); panel.current?.querySelector('button')?.focus(); } }}>
+ {row ? initials(row) : `+${items.length - 6}`}</button>;
+ };
+ const openRecord = (row: Item) => { close(); onOpen(row); };
+ const renderCard = (row: Item) => {
+ const m = metrics(row);
+ return <><header><strong>{name(row)}</strong><span>{status(row)}</span></header>
+ <p>{row.task || '—'}</p><p className={row.status === 'running' ? 'presence-live' : undefined}>{t(isActiveDelegate(row) ? 'chat.presenceCurrent' : 'chat.presenceResult')}: {row.detail || '—'}</p>
+ <p className="presence-model">{row.model || '—'}</p><dl><dt>{t('chat.usageTotal')}</dt><dd>{m.usage}</dd><dt>{t('chat.usageThroughputLabel')}</dt><dd>{m.speed}</dd></dl>
+ <div className="presence-pair"><span>{t('modes.run.elapsed', {duration: m.time})}</span><span>{m.turns}</span></div>
+ <footer><Button size="sm" variant="ghost" onClick={() => openRecord(row)}>{t('chat.presenceRecord')}</Button>{row.status === 'running' && <Button size="sm" variant="ghost" onClick={() => onStop([row])}>{t('chat.stopSubagent')}</Button>}</footer></>;
+ };
+ const renderRoster = () => <><header><strong>{t('chat.subagentCount', {count: items.length})}</strong><small>{[...new Set(items.map(i => i.status))].map(s => `${items.filter(i=>i.status === s).length} ${status(items.find(i=>i.status === s)!)}`).join(' · ')}</small></header>
+ {[active, items.filter(i => !isActiveDelegate(i))].map((group, index) => group.length > 0 && <section key={index}><strong>{t(index ? 'chat.processCompleted' : 'chat.processRunning')} {group.length}</strong>
+ {group.map(row => { const m = metrics(row); return <button type="button" className="presence-row" key={row.id} onClick={() => openRecord(row)}>
+ <span className="presence-name"><b>{name(row)}</b> {status(row)}</span><span className="presence-time">{m.time} · {m.turns}</span>
+ <span className="presence-model">{row.model || '—'}</span><span className="presence-usage">{m.usage}</span><span>{m.speed}</span></button>; })}</section>)}
+ <footer><span>{t('chat.presenceRecord')}</span><Button size="sm" variant="ghost" disabled={!active.some(i => i.status === 'running')} onClick={() => onStop(active.filter(i => i.status === 'running'))}>{t('chat.stopAllSubagentsShort')}</Button></footer></>;
+ return <div className="subagent-bar" role="group" aria-label={t('chat.subagentTopology')}>
+ {items.slice(0,6).map(trigger)}{items.length > 6 && trigger()}
+ {popup && (item || roster) && portalToBody(<div id={panelId} role="dialog" aria-label={item ? name(item) : t('chat.subagentTopology')} ref={panel}
+ className={`presence-popup ${roster ? 'presence-roster' : 'presence-card'}`}
+ onPointerEnter={cancel} onPointerLeave={e => { if (!e.currentTarget.contains(document.activeElement)) leave(); }} onFocus={cancel}
+ onBlur={e => { if (!e.currentTarget.contains(e.relatedTarget)) leave(); }}>
+ {item ? renderCard(item) : renderRoster()}</div>)}
+ </div>;
+}
diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsx
index 2a6aceb20..36318e323 100644
--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx
+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx
@@ -543,11 +543,17 @@ export function useAppShellRuntime() {
// Host-originated settings writes (plugin `app.setTheme`) must reach the
// renderer store or the shell keeps painting the previous preference.
return api.onSettingsChanged((patch) => {
- if (patch.theme === undefined) return;
+ const style = patch.subagentStyle;
+ const stylePatch = style === "bar" || style === "transcript" ? { subagentStyle: style } as const : undefined;
+ if (patch.theme === undefined && !stylePatch) return;
const current = useAppStore.getState().settings;
if (!current) return;
useAppStore.setState({
- settings: { ...current, theme: String(patch.theme) as typeof current.theme },
+ settings: {
+ ...current,
+ ...(patch.theme === undefined ? {} : { theme: String(patch.theme) as typeof current.theme }),
+ ...stylePatch,
+ },
});
});
}, [ready]);
diff --git a/apps/desktop/src/features/chat/composer/ComposerSubagents.tsx b/apps/desktop/src/features/chat/composer/ComposerSubagents.tsx
new file mode 100644
index 000000000..f89ae2e48
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/ComposerSubagents.tsx
@@ -0,0 +1,24 @@
+import { SubagentPresenceBar } from "../../../components/SubagentPresenceBar";
+import { useMemo } from "react";
+import { projectSubagentPresence } from "../../../lib/subagent-presence";
+import { requestSubagentStop } from "../../../lib/subagent-stops";
+import { useAppStore } from "../../../stores/app-store";
+
+export function ComposerSubagents({ sessionId }: { sessionId: string }) {
+ const messages = useAppStore(state => state.activeSessionId === sessionId && state.isRunning ? state.messages : null);
+ const items = useMemo(() => messages ? projectSubagentPresence(messages) : [], [messages]);
+ if (!items.length) return null;
+ return (
+ <SubagentPresenceBar
+ items={items}
+ onOpen={item => {
+ const state = useAppStore.getState();
+ if (state.activeSessionId === sessionId) state.openSubagentTab(item.id, item.agent);
+ }}
+ onStop={selection => {
+ if (useAppStore.getState().activeSessionId !== sessionId) return;
+ void requestSubagentStop(sessionId, selection.map(item => item.id));
+ }}
+ />
+ );
+}
diff --git a/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsx b/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsx
index 6a660a6bc..c9fd2d85a 100644
--- a/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsx
+++ b/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsx
@@ -1,19 +1,12 @@
import { useChatSessionCapability } from "../../../hooks/use-chat-session-capability";
import { useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";
import { useEffect } from "react";
-import { create } from "zustand";
import { useTranslation } from "react-i18next";
import { Button, TooltipButton } from "../../../components/ui";
import { IconStop } from "../../../components/icons";
-import { api } from "../../../lib/api";
+import { requestSubagentStop, useStops } from "../../../lib/subagent-stops";
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,
@@ -33,7 +26,7 @@ export function SubagentStopButton({
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);
+ const stoppingRequest = busy && (!delegationId || !busy.ids || busy.ids.includes(delegationId));
useEffect(() => {
if (running || !sessionId || !delegationId || !stopping) return;
useStops.setState(state => ({ pending: {
@@ -43,27 +36,7 @@ export function SubagentStopButton({
}, [running, sessionId, delegationId, stopping]);
if (!running || !localToolsAllowed || !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 stop = () => requestSubagentStop(sessionId, delegationId ? [delegationId] : undefined);
const label = stoppingRequest || stopping
? t("chat.stoppingSubagents")
: delegationId
diff --git a/apps/desktop/src/features/settings/pages/ConversationSettings.tsx b/apps/desktop/src/features/settings/pages/ConversationSettings.tsx
index 1b5f3feb5..34e8129ba 100644
--- a/apps/desktop/src/features/settings/pages/ConversationSettings.tsx
+++ b/apps/desktop/src/features/settings/pages/ConversationSettings.tsx
@@ -6,7 +6,8 @@
* permission mode and the command shell. Nothing here changes what the model
* does — the Display card says so once, so no row has to repeat it.
*/
-import type { AppSettings } from "@pi-desktop/shared";
+import { isSubagentStyle, resolveSubagentStyle, type AppSettings } from "@pi-desktop/shared";
+import { SettingsMenuSelect } from "../../../components/settings/SettingsMenuSelect";
import { useTranslation } from "react-i18next";
import { SettingsToggle } from "../../../components/ui";
import { ShowThinkingRow } from "../../../components/settings/ShowThinkingRow";
@@ -63,6 +64,15 @@ export function ConversationSettings({
}
/>
</SettingsRow>
+ <SettingsRow title={t("settings.subagentStyle")} description={t("settings.subagentStyleDesc")}>
+ <SettingsMenuSelect label={t("settings.subagentStyle")} value={resolveSubagentStyle(settings)}
+ options={[
+ { id: "transcript", label: t("settings.subagentStyleTranscript") },
+ { id: "bar", label: t("settings.subagentStyleBar") },
+ ]}
+ onChange={value => { if (isSubagentStyle(value)) void saveSettings({ subagentStyle: value }); }}
+ />
+ </SettingsRow>
</SettingsCard>
<SettingsCard title={t("settings.chatInput")}>
diff --git a/apps/desktop/src/lib/subagent-presence.ts b/apps/desktop/src/lib/subagent-presence.ts
new file mode 100644
index 000000000..604d3e251
--- /dev/null
+++ b/apps/desktop/src/lib/subagent-presence.ts
@@ -0,0 +1,94 @@
+import type { UiMessage } from "@pi-desktop/shared";
+import { delegationIdForMessage } from "./subagent-panel";
+import { collectDelegationStatuses, collectDelegationTimings, delegationIsCreating, isDelegationActivityItem, subagentOutcome } from "./subagent-topology";
+import { delegationLifecycleKind, getToolSummary, isDelegationStartTool } from "./tool-display";
+import { toolResultPayload } from "./tool-presentation";
+
+const record = (value: unknown): Record<string, unknown> =>
+ value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
+const text = (value: unknown) => typeof value === "string" ? value.trim() : "";
+const count = (value: unknown) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
+
+export type PresenceStatus = "queued" | "running" | "completed" | "failed" | "stopped";
+export interface SubagentPresenceItem {
+ id: string;
+ agent: string;
+ status: PresenceStatus;
+ task: string;
+ detail: string;
+ model: string;
+ startedAt: number | null;
+ completedAt: number | null;
+ turns: number | null;
+ inputTokens: number | null;
+ outputTokens: number | null;
+}
+export function isActiveDelegate(item: SubagentPresenceItem) {
+ return item.status === "running" || item.status === "queued";
+}
+
+/** Inspect the current root turn only. A steering message does not start a new turn. */
+export function projectSubagentPresence(messages: readonly UiMessage[]): SubagentPresenceItem[] {
+ let start = messages.length;
+ while (start > 0) {
+ const m = messages[--start];
+ if (m.role === "user" && !m.parentToolCallId && !m.steering) break;
+ }
+ const tools = [];
+ const children = new Map<string, UiMessage[]>();
+ const snapshots = new Map<string, Record<string, unknown>>();
+ for (let i = start; i < messages.length; i++) {
+ const m = messages[i];
+ if (m.parentToolCallId) {
+ const rows = children.get(m.parentToolCallId);
+ if (rows) rows.push(m); else children.set(m.parentToolCallId, [m]);
+ } else if (m.role === "tool" && (isDelegationStartTool(m.toolName) || delegationLifecycleKind(m.toolName))) {
+ tools.push({kind: "tool" as const, message: m});
+ const payload = record(toolResultPayload(m));
+ for (const list of [payload.delegations, payload.stopped]) {
+ if (Array.isArray(list)) for (const entry of list) {
+ const row = record(entry);
+ if (typeof row.delegationId === "string") snapshots.set(row.delegationId, row);
+ }
+ }
+ }
+ }
+ const statuses = collectDelegationStatuses(tools);
+ const timings = collectDelegationTimings(tools);
+ const items = tools.filter(isDelegationActivityItem).map(({message: m}): SubagentPresenceItem => {
+ const id = delegationIdForMessage(m);
+ const payload = record(toolResultPayload(m));
+ const args = record(m.toolArgs);
+ const snapshot = snapshots.get(id);
+ const rows = children.get(m.toolCallId ?? m.id) ?? [];
+ const assistants = rows.filter(row => row.role === "assistant");
+ const latest = rows.at(-1);
+ const outcome = subagentOutcome(m, statuses);
+ const status = outcome === "running" ? (delegationIsCreating(m) ? "queued" : "running")
+ : outcome === "aborted" || outcome === "stopped" ? "stopped" : outcome === "completed" ? "completed" : "failed";
+ let inputTokens: number | null = null, outputTokens: number | null = null;
+ for (const row of assistants) if (row.usage) {
+ inputTokens = (inputTokens ?? 0) + row.usage.inputTokens;
+ outputTokens = (outputTokens ?? 0) + row.usage.outputTokens;
+ }
+ const usage = record(payload.usage);
+ const turnCount = Math.max(count(snapshot?.turns) ?? -1, count(payload.turns) ?? -1, assistants.length || -1);
+ return {
+ id, agent: text(payload.agent) || text(args.agent) || text(latest?.agentName), status,
+ task: text(args.description) || text(args.task),
+ detail: text(record(payload.error).message) || text(payload.report) ||
+ (latest?.role === "tool" ? [latest.toolName, getToolSummary(latest.toolName, latest.toolArgs)].filter(Boolean).join(" · ") : text(latest?.content)) || text(snapshot?.lastToolName),
+ model: text(payload.modelId) || text(assistants.at(-1)?.modelId) || text(args.model),
+ startedAt: timings.get(id)?.startedAt ?? count(Date.parse(m.createdAt)), completedAt: timings.get(id)?.completedAt ?? null,
+ inputTokens: count(usage.inputTokens) ?? inputTokens, outputTokens: count(usage.outputTokens) ?? outputTokens,
+ turns: turnCount >= 0 ? turnCount : null,
+ };
+ });
+ return items.some(isActiveDelegate) ? items.sort((a,b) => Number(isActiveDelegate(b)) - Number(isActiveDelegate(a))) : [];
+}
+
+export function presenceMetrics(item: SubagentPresenceItem, now: number) {
+ const end = item.completedAt ?? (isActiveDelegate(item) ? now : null);
+ const elapsed = item.startedAt !== null && end !== null ? Math.max(0, end - item.startedAt) : null;
+ return { elapsed, speed: elapsed && item.outputTokens !== null ? item.outputTokens * 1000 / elapsed : null };
+}
diff --git a/apps/desktop/src/lib/subagent-stops.ts b/apps/desktop/src/lib/subagent-stops.ts
new file mode 100644
index 000000000..fec3295a4
--- /dev/null
+++ b/apps/desktop/src/lib/subagent-stops.ts
@@ -0,0 +1,35 @@
+import { create } from "zustand";
+import { api } from "./api";
+import { useAppStore } from "../stores/app-store";
+
+/** One in-flight stop per session across every delegation surface. */
+export const useStops = create<{
+ busy: Record<string, { ids?: readonly string[] } | undefined>;
+ pending: Record<string, string[]>;
+}>(() => ({ busy: {}, pending: {} }));
+
+export async function requestSubagentStop(sessionId: string, selection?: readonly string[]) {
+ const state = useStops.getState();
+ if (state.busy[sessionId]) return;
+ const ids = selection?.filter(id => !state.pending[sessionId]?.includes(id));
+ // An empty selection must never be promoted to a session-wide stop.
+ if (ids && !ids.length) return;
+ useStops.setState(state => ({ busy: { ...state.busy, [sessionId]: { ids } } }));
+ try {
+ const result = await api.stopSubagents({ sessionId, ...(ids ? { delegationIds: ids } : {}) });
+ if (result.pending.length) {
+ 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 };
+ });
+ }
+}
diff --git a/apps/desktop/src/styles/subagent-presence.css b/apps/desktop/src/styles/subagent-presence.css
new file mode 100644
index 000000000..249124f72
--- /dev/null
+++ b/apps/desktop/src/styles/subagent-presence.css
@@ -0,0 +1,29 @@
+.subagent-bar { display: flex; align-items: center; min-height: 32px; padding-inline: 10px; }
+.presence-avatar, .presence-more { position: relative; z-index: 0; flex: none; height: 28px; min-width: 28px; border: 0; border-radius: var(--radius-full); background: var(--ds-bg-elevated-opaque); color: var(--ds-text-secondary); font-size: var(--text-xs); cursor: pointer; }
+.presence-avatar { width: 28px; padding: 0; }
+.presence-avatar + .presence-avatar { margin-inline-start: -8px; }
+.presence-more { margin-inline-start: 4px; border: 1px solid var(--ds-border-default); }
+.presence-avatar::before { content: ''; position: absolute; inset: 0; border: 1px solid var(--ds-border-default); border-radius: inherit; }
+.presence-avatar[data-status='running']::before, .presence-avatar[data-status='completed']::before { border: 2px solid var(--ds-success); }
+.presence-avatar[data-status='running']::before { border-inline-end-color: transparent; animation: presence-spin 1.05s linear infinite; }
+.presence-avatar[data-status='failed'] { color: var(--ds-error); }
+.presence-avatar[data-status='failed']::before { border: 2px solid currentColor; }
+.presence-avatar:is(:hover,:focus-visible) { transform: translateY(-2px); z-index: 5; }
+.presence-popup { box-sizing: border-box; position: fixed; z-index: 60; width: min(294px, calc(100vw - 16px)); max-height: calc(100vh - 16px); overflow: auto; padding: 12px; border: 1px solid var(--ds-border-default); border-radius: var(--radius-md); background: var(--ds-bg-elevated-opaque); box-shadow: var(--ds-shadow-dialog); color: var(--ds-text-primary); font-size: var(--text-sm); font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
+.presence-popup :is(header,footer), .presence-pair { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
+.presence-popup p { margin: 7px 0; max-height: 5em; overflow: auto; }
+.presence-popup footer { margin-top: 8px; border-top: 1px solid var(--ds-border-default); padding-top: 5px; }
+.presence-popup :is(small,dt,.presence-model) { color: var(--ds-text-secondary); }
+.presence-popup dl { display: grid; grid-template-columns: auto 1fr; gap: 2px 6px; margin: 6px 0; }
+.presence-popup dd { margin: 0; text-align: end; }
+.presence-live { background: linear-gradient(100deg, transparent 35%, color-mix(in srgb,var(--ds-success) 14%,transparent), transparent 65%); background-size: 240% 100%; animation: presence-sweep 2s linear infinite; }
+.presence-roster { width: min(404px,calc(100vw - 16px)); }
+.presence-roster section { margin-top: 8px; border-top: 1px solid var(--ds-border-default); padding-top: 6px; }
+.presence-row { display: grid; width: 100%; padding: 5px 0; grid-template-columns: minmax(0,1fr) 108px 64px; align-items: baseline; text-align: end; color: inherit; border: 0; background: transparent; font: inherit; cursor: pointer; }
+.presence-row:hover { background: var(--ds-bg-hover); }
+.presence-row .presence-name, .presence-row .presence-model { text-align: start; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.presence-time { grid-column: span 2; }
+.presence-usage::after { content: ' ·'; }
+@keyframes presence-spin { to { transform: rotate(360deg); } }
+@keyframes presence-sweep { to { background-position: -240% 0; } }
+@media (prefers-reduced-motion: reduce) { .presence-avatar::before, .presence-live { animation: none !important; } }
diff --git a/apps/desktop/test/subagent-presence-user-path.test.mjs b/apps/desktop/test/subagent-presence-user-path.test.mjs
new file mode 100644
index 000000000..c52f3075b
--- /dev/null
+++ b/apps/desktop/test/subagent-presence-user-path.test.mjs
@@ -0,0 +1,53 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { mkdtemp, writeFile, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { build } from 'esbuild';
+import { repositoryRoot, resolveElectronBinary } from '../../../scripts/e2e/boot.mjs';
+
+const fixture = `
+import React, {useState} from 'react';
+import {createRoot} from 'react-dom/client';
+import {flushSync} from 'react-dom';
+import i18n from 'i18next';
+import {initReactI18next} from 'react-i18next';
+import {en} from '@pi-desktop/i18n/locales/en';
+import {ConversationSettings} from './features/settings/pages/ConversationSettings';
+import {SubagentPresenceBar} from './components/SubagentPresenceBar';
+const items = Array.from({length:8},(_,n)=>({ id:String(n),agent:'agent-'+n,task:'Inspect inputs',detail:'Read files',model:'fixture-model',status:n<3?'running':n<7?'completed':'failed',inputTokens:18200,outputTokens:1900,turns:6,startedAt:Date.now()-24000,completedAt:null }));
+let opened, stopped;
+function Harness(){const [settings,set]=useState({subagentStyle:'unknown'});return <><ConversationSettings settings={settings} saveSettings={async patch=>set({...settings,...patch})}/>{settings.subagentStyle==='bar' && <div style={{overflow:'hidden'}}><SubagentPresenceBar items={items} onOpen={i=>opened=i.id} onStop={rows=>stopped=rows.map(i=>i.id).join(',')}/></div>}</>}
+window.probe=async()=>{
+ await i18n.use(initReactI18next).init({lng:'en',resources:{en:{translation:en}},interpolation:{escapeValue:false}});
+ flushSync(()=>createRoot(document.getElementById('root')).render(<Harness/>));
+ const check=(ok,msg)=>{if(!ok)throw Error(msg)};
+ const until=async(fn)=>{const deadline=performance.now()+3000;while(!fn()){if(performance.now()>deadline)throw Error('timed out: '+fn+'; focus='+document.activeElement.outerHTML.slice(0,300)+'; bar='+document.querySelector('.subagent-bar')?.innerHTML.slice(0,400));await new Promise(requestAnimationFrame)}};
+ const q=s=>document.querySelector(s),all=s=>[...document.querySelectorAll(s)];
+ check(!q('.subagent-bar'),'unknown style must not add a row');
+ const picker=q('button[aria-label="Subagent style"]');check(picker?.textContent.includes('In transcript'),'style fallback');
+ flushSync(()=>picker.click()); const option=all('button').find(b=>b.textContent.trim()==='Composer bar');check(option,'select option');flushSync(()=>option.click());
+ check(all('.presence-avatar').length===6 && q('.presence-more').textContent==='+2','overflow cap');
+ q('.presence-avatar').focus(); await until(()=>q('.presence-card'));check(q('.presence-card').textContent.includes('↑18.2k ↓1.9k'),'usage');
+ q('.presence-card footer button').click();check(opened==='0','single record');
+ const more=q('.presence-more');more.focus();await until(()=>q('.presence-roster'));check(more.getAttribute('aria-controls')===q('.presence-roster').id && !q('.presence-card'),'exclusive, linked roster');
+ check(all('.presence-roster section').map(g=>g.querySelectorAll('.presence-row').length).join(',')==='3,5','status groups');
+ q('.presence-roster footer button').click();check(stopped==='0,1,2','stop only running workers');
+ q('.presence-row').focus();document.activeElement.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true}));await until(()=>!q('.presence-roster'));check(document.activeElement===more && more.getAttribute('aria-expanded')==='false','Escape restores focus');
+ flushSync(()=>more.click());all('.presence-row').at(-1).click();check(opened==='7','failed worker record');
+ return true;
+};`;
+
+test('select bar, inspect a delegate, navigate and stop from the overflow roster', {skip: process.platform === 'linux' && !process.env.DISPLAY}, async()=>{
+ const root=repositoryRoot(), temp=await mkdtemp(join(tmpdir(),'pi-presence-'));
+ try {
+ await build({stdin:{contents:fixture,resolveDir:join(root,'apps/desktop/src'),loader:'tsx'},bundle:true,jsx:'automatic',format:'esm',outfile:join(temp,'fixture.js'),define:{'process.env.NODE_ENV':'"production"'}});
+ await writeFile(join(temp,'index.html'), '<meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'"><link rel="stylesheet" href="fixture.css"><div id="root"></div><script type="module" src="fixture.js"></script>');
+ await writeFile(join(temp,'main.cjs'),`const {app,BrowserWindow}=require('electron');app.setPath('userData',require('node:path').join(__dirname,'profile'));app.whenReady().then(async()=>{const w=new BrowserWindow({show:false,webPreferences:{backgroundThrottling:false}});w.webContents.on('console-message',e=>console.error(e.message));w.show();w.focus();await w.loadFile(require('node:path').join(__dirname,'index.html'));await w.webContents.executeJavaScript('window.probe()');console.log('PASS presence');app.exit(0)}).catch(e=>{console.error(e);app.exit(1)});`);
+ const env={...process.env};delete env.ELECTRON_RUN_AS_NODE;
+ const {stdout}=await promisify(execFile)(resolveElectronBinary(root).electronBinary,[join(temp,'main.cjs')],{env,timeout:30000});
+ assert.match(stdout,/PASS presence/);
+ } finally {await rm(temp,{recursive:true,force:true,maxRetries:5});}
+});
diff --git a/apps/desktop/test/subagent-presence.test.mjs b/apps/desktop/test/subagent-presence.test.mjs
new file mode 100644
index 000000000..8b6a05e53
--- /dev/null
+++ b/apps/desktop/test/subagent-presence.test.mjs
@@ -0,0 +1,29 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { register } from 'node:module';
+register(new URL('./helpers/ts-import-hooks.mjs', import.meta.url));
+const { projectSubagentPresence, presenceMetrics } = await import('../src/lib/subagent-presence.ts');
+const { resolveSubagentStyle } = await import('@pi-desktop/shared');
+const task = (id, status) => ({ id, role: 'tool', toolName: 'Task', toolCallId: `call-${id}`, toolStatus: 'success', toolArgs: {agent:'worker',task:'Read files'}, toolResult:{details:{delegationId:id,status,modelId:'fixture',startedAt:1000,...(status==='running'?{}:{completedAt:3000})}} });
+const child = (id, inputTokens, outputTokens) => ({role:'assistant',id,parentToolCallId:'call-a',content:'Reading files',usage:{inputTokens,outputTokens}});
+
+test('only the current turn contributes; root usage and lifecycle rows are not delegates', () => {
+ const messages = [task('old','running'), {role:'user'}, task('b','failed'), task('a','running'), child('1',22,4),{role:'user',steering:true},child('2',30,6),{role:'assistant',usage:{inputTokens:999,outputTokens:888}}];
+ const [a,b] = projectSubagentPresence(messages);
+ assert.deepEqual([a.id,a.turns,a.inputTokens,a.outputTokens,a.detail],['a',2,52,10,'Reading files']);
+ assert.deepEqual(presenceMetrics(a,6000),{elapsed:5000,speed:2});
+ assert.deepEqual([b.id,b.status,b.inputTokens],['b','failed',null]);
+ assert.deepEqual(presenceMetrics(b,9000),{elapsed:2000,speed:null});
+ assert.deepEqual(projectSubagentPresence([...messages,{role:'user'}]),[]);
+ assert.deepEqual(projectSubagentPresence([task('a','completed')]),[]);
+});
+test('creating and terminal snapshots are not mistaken for live running workers', () => {
+ const queued = { ...task('q','running'), toolResult:undefined,toolStatus:'running' };
+ const stale = {role:'tool',toolName:'TaskList',toolResult:{details:{delegations:[{delegationId:'b',status:'running'}]}}};
+ const [q,b] = projectSubagentPresence([task('b','failed'),queued,stale]);
+ assert.deepEqual([q.status,b.status],['queued','failed']);
+});
+test('style is opt-in, including with unknown stored values', () => {
+ for(const setting of [undefined,{}, {subagentStyle:'future'}]) assert.equal(resolveSubagentStyle(setting),'transcript');
+ assert.equal(resolveSubagentStyle({subagentStyle:'bar'}),'bar');
+});
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index 67b05fe85..988c27a59 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -364,10 +364,18 @@ so no row repeats it.
- **Display** card, in rendered order: the **Show thinking** toggle with its
**Auto-fold finished thinking** sub-row, the **Transcript display** segmented
control with its **Auto-fold finished groups** sub-row, **Context usage
- display** (remaining or used), **Smooth streaming**, and **Inline
- visualizations**. Context usage display controls whether the composer toolbar
- context ring and its popover lead with the remaining or the used capacity
- figure; the default is remaining.
+ display** (remaining or used), **Smooth streaming**, **Inline
+ visualizations**, and **Subagent style**. Context usage display controls whether
+ the composer toolbar context ring and its popover lead with the remaining or
+ the used capacity figure; the default is remaining.
+- **Subagent style** defaults to **In transcript** (also for an absent or unknown
+ `subagentStyle`). **Composer bar** adds a session-scoped avatar row above the
+ input while delegates are active; it is independent of the collapsible task
+ dock. Neither style removes topology cards, lifecycle rows or Work panel tabs.
+ Focus or hover an avatar for its current step or result, model, input/output
+ tokens, elapsed time, average output tokens per elapsed second and turns.
+ Unavailable measurements are not estimated. After six avatars, `+N` opens
+ the grouped roster. Both surfaces offer transcript navigation and stop actions.
- **Input & links** card: the **Enter-to-send** control, the large text paste
threshold, and the **Link open destination**. The threshold controls when a
text-only paste becomes a temporary session-scratch file; it defaults to 600
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index d8fbb21d7..d99e0981e 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -144,6 +144,14 @@ profiles, data directories, sockets, ports, logs, and artifacts. Install or
rebuild dependencies only when the host environment is missing or incompatible
and record the reason. Clean CI and release runners may install from lockfiles.
+From a fresh request worktree, run `node scripts/reuse-worktree-deps.mjs` with
+the same Node version/ABI as the primary installation. It links installed
+third-party packages and points `@pi-desktop/*` at this worktree; build those
+workspace packages here. If the primary installation is stale, pass the path of
+another checkout of this repository with matching installed dependencies and
+keep it until the consuming worktree is removed. If none matches, use an
+isolated install. Never install, prune, or rebuild through shared links.
+
Use the root `package.json` as the source of truth for executable commands.
The minimum selection is:
diff --git a/docs/spec/06-delivery/e2e/conversation.md b/docs/spec/06-delivery/e2e/conversation.md
index ef1992558..667135b4c 100644
--- a/docs/spec/06-delivery/e2e/conversation.md
+++ b/docs/spec/06-delivery/e2e/conversation.md
@@ -1,5 +1,16 @@
# E2E Scenarios: Conversation and Sessions
+## E2E-SUBAGENT-composer-presence
+
+Start delegates in a local session. In transcript-only mode, verify the composer
+has no avatar row. Enable **Composer bar** in Conversation settings: the same
+running delegates appear above the input with their existing topology unchanged.
+Collapse the task dock; inspect an avatar and open its Work panel record. With
+more than six workers, focus `+N`, enter the grouped roster, and dismiss it with
+Escape. Stop a worker while another runs: its settled status remains visible;
+after the last worker settles the entire row disappears. Switch sessions and
+restart to verify isolation and the saved presentation preference.
+
## E2E-stop-navigation-running-state
Hold the history read after a successful local Stop, switch to another running session, then resolve the older session's history. Verify only the stopped session is settled, the new transcript remains and its toolbar still offers Stop. Also navigate synchronously during the hydration commit to exercise the final state writer. Coverage: `stop-navigation-running-state.test.mjs`, related smart-stop/terminal regressions, and `scripts/e2e-stop-navigation-running-state.mjs` using the production store and ComposerToolbar in Electron.
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 544d3f632..a0c1e06d7 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -666,6 +666,7 @@ export const de = {
"subagentCount_one": "{{count}} Subagent",
"subagentCount_other": "{{count}} Subagenten",
"subagentFinishedCount": "{{finished}}/{{total}} fertig",
+ presenceTurns: "Runden: {{n}}", presenceRecord: "Protokoll öffnen", presenceCurrent: "Aktuell", presenceResult: "Ergebnis",
"subagentCreating": "Starte Subagent…",
"subagentStatus": {
"running": "Läuft",
@@ -1770,6 +1771,10 @@ sklm: {
"infiniteProviderRetryDesc": "Netzwerk- und vorübergehende Anbieterfehler werden bis zum Erfolg wiederholt. Du kannst den Lauf weiterhin stoppen; der API-Verbrauch kann fortlaufen.",
"smoothStreaming": "Sanftes Streaming",
"smoothStreamingDesc": "Gibt gestreamten Text zeichenweise aus, um einen Schreibmaschineneffekt zu erzeugen. Wird automatisch deaktiviert, wenn das System reduzierte Bewegung bevorzugt.",
+ subagentStyle: "Subagentenanzeige",
+ subagentStyleDesc: "Laufende Subagenten zusätzlich zum Verlauf über dem Eingabefeld anzeigen.",
+ subagentStyleTranscript: "Im Verlauf",
+ subagentStyleBar: "Eingabeleiste",
"inlineVisualizations": "Inline-Visualisierungen",
"inlineVisualizationsDesc": "Zeigt die interaktiven HTML-Karten, die der Agent in das Visualisierungsverzeichnis der Sitzung schreibt. Standardmäßig aus: Der Prompt nennt kein Visualisierungsverzeichnis, der visualize-Skill wird zurückgehalten und vorhandene Referenzzeilen bleiben ausgeblendet.",
"preventScreenSleep": "Bildschirmsperre verhindern",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 017b1cde4..7a8622ec7 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -678,6 +678,7 @@ deleteRunningSessionBlocked: "Stop the running session before deleting it.",
subagentCount_one: "{{count}} subagent",
subagentCount_other: "{{count}} subagents",
subagentFinishedCount: "{{finished}}/{{total}} finished",
+ presenceTurns: "Turns: {{n}}", presenceRecord: "View record", presenceCurrent: "Current", presenceResult: "Result",
subagentCreating: "Starting subagent…",
subagentStatus: {
running: "Running",
@@ -1782,6 +1783,10 @@ sklm: {
infiniteProviderRetryDesc: "Keep retrying network and transient provider failures until the request succeeds. You can still stop the turn; API usage may continue while enabled.",
smoothStreaming: "Smooth streaming",
smoothStreamingDesc: "Release streamed text character by character for a typewriter effect. Automatically disabled when the system prefers reduced motion.",
+ subagentStyle: "Subagent style",
+ subagentStyleDesc: "Optionally show active delegates above the input as well as in the transcript.",
+ subagentStyleTranscript: "In transcript",
+ subagentStyleBar: "Composer bar",
inlineVisualizations: "Inline visualizations",
inlineVisualizationsDesc: "Show the interactive HTML cards the agent writes into the session's visualization directory. Off by default: the prompt advertises no visualization directory, the visualize skill is withheld, and existing reference lines stay hidden.",
preventScreenSleep: "Prevent screen sleep",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index b2bca047b..7b35b8793 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -666,6 +666,7 @@ export const es = {
"subagentCount_one": "{{count}} subagente",
"subagentCount_other": "{{count}} subagentes",
"subagentFinishedCount": "{{finished}}/{{total}} finalizado",
+ presenceTurns: "Turnos: {{n}}", presenceRecord: "Ver registro", presenceCurrent: "Actual", presenceResult: "Resultado",
"subagentCreating": "Iniciando subagente…",
"subagentStatus": {
"running": "En ejecución",
@@ -1770,6 +1771,10 @@ sklm: {
"infiniteProviderRetryDesc": "Reintenta los errores de red y temporales hasta que la solicitud tenga éxito. Puedes detener el turno; el uso de la API puede continuar.",
"smoothStreaming": "Transmisión suave",
"smoothStreamingDesc": "Libera el texto transmitido carácter por carácter para un efecto de máquina de escribir. Se desactiva automáticamente cuando el sistema prefiere movimiento reducido.",
+ subagentStyle: "Estilo de subagentes",
+ subagentStyleDesc: "Muestra los subagentes activos también sobre el cuadro de entrada.",
+ subagentStyleTranscript: "En la conversación",
+ subagentStyleBar: "Barra de entrada",
"inlineVisualizations": "Visualizaciones en línea",
"inlineVisualizationsDesc": "Muestra las tarjetas HTML interactivas que el agente escribe en el directorio de visualizaciones de la sesión. Desactivado por defecto: el prompt no anuncia ningún directorio de visualizaciones, la habilidad visualize no se ofrece y las líneas de referencia existentes quedan ocultas.",
"preventScreenSleep": "Evitar suspensión de pantalla",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 489f19476..7b0c5fc5b 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -666,6 +666,7 @@ export const fr = {
"subagentCount_one": "{{count}} sous-agent",
"subagentCount_other": "{{count}} sous-agents",
"subagentFinishedCount": "{{finished}}/{{total}} terminé",
+ presenceTurns: "Tours : {{n}}", presenceRecord: "Voir le journal", presenceCurrent: "En cours", presenceResult: "Résultat",
"subagentCreating": "Démarrage du sous-agent…",
"subagentStatus": {
"running": "En cours d'exécution",
@@ -1770,6 +1771,10 @@ sklm: {
"infiniteProviderRetryDesc": "Réessaie les erreurs réseau et temporaires jusqu’à la réussite. Vous pouvez toujours arrêter le tour ; la consommation d’API peut continuer.",
"smoothStreaming": "Streaming fluide",
"smoothStreamingDesc": "Libère le texte diffusé caractère par caractère pour un effet machine à écrire. Automatiquement désactivé lorsque le système préfère un mouvement réduit.",
+ subagentStyle: "Affichage des sous-agents",
+ subagentStyleDesc: "Afficher aussi les sous-agents actifs au-dessus du champ de saisie.",
+ subagentStyleTranscript: "Dans la conversation",
+ subagentStyleBar: "Barre de saisie",
"inlineVisualizations": "Visualisations intégrées",
"inlineVisualizationsDesc": "Affiche les cartes HTML interactives que l'agent écrit dans le répertoire de visualisations de la session. Désactivé par défaut : le prompt n'annonce aucun répertoire de visualisations, la compétence visualize est retirée et les lignes de référence existantes restent masquées.",
"preventScreenSleep": "Empêcher la mise en veille",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index b7669af48..6ab11af9e 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -675,6 +675,7 @@ export const ko = {
subagentCount_one: "서브에이전트 {{count}}개",
subagentCount_other: "서브에이전트 {{count}}개",
subagentFinishedCount: "{{finished}}/{{total}} 완료",
+ presenceTurns: "{{n}}라운드", presenceRecord: "기록 보기", presenceCurrent: "현재", presenceResult: "결과",
subagentCreating: "하위 에이전트 생성 중…",
subagentStatus: {
running: "실행 중",
@@ -1778,6 +1779,10 @@ sklm: {
infiniteProviderRetryDesc: "네트워크 및 일시적인 제공자 오류가 성공할 때까지 계속 재시도됩니다. 언제든 중지할 수 있지만 API 사용량이 계속 발생할 수 있습니다.",
smoothStreaming: "부드러운 스트리밍",
smoothStreamingDesc: "스트리밍 텍스트를 한 글자씩 타자기 효과로 표시합니다. 시스템에서 동작 줄이기를 선호하면 자동으로 비활성화됩니다.",
+ subagentStyle: "하위 에이전트 표시",
+ subagentStyleDesc: "대화 기록을 유지하면서 입력창 위에도 실행 상태를 표시합니다.",
+ subagentStyleTranscript: "대화 안에 표시",
+ subagentStyleBar: "입력창 표시줄",
inlineVisualizations: "인라인 시각화",
inlineVisualizationsDesc: "에이전트가 세션 시각화 디렉터리에 작성한 대화형 HTML 카드를 대화에 표시합니다. 기본적으로 꺼져 있습니다: 프롬프트에 시각화 디렉터리를 제공하지 않고 visualize 스킬을 숨기며 기존 참조 줄도 표시하지 않습니다.",
preventScreenSleep: "화면 절전 방지",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 4851ca322..d1fd37404 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -665,6 +665,7 @@ export const ptBR = {
subagentCount_one: "{{count}} subagente",
subagentCount_other: "{{count}} subagentes",
subagentFinishedCount: "{{finished}}/{{total}} finalizados",
+ presenceTurns: "Rodadas: {{n}}", presenceRecord: "Ver histórico", presenceCurrent: "Atual", presenceResult: "Resultado",
subagentCreating: "Iniciando subagente…",
subagentStatus: {
running: "Em execução",
@@ -1741,6 +1742,10 @@ export const ptBR = {
infiniteProviderRetryDesc: "Continua tentando indefinidamente em caso de falhas temporárias de rede ou do provedor. Ainda é possível interromper a rodada; enquanto esta opção estiver ativada, o consumo e os custos da API podem continuar.",
smoothStreaming: "Exibição gradual",
smoothStreamingDesc: "Exibe o texto recebido caractere por caractere, criando um efeito de máquina de escrever. É desativada automaticamente quando o sistema está configurado para reduzir animações.",
+ subagentStyle: "Exibição dos subagentes",
+ subagentStyleDesc: "Mostre os subagentes ativos também acima do campo de mensagem.",
+ subagentStyleTranscript: "Na conversa",
+ subagentStyleBar: "Barra de entrada",
inlineVisualizations: "Visualizações embutidas",
inlineVisualizationsDesc: "Mostra os cartões HTML interativos que o agente escreve no diretório de visualizações da sessão. Desativado por padrão: o prompt não anuncia diretório de visualizações, a habilidade visualize fica oculta e as linhas de referência existentes permanecem escondidas.",
preventScreenSleep: "Impedir suspensão da tela",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 58ec7817c..3fa63ffe5 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -675,6 +675,7 @@ export const tr = {
subagentCount_one: "{{count}} alt ajan",
subagentCount_other: "{{count}} alt ajan",
subagentFinishedCount: "{{finished}}/{{total}} bitti",
+ presenceTurns: "Tur: {{n}}", presenceRecord: "Kaydı aç", presenceCurrent: "Şimdi", presenceResult: "Sonuç",
subagentCreating: "Alt ajan başlatılıyor…",
subagentStatus: {
running: "Çalışıyor",
@@ -1772,6 +1773,10 @@ sklm: {
infiniteProviderRetryDesc: "Ağ ve geçici sağlayıcı hataları istek başarılı olana kadar yeniden denenir. Çalışmayı yine durdurabilirsiniz; açıkken API kullanımı sürebilir.",
smoothStreaming: "Düzgün akış",
smoothStreamingDesc: "Akan metni daktilo efekti için karakter karakter gösterir. Sistem hareket azaltmayı tercih ettiğinde otomatik devre dışı kalır.",
+ subagentStyle: "Alt ajan görünümü",
+ subagentStyleDesc: "Etkin alt ajanları sohbetin yanı sıra giriş alanının üzerinde de gösterin.",
+ subagentStyleTranscript: "Sohbet içinde",
+ subagentStyleBar: "Giriş çubuğu",
inlineVisualizations: "Satır içi görselleştirmeler",
inlineVisualizationsDesc: "Aracının oturumun görselleştirme dizinine yazdığı etkileşimli HTML kartlarını gösterir. Varsayılan olarak kapalı: istem görselleştirme dizinini bildirmez, visualize becerisi gizlenir ve mevcut referans satırları gösterilmez.",
preventScreenSleep: "Ekran uykusunu engelle",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 32557786f..da78dff7c 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -671,6 +671,7 @@ deleteRunningSessionBlocked: "请先停止运行中的会话,再删除它。",
subagentCount_one: "{{count}} 个 Subagent",
subagentCount_other: "{{count}} 个 Subagent",
subagentFinishedCount: "已完成 {{finished}}/{{total}}",
+ presenceTurns: "{{n}} 轮", presenceRecord: "查看记录", presenceCurrent: "当前", presenceResult: "结果",
subagentCreating: "正在创建子智能体…",
subagentStatus: {
running: "运行中",
@@ -1762,6 +1763,10 @@ sklm: {
infiniteProviderRetryDesc: "网络或临时服务故障会一直重试直到成功。仍可随时停止,但开启后可能持续消耗 API 用量。",
smoothStreaming: "平滑流式显示",
smoothStreamingDesc: "将流式文本逐字释放,产生打字机效果。系统开启“减少动态效果”时自动禁用。",
+ subagentStyle: "子代理样式",
+ subagentStyleDesc: "保留对话内记录,也可在输入框上方查看子代理的运行状态。",
+ subagentStyleTranscript: "对话内",
+ subagentStyleBar: "输入框贴靠条",
inlineVisualizations: "聊天内嵌可视化",
inlineVisualizationsDesc: "在对话中显示智能体写入会话可视化目录的交互式 HTML 卡片。默认关闭:不向模型提供可视化目录,同时隐藏 visualize 技能,历史引用行也不再显示。",
preventScreenSleep: "阻止屏幕休眠",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index ed8fb783f..2e830ffa8 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -671,6 +671,7 @@ deleteRunningSessionBlocked: "請先停止執行中的會話,再刪除它。",
subagentCount_one: "{{count}} 個 Subagent",
subagentCount_other: "{{count}} 個 Subagent",
subagentFinishedCount: "已完成 {{finished}}/{{total}}",
+ presenceTurns: "{{n}} 輪", presenceRecord: "查看記錄", presenceCurrent: "目前", presenceResult: "結果",
subagentCreating: "正在建立子智能體…",
subagentStatus: {
running: "執行中",
@@ -1762,6 +1763,10 @@ sklm: {
infiniteProviderRetryDesc: "網路或暫時性服務故障會持續重試直到成功。仍可隨時停止,但開啟後可能持續消耗 API 用量。",
smoothStreaming: "平滑串流顯示",
smoothStreamingDesc: "將串流文字逐字釋放,產生打字機效果。系統開啟「減少動態效果」時自動停用。",
+ subagentStyle: "子代理樣式",
+ subagentStyleDesc: "保留對話記錄,也可在輸入框上方查看子代理狀態。",
+ subagentStyleTranscript: "對話內",
+ subagentStyleBar: "輸入框貼靠列",
inlineVisualizations: "聊天內嵌視覺化",
inlineVisualizationsDesc: "在對話中顯示智慧代理寫入工作階段視覺化目錄的互動式 HTML 卡片。預設停用:不向模型提供視覺化目錄,同時隱藏 visualize 技能,歷史引用行也不再顯示。",
preventScreenSleep: "防止螢幕休眠",
diff --git a/packages/shared/src/changelog-de.ts b/packages/shared/src/changelog-de.ts
index 3c46257c1..83afd9c3f 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.24.0",
date: "2026-11-20",
highlights: [
+ "Aktiviere in den Unterhaltungseinstellungen die Leiste über dem Eingabefeld, um Status, Verbrauch und Protokolle der Subagenten ohne Scrollen zu sehen.",
"Bei einer Neuinstallation erzeugt das mitgelieferte Plugin „Offizielle Erweiterungen“ Sitzungstitel automatisch; Vorschläge, Entwurfsverbesserung und KI-Gedächtnis bleiben aus, bis du sie einschaltest.",
"Neue Aufgabe startet jetzt einen temporären Chat außerhalb von Projekten, und Unterhaltungen lassen sich zwischen Projekten oder zurück in den temporären Chat verschieben.",
"Auf der leeren Startseite wechselst du das Projekt per Klick auf den Projektnamen oder „temporär“ im Titel; das projektlose Ziel heißt jetzt überall Temporärer Chat.",
diff --git a/packages/shared/src/changelog-en.ts b/packages/shared/src/changelog-en.ts
index c1b20f6b2..29a68e04e 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.24.0",
date: "2026-11-20",
highlights: [
+ "Choose Composer bar in Conversation settings to track subagents, inspect usage and open their records without scrolling the transcript.",
"On a fresh install, session titles are generated automatically by the bundled Official enhancements plugin; suggestions, draft enhancement and AI memory stay off until you turn them on.",
"New task now starts a temporary chat outside any project, and conversations can move between projects or back to Temporary chat.",
"On the empty home, click the project name or \"temporarily\" in the title to switch projects; the project-free destination is now called Temporary chat everywhere.",
diff --git a/packages/shared/src/changelog-es.ts b/packages/shared/src/changelog-es.ts
index 41ffe50f3..6f43e8d12 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.24.0",
date: "2026-11-20",
highlights: [
+ "Activa la barra del cuadro de entrada en los ajustes de conversación para consultar el estado, el consumo y el registro de los subagentes sin desplazarte por el chat.",
"En una instalación nueva, el complemento incluido Mejoras oficiales genera automáticamente los títulos de las sesiones; las sugerencias, la mejora de borradores y la memoria de IA siguen desactivadas hasta que las actives.",
"Nueva tarea ahora inicia un chat temporal fuera de cualquier proyecto, y las conversaciones pueden moverse entre proyectos o volver a Chat temporal.",
"En la página de inicio vacía, haz clic en el nombre del proyecto o en «temporal» del título para cambiar de proyecto; el destino sin proyecto ahora se llama Chat temporal en todas partes.",
diff --git a/packages/shared/src/changelog-fr.ts b/packages/shared/src/changelog-fr.ts
index b5413bdd0..af7191f74 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.24.0",
date: "2026-11-20",
highlights: [
+ "Activez la barre au-dessus du champ de saisie dans les réglages de conversation pour consulter l’état, la consommation et le journal des sous-agents sans faire défiler la conversation.",
"Sur une nouvelle installation, le plugin intégré Améliorations officielles génère automatiquement les titres de session ; les suggestions, l'amélioration des brouillons et la mémoire IA restent désactivées jusqu'à ce que vous les activiez.",
"Nouvelle tâche ouvre désormais une discussion temporaire hors de tout projet, et les conversations peuvent passer d'un projet à l'autre ou revenir en Discussion temporaire.",
"Sur l'accueil vide, cliquez sur le nom du projet ou sur « temporairement » dans le titre pour changer de projet ; la destination sans projet s'appelle désormais partout Discussion temporaire.",
diff --git a/packages/shared/src/changelog-ko.ts b/packages/shared/src/changelog-ko.ts
index f831cb4f1..bd0c2588e 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.24.0",
date: "2026-11-20",
highlights: [
+ "대화 설정에서 입력창 표시줄을 선택하면 대화를 스크롤하지 않고도 하위 에이전트의 상태와 사용량을 확인하고 실행 기록을 열 수 있습니다.",
"새로 설치하면 기본 제공되는 공식 개선 플러그인이 세션 제목을 자동으로 만듭니다. 제안, 초안 개선, AI 메모리는 직접 켜기 전까지 꺼져 있습니다.",
"새 작업이 이제 프로젝트 밖에서 임시 채팅으로 시작되며, 대화를 프로젝트 간에 옮기거나 임시 채팅으로 되돌릴 수 있습니다.",
"빈 홈 화면 제목의 프로젝트 이름이나 \"임시\"를 클릭해 프로젝트를 전환할 수 있으며, 프로젝트가 없는 위치는 이제 어디서나 임시 채팅으로 표시됩니다.",
diff --git a/packages/shared/src/changelog-pt-BR.ts b/packages/shared/src/changelog-pt-BR.ts
index 48f491f76..9b402d429 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.24.0",
date: "2026-11-20",
highlights: [
+ "Ative a barra acima do campo de mensagem nas configurações da conversa para ver o estado, o consumo e o histórico dos subagentes sem rolar o chat.",
"Em uma instalação nova, o plugin incluído Melhorias oficiais gera automaticamente os títulos das sessões; sugestões, aprimoramento de rascunho e memória de IA continuam desligados até você ativá-los.",
"Nova tarefa agora inicia um chat temporário fora de qualquer projeto, e as conversas podem ser movidas entre projetos ou de volta para Chat temporário.",
"Na tela inicial vazia, clique no nome do projeto ou em \"temporariamente\" no título para trocar de projeto; o destino sem projeto agora se chama Chat temporário em todo lugar.",
diff --git a/packages/shared/src/changelog-tr.ts b/packages/shared/src/changelog-tr.ts
index 00c1f6494..ce76f4bf6 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.24.0",
date: "2026-11-20",
highlights: [
+ "Sohbeti kaydırmadan alt ajanların durumunu, kullanımını ve kayıtlarını görmek için konuşma ayarlarından giriş alanı çubuğunu seçin.",
"Yeni kurulumda, birlikte gelen Resmi geliştirmeler eklentisi oturum başlıklarını otomatik oluşturur; öneriler, taslak iyileştirme ve yapay zekâ belleği siz açana kadar kapalı kalır.",
"Yeni görev artık herhangi bir projenin dışında geçici bir sohbet başlatır ve sohbetler projeler arasında ya da Geçici sohbete geri taşınabilir.",
"Boş ana sayfada projeyi değiştirmek için başlıktaki proje adına veya \"geçici\" sözcüğüne tıklayın; projesiz hedefin adı artık her yerde Geçici sohbet.",
diff --git a/packages/shared/src/changelog-zh-CN.ts b/packages/shared/src/changelog-zh-CN.ts
index 4ba7b5fe3..4378dc791 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.24.0",
date: "2026-11-20",
highlights: [
+ "在「设置 → 对话」选择「输入框贴靠条」,无需滚动对话即可查看子代理状态、用量和运行记录。",
"全新安装时,内置的「官方增强」插件会自动生成会话标题;建议、草稿增强和 AI 记忆仍需手动开启。",
"「新任务」现在会在项目之外开启临时对话,对话也可以在项目之间移动,或移回临时对话。",
"空白首页标题中的项目名或「临时」可直接点击切换项目;不属于任何项目的位置统一称为「临时对话」。",
diff --git a/packages/shared/src/changelog-zh-TW.ts b/packages/shared/src/changelog-zh-TW.ts
index 53f94406c..b1a23f96e 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.24.0",
date: "2026-11-20",
highlights: [
+ "在對話設定中選擇輸入框貼靠列,不用捲動對話就能查看子代理狀態、用量與執行記錄。",
"全新安裝時,內建的「官方增強」外掛會自動產生對話標題;建議、草稿增強和 AI 記憶仍需手動開啟。",
"「新任務」現在會在專案之外開啟臨時對話,對話也可以在專案之間移動,或移回臨時對話。",
"空白首頁標題中的專案名稱或「臨時」可直接點選切換專案;不屬於任何專案的位置統一稱為「臨時對話」。",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index e22ef5695..3b2bc078e 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -49,6 +49,7 @@ export * from "./rpc-timeouts.js";
export * from "./rpc-limits.js";
export * from "./ndjson.js";
export * from "./subagent-definition.js";
+export * from "./subagent-style.js";
export * from "./mode-definition.js";
export * from "./mode-definition-parse.js";
export * from "./subagent-presets.js";
diff --git a/packages/shared/src/subagent-style.ts b/packages/shared/src/subagent-style.ts
new file mode 100644
index 000000000..5a6d943c8
--- /dev/null
+++ b/packages/shared/src/subagent-style.ts
@@ -0,0 +1,10 @@
+import type { AppSettings, SubagentStyle } from "./types/settings.js";
+
+export function isSubagentStyle(value: unknown): value is SubagentStyle {
+ return value === "transcript" || value === "bar";
+}
+
+/** Older or unknown settings retain the transcript-only UI without a write. */
+export function resolveSubagentStyle(settings?: Pick<AppSettings, "subagentStyle"> | null): SubagentStyle {
+ return settings?.subagentStyle === "bar" ? "bar" : "transcript";
+}
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index c03c2bc01..09c8b9935 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -39,6 +39,18 @@ export type CloseBehavior = "ask" | "tray" | "quit";
export type TranscriptDisplayMode = "flat" | "command-first" | "fully-folded";
+/**
+ * Where a running subagent is presented while it works (issue #2549).
+ *
+ * - `transcript`: delegates stay in the conversation transcript only.
+ * - `bar`: a session-scoped avatar row above the composer mirrors the running
+ * delegates; topology cards, lifecycle rows and Work panel tabs stay put.
+ *
+ * Presentation only: neither value changes what a delegate does or what the
+ * host executes.
+ */
+export type SubagentStyle = "transcript" | "bar";
+
/**
* Preferences for the user-supplied boot animation (D679 / ADR 0338).
*
@@ -257,6 +269,14 @@ export type AppSettings = {
* it because their tools write on the remote machine.
*/
inlineVisualizations?: boolean;
+ /**
+ * How a running subagent is presented (issue #2549): `transcript` keeps
+ * delegates in the conversation transcript only, `bar` adds a session-scoped
+ * avatar row above the composer. Absent and any unknown value read as
+ * `transcript`, so the field is written only when the user picks the bar;
+ * reading a missing field never persists the default. Presentation only.
+ */
+ subagentStyle?: SubagentStyle;
/**
* Prevent the display from sleeping while the app is running. Uses
* Electron's `powerSaveBlocker` with `prevent-display-sleep` on all
diff --git a/scripts/e2e-subagent-stop.mjs b/scripts/e2e-subagent-stop.mjs
index 5c1c62b69..aba9cd5d3 100644
--- a/scripts/e2e-subagent-stop.mjs
+++ b/scripts/e2e-subagent-stop.mjs
@@ -123,6 +123,11 @@ async function connect(port, type) {
}
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" };
+if (process.platform === "win32") {
+ env.USERPROFILE = env.HOME;
+ env.APPDATA = join(scratch, "roaming");
+ env.LOCALAPPDATA = join(scratch, "local");
+}
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"], detached: process.platform !== "win32" });
let output = "";
@@ -143,6 +148,7 @@ try {
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("settingsSet", { transcriptDisplayMode: "flat" })).ok, true);
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");
@@ -150,8 +156,30 @@ try {
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(async () => (await buttons()).length === 2, "two stop buttons").catch(async error => {
+ throw new Error(`${error.message}\nFixture UI: ${await page.evaluate('document.body.innerText.slice(-2200)')}`);
+ });
+ const bar = '.composer-shell > .subagent-bar:first-child';
+ const barVisible = () => page.evaluate(`!!document.querySelector(${JSON.stringify(bar)})`);
+ assert.equal(await barVisible(), false, "transcript-only is the default");
+ const settings = await invoke("settingsGet");
+ assert.equal(settings.ok, true);
+ const setStyle = async subagentStyle => {
+ const result = await invoke("settingsSet", { subagentStyle });
+ assert.equal(result.ok, true, JSON.stringify(result));
+ assert.equal((await invoke("settingsGet")).data.subagentStyle, subagentStyle);
+ };
+ await setStyle("bar");
+ await until(barVisible, "running delegates gain a composer bar without replacing topology");
+ assert.equal((await buttons()).length, 2);
+ await setStyle("transcript");
+ await until(async () => !await barVisible(), "switching back removes the entire bar");
+ await setStyle("bar");
+ await until(barVisible, "restored presence bar");
+ await page.evaluate(`document.querySelector('.presence-avatar').focus()`);
+ await until(() => page.evaluate(`!!document.querySelector('.presence-card footer button')`), "focus opens delegate card");
+ assert.equal(await page.evaluate(`document.querySelector('.presence-card').closest('.composer-shell') === null`), true);
+ await page.evaluate(`document.querySelector('.presence-card footer button').click()`);
await until(() => page.evaluate(`!!document.querySelector('.subagent-transcript-composer-controls .stop-btn')`), "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(`({
@@ -179,6 +207,7 @@ try {
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");
+ await until(async () => !await barVisible(), "last settlement removes the entire presence bar");
const invalid = await invoke("agentStopSubagents", { sessionId: setup.sessionId, delegationIds: [] });
assert.equal(invalid.ok, false, "empty selection must not mean stop-all");
await until(async () => {
diff --git a/scripts/reuse-worktree-deps.mjs b/scripts/reuse-worktree-deps.mjs
new file mode 100644
index 000000000..f0f3e397e
--- /dev/null
+++ b/scripts/reuse-worktree-deps.mjs
@@ -0,0 +1,56 @@
+// Run from a fresh request worktree. Links only; never install against this layout.
+import { execFileSync } from "node:child_process";
+import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, symlinkSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+const git = (...args) => execFileSync("git", args, { encoding: "utf8" }).trim();
+const root = realpathSync(git("rev-parse", "--show-toplevel"));
+const common = cwd => realpathSync.native(git("-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"));
+const primary = dirname(common(root));
+if (realpathSync.native(root) === primary) throw new Error("Run inside a dedicated worktree, not the primary checkout.");
+const main = process.argv[2] ? realpathSync.native(process.argv[2]) : primary;
+if (common(main) !== common(root)) throw new Error("Dependency source must belong to the same repository.");
+const installedLock = join(main, "node_modules/.pnpm/lock.yaml");
+if (!existsSync(installedLock)) throw new Error("Dependency source needs a complete pnpm installation first.");
+
+const manifests = ["package.json", "apps/*/package.json", "packages/*/package.json", "docs/package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", ".npmrc", "patches"];
+const installInputs = cwd => git("-C", cwd, "ls-files", "-z", "--", ...manifests).split("\0").filter(Boolean);
+const inputs = installInputs(main);
+const required = installInputs(root);
+if (inputs.join("\n") !== required.join("\n")) throw new Error("Workspace manifests or patches differ; use an isolated install.");
+for (const file of inputs) {
+ if (!readFileSync(join(main, file)).equals(readFileSync(join(root, file)))) throw new Error(`Different ${file}; use an isolated install.`);
+}
+// pnpm 12 prepends a separate package-manager document to the wanted lock.
+const projectLock = file => readFileSync(file, "utf8").replaceAll("\r\n", "\n").split(/^---$/m).at(-1).trim();
+if (projectLock(installedLock) !== projectLock(join(root, "pnpm-lock.yaml"))) throw new Error("Installed dependencies are stale; choose a compatible source checkout.");
+const packages = inputs.filter(path => /^(?:(?:apps|packages)\/[^/]+|docs)\/package\.json$/.test(path));
+const workspace = new Map(packages.map(file => [JSON.parse(readFileSync(join(root, file), "utf8")).name, join(root, dirname(file))]));
+const links = [];
+const directories = [];
+for (const folder of [".", ...packages.map(dirname)]) {
+ const source = join(main, folder, "node_modules");
+ if (!existsSync(source)) continue;
+ const dest = join(root, folder, "node_modules");
+ if (lstatSync(dest, { throwIfNoEntry: false })) throw new Error(`Refusing to overwrite ${dest}. Use a fresh worktree.`);
+ directories.push(dest);
+ for (const entry of readdirSync(source, { withFileTypes: true })) {
+ if (entry.name.startsWith(".") && ![".pnpm", ".bin"].includes(entry.name)) continue;
+ const from = join(source, entry.name);
+ const to = join(dest, entry.name);
+ if (entry.name === "@pi-desktop") {
+ directories.push(to);
+ for (const name of readdirSync(from)) {
+ const target = workspace.get(`@pi-desktop/${name}`);
+ if (!target) throw new Error(`Unknown workspace package @pi-desktop/${name}`);
+ links.push([target, join(to, name)]);
+ }
+ } else if (entry.isDirectory() || entry.isSymbolicLink()) {
+ links.push([realpathSync(from), to]);
+ }
+ }
+}
+for (const dir of directories) mkdirSync(dir);
+for (const [target, path] of links) symlinkSync(target, path, process.platform === "win32" ? "junction" : "dir");
+console.log(`Linked ${links.length} dependency directories. Workspace packages resolve inside ${root}.`);
+console.log("Build workspace packages here. Do not install, prune, or rebuild shared dependencies through these links.");
diff --git a/scripts/reuse-worktree-deps.test.mjs b/scripts/reuse-worktree-deps.test.mjs
new file mode 100644
index 000000000..c867055cb
--- /dev/null
+++ b/scripts/reuse-worktree-deps.test.mjs
@@ -0,0 +1,42 @@
+import assert from "node:assert/strict";
+import { execFileSync, spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+const script = fileURLToPath(new URL("./reuse-worktree-deps.mjs", import.meta.url));
+test("reuse refuses incompatible or existing installs and resolves internal packages locally", t => {
+ const tmp = mkdtempSync(join(tmpdir(), "pi-reuse-"));
+ t.after(() => rmSync(tmp, { recursive: true, force: true }));
+ const main = join(tmp, "main");
+ const wt = join(tmp, "task");
+ mkdirSync(join(main, "packages/shared"), { recursive: true });
+ const git = (...args) => execFileSync("git", ["-C", main, ...args], { stdio: "pipe" });
+ const run = cwd => spawnSync(process.execPath, [script], { cwd, encoding: "utf8" });
+ const manifest = '{"name":"@pi-desktop/shared"}';
+ writeFileSync(join(main, "packages/shared/package.json"), manifest);
+ writeFileSync(join(main, "pnpm-lock.yaml"), "lock");
+ git("init");
+ git("add", "packages/shared/package.json", "pnpm-lock.yaml");
+ git("-c", "user.name=Test", "-c", "[email protected]", "-c", "commit.gpgsign=false", "commit", "-m", "Fixture");
+ git("worktree", "add", "--detach", wt, "HEAD");
+ for (const path of [".pnpm/react", "@pi-desktop"]) mkdirSync(join(main, "node_modules", path), { recursive: true });
+ writeFileSync(join(main, "node_modules/.pnpm/lock.yaml"), "lock");
+ const kind = process.platform === "win32" ? "junction" : "dir";
+ symlinkSync(join(main, "packages/shared"), join(main, "node_modules/@pi-desktop/shared"), kind);
+ symlinkSync(join(main, "node_modules/.pnpm/react"), join(main, "node_modules/react"), kind);
+ assert.match(run(main).stderr, /dedicated worktree/);
+ writeFileSync(join(wt, "pnpm-lock.yaml"), "different");
+ assert.match(run(wt).stderr, /Different pnpm-lock/);
+ writeFileSync(join(wt, "pnpm-lock.yaml"), "lock");
+ writeFileSync(join(main, "node_modules/.pnpm/lock.yaml"), "old");
+ assert.match(run(wt).stderr, /Installed dependencies are stale/);
+ writeFileSync(join(main, "node_modules/.pnpm/lock.yaml"), "lock");
+ const result = run(wt);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(realpathSync.native(join(wt, "node_modules/react")), realpathSync.native(join(main, "node_modules/react")));
+ assert.equal(realpathSync.native(join(wt, "node_modules/@pi-desktop/shared")), realpathSync.native(join(wt, "packages/shared")));
+ assert.match(run(wt).stderr, /Refusing to overwrite/);
+});