Files
paseo/packages/app/src/subagents/track-presentation.ts
T
77798b2e46 Show and stop agent background work (#6220)
* feat(server): add an in-memory store for agent background work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(claude): report background tasks as background work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(server): track agent background work in the agent manager

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(protocol): add agent background work messages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(server): serve and push agent background work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(client): expose agent background work on agent handles

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(sdk): document agent background work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(claude): cover background shells in background work end to end

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(client): resync background work subscriptions on every snapshot

subscribe() now lists the agent's background work each time the event
observation is established, so the listener starts with the current list
and catches up after a reconnect. A list answered after a newer update
is dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): answer background work lists without loading dormant agents

Background work lives only in memory, so a stored agent that is not
loaded has none. The list handler now answers [] from storage instead of
resuming the agent, and still rejects unknown, internal, and archived
agents. A new test pins that old apps never receive
agent.background_work.update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): read Claude background tasks defensively

The user's claude binary can differ from the SDK typings, so a task's
description is read as unknown and an empty or missing one becomes null.
Drop the monitor kind: Claude Monitor watches report as local_bash, so
kind is "shell" or "other" today. The store now copies only the wire
fields of each input.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(server): prove internal background work was emitted before checking globals

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(sdk): describe background work resync and feature gating

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(claude): cover background work reported by a retired query

The daemon stops reading a Claude query it no longer owns, so work that a
retired process still had queued cannot reach the background work list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(client): let background work subscribers handle a failed list read

When the list read that follows each subscription snapshot failed, the
error was only logged and the caller got neither the list nor a failure.
subscribe() now takes an optional onError that receives it; without one
the error is still logged. The read is not retried, since the next
reconnect reads the list again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(agents): show background work as active

Keep background activity visible after a foreground turn ends while preserving independent send and interrupt behavior.

* fix(agents): protect background work subscriptions

Keep internal work out of public updates and restore observation after a subscription failure.

* feat(agents): show Codex and OpenCode background work

Keep provider-owned shell activity visible after a turn ends while leaving foreground turn controls independent.

* feat(agents): stop individual background work

Wait for provider confirmation so stopping one background item leaves sibling work and foreground turn controls independent.

* refactor(agents): name background stop parameters

* test(website): isolate browser tests from live metadata

* test(agents): clarify background stop journeys

* fix(sdk): report background work subscription failures

Report setup failures so subscribers can replace an observation that the host released.

* fix(app): restore background work after reconnect

Wait for the host handshake before selecting the retained client so an offline pane starts observing when the connection returns.

* fix(agents): retain background shells across rewind

Preserve known live shell ownership when conversation history is rewound, and revoke it when the provider runtime exits.

* fix(website): launch test seeder across platforms

Invoke Wrangler through Node so local website test startup does not depend on an executable npm command shim.

* feat(agents): clarify background task details and tracks

Keep launch descriptions and commands distinct so background work remains identifiable, and allow composer tracks to scroll when space is limited.

* fix(agents): preserve active background work during archive

Keep background-running children out of bulk cleanup and warn before an individual archive. Preserve first taps on composer tracks while the keyboard is open.

* fix(codex): retain background terminals across rewind

Keep live terminal inventories attached to their originating threads so a fork does not hide or misroute their stop actions.

* fix(codex): scope background terminal identities to threads

Prevent commands on separate threads with the same provider process ID from sharing a stop target.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-06 19:49:49 +07:00

159 lines
6.0 KiB
TypeScript

import type { TFunction } from "i18next";
import type { ComposerTrackPillSegment } from "@/composer/tracks";
import type { SidebarStateBucket } from "@/utils/sidebar-agent-state";
import type { AgentLifecycleStatus } from "@getpaseo/protocol/agent-lifecycle";
import { STATUS_BUCKET_ORDER } from "@/utils/sidebar-agent-state";
import type { SubagentRow } from "./select";
import { isFinishedSubagent } from "./archive-finished";
import { providerSubagentLifecycleStatus } from "./provider-store";
function presentationStatus(row: SubagentRow) {
if (row.kind === "paseo") {
if (row.turn.phase === "open") return "running";
return row.status === "running" ? "idle" : row.status;
}
return providerSubagentLifecycleStatus(row.status);
}
/**
* A child's mark reports what it is doing, not whether anyone read it: the track is where a
* failed child stays visible after the parent's own attention is cleared.
*/
export function deriveSubagentStatusBucket(
status: AgentLifecycleStatus,
backgroundWork?: { count: number } | null,
): SidebarStateBucket {
if (status === "error") return "failed";
if (status === "running" || (backgroundWork?.count ?? 0) > 0) return "running";
return "done";
}
export interface SubagentRowPresentationData {
key: string;
kind: "agent";
label: string;
subtitle: string;
titleState: "ready" | "loading";
statusBucket: SidebarStateBucket | null;
}
export function buildSubagentRowPresentationData(row: SubagentRow): SubagentRowPresentationData {
// The task distinguishes siblings in a fan-out, so it names the row when present. Providers
// own the compact secondary context because model, effort, and usage semantics differ.
const description = resolveRowLabel(row.description);
const title = resolveRowLabel(row.title);
const label = description ?? title;
const providerSubtitle = row.kind === "provider" ? resolveRowLabel(row.subtitle) : null;
const subtitle = providerSubtitle ?? (description ? title : null);
const status = presentationStatus(row);
return {
key: `${row.kind}_subagent_${row.id}`,
kind: "agent",
label: label ?? "",
subtitle: subtitle ?? "",
titleState: label ? "ready" : "loading",
statusBucket: deriveSubagentStatusBucket(
status,
row.kind === "paseo" ? row.backgroundWork : undefined,
),
};
}
type ActiveStatusBucket = Exclude<SidebarStateBucket, "done">;
/** The sidebar's list order, minus the state that earns no mark. */
const ACTIVE_STATUS_BUCKET_ORDER = STATUS_BUCKET_ORDER.filter(
(bucket): bucket is ActiveStatusBucket => bucket !== "done",
);
/** One state the pill reports, and how many children are in it. */
interface SubagentStatusCount {
bucket: ActiveStatusBucket;
count: number;
}
/** Everything the pill draws. Built together so no mark can end up next to another one's count. */
export interface SubagentPillPresentation {
segments: ComposerTrackPillSegment[];
accessibilityLabel: string;
}
/**
* What the pill says about a fan-out, and which marks it says it with.
*
* A mark and a number sitting together answer the same question, so the pill cannot collapse a
* mixed fan-out into the most urgent state the way a sidebar project row does: a red dot beside
* "1 failed" over a child that is still working says the fan-out has stopped. Every state present
* gets its own mark and its own count, in the order the sidebar's status groups list them.
*
* It stays one line because subagent rows only ever reach three states — see
* `buildSubagentRowPresentationData`, which reports no attention of its own — so the pill is two
* segments at worst, and falls back to naming what it opens once nothing is happening.
*/
export function buildSubagentPillPresentation(
t: TFunction,
rows: readonly SubagentRow[],
): SubagentPillPresentation {
const counts = summarizeSubagentStatus(rows);
if (counts.length === 0) {
const label = totalLabel(t, rows.length);
return { segments: [{ bucket: null, text: label }], accessibilityLabel: label };
}
const labels = counts.map(({ bucket, count }) => statusLabel(t, bucket, count));
return {
segments: counts.map(({ bucket }, index) => ({ bucket, text: labels[index] ?? "" })),
// Marks separate the segments on screen; a screen reader needs the pause spelled out.
accessibilityLabel: labels.join(", "),
};
}
/** Wording comes from the sidebar's status groups — one name per state across the whole app. */
function statusLabel(t: TFunction, bucket: ActiveStatusBucket, count: number): string {
switch (bucket) {
case "running":
return t("subagents.pillLabelWorking", { count });
case "failed":
return t("subagents.pillLabelFailed", { count });
case "needs_input":
return count === 1
? t("subagents.pillLabelNeedsInputOne")
: t("subagents.pillLabelNeedsInputMany", { count });
case "attention":
return t("subagents.pillLabelReadyToReview", { count });
}
}
/** Nothing is happening, so the pill is back to naming what it opens. */
function totalLabel(t: TFunction, total: number): string {
return total === 1 ? t("subagents.pillLabelOne") : t("subagents.pillLabelMany", { count: total });
}
/**
* Empty when every child is done: a finished fan-out is not worth a colour above the composer.
*/
function summarizeSubagentStatus(rows: readonly SubagentRow[]): SubagentStatusCount[] {
const buckets = rows.map((row) => buildSubagentRowPresentationData(row).statusBucket);
return ACTIVE_STATUS_BUCKET_ORDER.flatMap((bucket) => {
const count = buckets.filter((candidate) => candidate === bucket).length;
return count > 0 ? [{ bucket, count }] : [];
});
}
export function countFinishedSubagents(rows: readonly SubagentRow[]): number {
return rows.filter(isFinishedSubagent).length;
}
export function resolveRowLabel(title: string | null | undefined): string | null {
if (typeof title !== "string") {
return null;
}
const normalized = title.trim();
if (!normalized) {
return null;
}
if (normalized.toLowerCase() === "new agent") {
return null;
}
return normalized;
}