🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(working-sidebar): show Claude Code background tasks in the Overview (#23198)
Bryan9c18f1cf800f
diff --git a/apps/cli/src/utils/TrpcIngestSink.test.ts b/apps/cli/src/utils/TrpcIngestSink.test.tsindex e2742157271..fd94d29880a 100644--- a/apps/cli/src/utils/TrpcIngestSink.test.ts+++ b/apps/cli/src/utils/TrpcIngestSink.test.ts@@ -68,4 +68,62 @@ describe('heterogeneous completion delivery', () => {await assertion;expect(mutate).toHaveBeenCalledTimes(7);});++ it('drops background tasks for the rest of the run once a server refuses them', async () => {+ const { ingestMutate, sink } = setup();+ const badRequest = Object.assign(new Error('Invalid input'), { data: { code: 'BAD_REQUEST' } });+ ingestMutate.mockRejectedValueOnce(badRequest).mockResolvedValue({ accepted: true });+ const chunk = {+ data: {},+ operationId: 'owned-op',+ stepIndex: 0,+ timestamp: 1,+ type: 'stream_chunk',+ };+ const task = { ...chunk, type: 'background_task' };++ await expect(sink.ingest([chunk, task] as any)).resolves.toEqual({ accepted: true });+ await sink.ingest([task, chunk] as any);++ expect(ingestMutate.mock.calls.map(([input]) => input.events.map((e: any) => e.type))).toEqual([+ ['stream_chunk', 'background_task'],+ ['stream_chunk'],+ ['stream_chunk'],+ ]);+ });++ it('keeps other refusals as they are', async () => {+ const { ingestMutate, sink } = setup();+ const badRequest = Object.assign(new Error('Invalid input'), { data: { code: 'BAD_REQUEST' } });+ ingestMutate.mockRejectedValue(badRequest);+ const chunk = {+ data: {},+ operationId: 'owned-op',+ stepIndex: 0,+ timestamp: 1,+ type: 'stream_chunk',+ };++ await expect(sink.ingest([chunk] as any)).rejects.toBe(badRequest);+ expect(ingestMutate).toHaveBeenCalledTimes(1);+ });++ it('sends nothing for a batch of only background tasks once the server refused them', async () => {+ const { ingestMutate, sink } = setup();+ const badRequest = Object.assign(new Error('Invalid input'), { data: { code: 'BAD_REQUEST' } });+ ingestMutate.mockRejectedValueOnce(badRequest);+ const task = {+ data: {},+ operationId: 'owned-op',+ stepIndex: 0,+ timestamp: 1,+ type: 'background_task',+ };++ // The refused batch held only tasks: dropping them leaves nothing to send.+ await expect(sink.ingest([task] as any)).resolves.toEqual({ accepted: true });+ await expect(sink.ingest([task, task] as any)).resolves.toEqual({ accepted: true });++ expect(ingestMutate).toHaveBeenCalledTimes(1);+ });});diff --git a/apps/cli/src/utils/TrpcIngestSink.ts b/apps/cli/src/utils/TrpcIngestSink.tsindex 61786f08642..da95bb919de 100644--- a/apps/cli/src/utils/TrpcIngestSink.ts+++ b/apps/cli/src/utils/TrpcIngestSink.ts@@ -14,7 +14,17 @@ import type { IngestAck, IngestSink } from './BatchIngester';* The CLI authenticates using the `LOBEHUB_JWT` env var (operation-scoped JWT* injected by the server before spawning the sandbox / desktop process).*/+const withoutBackgroundTasks = (events: AgentStreamEvent[]) =>+ events.filter((event) => event.type !== 'background_task');+export class TrpcIngestSink implements IngestSink {+ /**+ * Cleared once the server refused a batch for carrying `background_task`+ * events: a server that predates them rejects the whole batch at input+ * validation, so they are dropped for the rest of the run instead.+ */+ private sendBackgroundTasks = true;+constructor(private readonly client: TrpcClient,private readonly agentType: LocalHeterogeneousAgentType | LocalRuntimeHeterogeneousAgentType,@@ -53,6 +63,23 @@ export class TrpcIngestSink implements IngestSink {}async ingest(events: AgentStreamEvent[]): Promise<IngestAck> {+ const sendable = this.sendBackgroundTasks ? events : withoutBackgroundTasks(events);+ // Filtering emptied the batch, and an older server refuses an empty one:+ // nothing is left to deliver, so it counts as delivered.+ if (sendable.length === 0 && events.length > 0) return { accepted: true };+ try {+ return await this.send(sendable);+ } catch (error) {+ const code = (error as { data?: { code?: string } } | null)?.data?.code;+ const hasTasks = sendable.some((event) => event.type === 'background_task');+ if (code !== 'BAD_REQUEST' || !hasTasks) throw error;+ this.sendBackgroundTasks = false;+ const rest = withoutBackgroundTasks(sendable);+ return rest.length > 0 ? this.send(rest) : { accepted: true };+ }+ }++ private async send(events: AgentStreamEvent[]): Promise<IngestAck> {const ack = (await this.client.aiAgent.heteroIngest.mutate({agentType: this.agentType,assistantMessageId: this.assistantMessageId,diff --git a/apps/cli/src/utils/heteroSteer.ts b/apps/cli/src/utils/heteroSteer.tsindex 1217eeb56aa..cec88a7eeeb 100644--- a/apps/cli/src/utils/heteroSteer.ts+++ b/apps/cli/src/utils/heteroSteer.ts@@ -1,3 +1,6 @@+// Built-in control commands register themselves when the steer loop loads.+import './heteroStopTask';+import type {AgentContentBlock,AgentPromptInput,diff --git a/apps/cli/src/utils/heteroStopTask.test.ts b/apps/cli/src/utils/heteroStopTask.test.tsnew file mode 100644index 00000000000..1a382687fac--- /dev/null+++ b/apps/cli/src/utils/heteroStopTask.test.ts@@ -0,0 +1,99 @@+import { PassThrough } from 'node:stream';++import { ClaudeCodeLiveInput } from '@lobechat/heterogeneous-agents/spawn';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { dispatchHeteroControl } from './heteroControl';+import { HETERO_STOP_TASK_COMMAND, STOP_TASK_ANSWER_TIMEOUT_MS } from './heteroStopTask';++const createLiveInput = () => {+ const stdin = new PassThrough();+ const written: any[] = [];+ stdin.on('data', (chunk: Buffer) => {+ for (const raw of chunk.toString().split('\n')) if (raw) written.push(JSON.parse(raw));+ });+ return { live: new ClaudeCodeLiveInput(stdin), written };+};++/** Claude Code's answer, as recorded from `claude` 2.1.308. */+const answer = (requestId: string, response: Record<string, unknown>) =>+ `${JSON.stringify({ response: { request_id: requestId, ...response }, type: 'control_response' })}\n`;++const stop = (+ live: ClaudeCodeLiveInput | undefined,+ params: unknown,+ signal = new AbortController().signal,+) =>+ dispatchHeteroControl(+ { command: HETERO_STOP_TASK_COMMAND, createdAt: 1, id: 'ctl-1', params },+ {+ operationId: 'op-1',+ sendControlRequest: (request) => live?.sendControlRequest(request),+ signal,+ },+ );++describe('stop_task control handler', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('writes stop_task into the Claude Code stdin and reports ok once CC accepts', async () => {+ const { live, written } = createLiveInput();+ const report = stop(live, { taskId: 'bys1w0wxo' });++ await vi.waitFor(() => expect(written).toHaveLength(1));+ expect(written[0]).toEqual({+ request: { subtype: 'stop_task', task_id: 'bys1w0wxo' },+ request_id: expect.any(String),+ type: 'control_request',+ });+ live.observe(answer(written[0].request_id, { response: {}, subtype: 'success' }));++ await expect(report).resolves.toEqual({ status: 'ok' });+ });++ it('reports the error Claude Code answers with', async () => {+ const { live, written } = createLiveInput();+ const report = stop(live, { taskId: 'missing' });++ await vi.waitFor(() => expect(written).toHaveLength(1));+ live.observe(answer(written[0].request_id, { error: 'No task found', subtype: 'error' }));++ await expect(report).resolves.toEqual({ error: 'No task found', status: 'error' });+ });++ it('rejects a request without a task id', async () => {+ const { live, written } = createLiveInput();+ await expect(stop(live, {})).resolves.toMatchObject({ status: 'error' });+ expect(written).toEqual([]);+ });++ it('fails when the session no longer takes input', async () => {+ await expect(stop(undefined, { taskId: 't' })).resolves.toEqual({+ error: 'The Claude Code session no longer takes input',+ status: 'error',+ });+ });++ it('gives up when Claude Code never answers', async () => {+ vi.useFakeTimers();+ const { live } = createLiveInput();+ const report = stop(live, { taskId: 't' });++ await vi.advanceTimersByTimeAsync(STOP_TASK_ANSWER_TIMEOUT_MS);+ await expect(report).resolves.toMatchObject({ status: 'error' });+ });++ it('gives up when the run ends first', async () => {+ const { live } = createLiveInput();+ const controller = new AbortController();+ const report = stop(live, { taskId: 't' }, controller.signal);++ controller.abort();+ await expect(report).resolves.toEqual({+ error: 'The run ended before Claude Code answered',+ status: 'error',+ });+ });+});diff --git a/apps/cli/src/utils/heteroStopTask.ts b/apps/cli/src/utils/heteroStopTask.tsnew file mode 100644index 00000000000..1d36ad2d8f3--- /dev/null+++ b/apps/cli/src/utils/heteroStopTask.ts@@ -0,0 +1,27 @@+import { stopClaudeCodeTask } from '@lobechat/heterogeneous-agents/spawn';++import { type HeteroControlHandler, registerHeteroControlHandler } from './heteroControl';++export { STOP_TASK_ANSWER_TIMEOUT_MS } from '@lobechat/heterogeneous-agents/spawn';++/** The control command the server queues to stop one background task. */+export const HETERO_STOP_TASK_COMMAND = 'stop_task';++/**+ * Stop one Claude Code background task: write a `stop_task` control request+ * into the session's stdin and wait for Claude Code to accept it. The stop is+ * only proven by the task's `stopped` report, which reaches the server through+ * the run's normal event stream; this reports that CC took the request.+ */+export const stopTaskHandler: HeteroControlHandler = async ({+ params,+ sendControlRequest,+ signal,+}) => {+ const taskId = (params as { taskId?: unknown } | null)?.taskId;+ if (typeof taskId !== 'string' || !taskId) throw new Error('stop_task needs a taskId');++ await stopClaudeCodeTask(sendControlRequest, taskId, { signal });+};++registerHeteroControlHandler(HETERO_STOP_TASK_COMMAND, stopTaskHandler);diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex f5f56028afd..8a713f84668 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -203,6 +203,11 @@ export default class HeterogeneousAgentCtr extends ControllerModule {return (await this.getImplementation()).cancelSession(...args);}+ @IpcMethod()+ async stopBackgroundTask(...args: Parameters<Implementation['stopBackgroundTask']>) {+ return (await this.getImplementation()).stopBackgroundTask(...args);+ }+@IpcMethod()async stopSession(...args: Parameters<Implementation['stopSession']>) {return (await this.getImplementation()).stopSession(...args);diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.backgroundTask.test.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.backgroundTask.test.tsnew file mode 100644index 00000000000..4ff89dcd860--- /dev/null+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.backgroundTask.test.ts@@ -0,0 +1,83 @@+import { PassThrough } from 'node:stream';++import { ClaudeCodeLiveInput } from '@lobechat/heterogeneous-agents/spawn';+import { describe, expect, it, vi } from 'vitest';++import HeterogeneousAgentCtr from './HeterogeneousAgentImpl';++vi.mock('electron', () => ({+ BrowserWindow: { getAllWindows: () => [] },+ app: {+ getAppPath: vi.fn(() => '/fake/appPath'),+ getPath: vi.fn((name: string) => `/fake/${name}`),+ getVersion: vi.fn(() => '1.0.0-test'),+ isPackaged: false,+ on: vi.fn(),+ quit: vi.fn(),+ },+ ipcMain: { handle: vi.fn() },+}));++vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ verbose: vi.fn(),+ warn: vi.fn(),+ }),+}));++const createCtr = (sessions: Record<string, unknown>) => {+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath: '/fake/storage',+ storeManager: { get: vi.fn() },+ } as any);+ const map = (ctr as any).sessions as Map<string, unknown>;+ for (const [id, session] of Object.entries(sessions)) map.set(id, session);+ return ctr;+};++describe('HeterogeneousAgentCtr.stopBackgroundTask', () => {+ it('asks the SDK session to stop the task', async () => {+ const stopTask = vi.fn().mockResolvedValue(undefined);+ const ctr = createCtr({ s1: { sdkSession: { stopTask } } });++ await ctr.stopBackgroundTask({ sessionId: 's1', taskId: 'bys1w0wxo' });++ expect(stopTask).toHaveBeenCalledWith('bys1w0wxo');+ });++ it('writes stop_task into a CLI spawned with live input (Steer)', async () => {+ const stdin = new PassThrough();+ const written: any[] = [];+ stdin.on('data', (chunk: Buffer) => {+ for (const raw of chunk.toString().split('\n')) if (raw) written.push(JSON.parse(raw));+ });+ const liveInput = new ClaudeCodeLiveInput(stdin);+ const ctr = createCtr({ cli: { liveInput, process: {} } });++ const stopping = ctr.stopBackgroundTask({ sessionId: 'cli', taskId: 'bys1w0wxo' });+ await vi.waitFor(() => expect(written).toHaveLength(1));+ expect(written[0]).toMatchObject({+ request: { subtype: 'stop_task', task_id: 'bys1w0wxo' },+ type: 'control_request',+ });+ liveInput.observe(+ `${JSON.stringify({+ response: { request_id: written[0].request_id, response: {}, subtype: 'success' },+ type: 'control_response',+ })}\n`,+ );+ await expect(stopping).resolves.toBeUndefined();+ });++ it('refuses a one-shot CLI run, whose stdin closed after the prompt', async () => {+ const ctr = createCtr({ cli: { process: {} } });++ await expect(ctr.stopBackgroundTask({ sessionId: 'cli', taskId: 't' })).rejects.toThrow(+ 'cannot stop a single background task',+ );+ await expect(ctr.stopBackgroundTask({ sessionId: 'gone', taskId: 't' })).rejects.toThrow();+ });+});diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex b38d895e0a5..85ff544f720 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -85,6 +85,7 @@ import {resolveCliSpawnPlan,resolveCodexInitialModel,spawnDshAcpSession,+ stopClaudeCodeTask,} from '@lobechat/heterogeneous-agents/spawn';import {buildClaudeCodeReplayTurn,@@ -166,7 +167,16 @@ import {createLiveCliAdapter,writeCliPrompt,} from './heterogeneousAgentLiveInput';-import type { AgentSession, CliTraceSession, SendPromptParams } from './heterogeneousAgentSession';+import type {+ AgentSession,+ CancelSessionParams,+ CliTraceSession,+ GetSessionInfoParams,+ SendPromptParams,+ StopBackgroundTaskParams,+ StopSessionParams,+ SubmitInterventionParams,+} from './heterogeneousAgentSession';import {claudeProfileDirOf,closeActiveAcpSessions,@@ -316,30 +326,6 @@ interface BrowserRunBinding {topicId?: string;}-interface CancelSessionParams {- sessionId: string;-}--interface SubmitInterventionParams {- cancelled?: boolean;- /** When set, signals user-cancelled or timeout — the bridge resolves with isError. */- cancelReason?: 'timeout' | 'user_cancelled';- /** Operation id stamped on the request the renderer is responding to. */- operationId: string;- /** Structured user answer; ignored when `cancelled` is true. */- result?: unknown;- /** Correlation key carried on the original `agent_intervention_request`. */- toolCallId: string;-}--interface StopSessionParams {- sessionId: string;-}--interface GetSessionInfoParams {- sessionId: string;-}-/*** A runtime dispatcher decides whether it handles a prompt for its agent* type. Returns `true` when handled (the caller returns early); `false` when@@ -3184,6 +3170,20 @@ export default class HeterogeneousAgentCtr {}}+ /**+ * Stop one background task of a Claude Code run whose input is still open:+ * the SDK session, or a CLI spawned with live input (Steer); a one-shot CLI+ * closed its stdin. Resolves once CC accepted the request; its `stopped`+ * report, the proof, reaches the renderer through the run's own stream.+ */+ async stopBackgroundTask({ sessionId, taskId }: StopBackgroundTaskParams): Promise<void> {+ const session = this.sessions.get(sessionId);+ if (session?.sdkSession) return session.sdkSession.stopTask(taskId);+ const live = session?.liveInput;+ if (!live) throw new Error('This run cannot stop a single background task');+ await stopClaudeCodeTask((request) => live.sendControlRequest(request), taskId);+ }+/*** Stop and clean up a session.*/diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.tsindex 09b806d0b42..fdd82ac87ff 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts@@ -825,3 +825,33 @@ export const sendPromptWithAcpSession = async (});}};++export interface CancelSessionParams {+ sessionId: string;+}++export interface SubmitInterventionParams {+ cancelled?: boolean;+ /** When set, signals user-cancelled or timeout — the bridge resolves with isError. */+ cancelReason?: 'timeout' | 'user_cancelled';+ /** Operation id stamped on the request the renderer is responding to. */+ operationId: string;+ /** Structured user answer; ignored when `cancelled` is true. */+ result?: unknown;+ /** Correlation key carried on the original `agent_intervention_request`. */+ toolCallId: string;+}++export interface StopSessionParams {+ sessionId: string;+}++export interface GetSessionInfoParams {+ sessionId: string;+}++export interface StopBackgroundTaskParams {+ sessionId: string;+ /** Claude Code `task_id` of the background task to stop. */+ taskId: string;+}diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.stopBackgroundTask.test.ts b/apps/server/src/routers/lambda/aiAgent/hetero.stopBackgroundTask.test.tsnew file mode 100644index 00000000000..42082bef4c1--- /dev/null+++ b/apps/server/src/routers/lambda/aiAgent/hetero.stopBackgroundTask.test.ts@@ -0,0 +1,68 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { heteroRouter } from './hetero';++const mocks = vi.hoisted(() => ({+ operation: undefined as Record<string, unknown> | undefined,+ stopHeteroBackgroundTask: vi.fn(),+}));++vi.mock('@/server/services/aiAgent/steerQueue/heteroStopTask', () => ({+ stopHeteroBackgroundTask: mocks.stopHeteroBackgroundTask,+}));+vi.mock('./procedures', async () => {+ const { trpc } = await import('@/libs/trpc/lambda/init');+ const serverDB = {+ select: () => ({+ from: () => ({+ where: () => ({ limit: async () => (mocks.operation ? [mocks.operation] : []) }),+ }),+ }),+ };+ const procedure = trpc.procedure.use((opts) =>+ opts.next({ ctx: { ...opts.ctx, serverDB: serverDB as never } }),+ );+ return {+ aiAgentBaseProcedure: procedure,+ aiAgentWriteProcedure: procedure,+ heteroAgentProcedure: procedure,+ };+});++const caller = heteroRouter.createCaller({ userId: 'user-1' } as never);++beforeEach(() => {+ vi.clearAllMocks();+ mocks.operation = { agentId: 'agent-1', userId: 'user-1' };+ mocks.stopHeteroBackgroundTask.mockResolvedValue({ status: 'accepted' });+});++describe('aiAgent.stopHeteroBackgroundTask', () => {+ it('sends the stop over the run control channel and returns its result', async () => {+ await expect(+ caller.stopHeteroBackgroundTask({ operationId: 'op-1', taskId: 'bys1w0wxo' }),+ ).resolves.toEqual({ status: 'accepted' });+ expect(mocks.stopHeteroBackgroundTask).toHaveBeenCalledWith('op-1', 'bys1w0wxo');+ });++ it('passes through why a device could not stop the task', async () => {+ mocks.stopHeteroBackgroundTask.mockResolvedValue({ status: 'unreachable' });+ await expect(+ caller.stopHeteroBackgroundTask({ operationId: 'op-1', taskId: 'bys1w0wxo' }),+ ).resolves.toEqual({ status: 'unreachable' });+ });++ it("refuses another user's run", async () => {+ mocks.operation = { agentId: 'agent-1', userId: 'user-2' };+ await expect(+ caller.stopHeteroBackgroundTask({ operationId: 'op-1', taskId: 'bys1w0wxo' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });++ mocks.operation = undefined;+ await expect(+ caller.stopHeteroBackgroundTask({ operationId: 'op-missing', taskId: 'bys1w0wxo' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mocks.stopHeteroBackgroundTask).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.ts b/apps/server/src/routers/lambda/aiAgent/hetero.tsindex 00a3fcca58c..6c73fe85a11 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.ts@@ -31,6 +31,7 @@ import {reportHeteroControlResult,takeHeteroControl,} from '@/server/services/aiAgent/steerQueue/heteroControl';+import { stopHeteroBackgroundTask } from '@/server/services/aiAgent/steerQueue/heteroStopTask';import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';import {HeteroOperationPrincipalError,@@ -72,6 +73,7 @@ const AgentStreamEventSchema = z.object({'agent_intervention_response','step_start','step_complete',+ 'background_task','notify_update','error',]),@@ -165,6 +167,12 @@ const WaitHeteroSteerSchema = z.object({operationId: z.string().min(1),});+/** Schema for `aiAgent.stopHeteroBackgroundTask` — stop one Claude Code background task. */+const StopHeteroBackgroundTaskSchema = z.object({+ operationId: z.string().min(1),+ taskId: z.string().min(1).max(256),+});+/** Schema for `aiAgent.returnHeteroSteer` — the session could not take the message. */const ReturnHeteroSteerSchema = z.object({messageId: z.string().min(1),@@ -742,6 +750,35 @@ export const heteroRouter = router({workspaceId: ctx.workspaceId ?? undefined,}),),+ /**+ * Stop one Claude Code background task of a run hosted by `lh hetero exec`+ * (a connected device, the desktop gateway, the cloud sandbox). The request+ * rides the run's control channel; `accepted` means Claude Code took it, and+ * the task's `stopped` snapshot then arrives through the run's own stream.+ */+ stopHeteroBackgroundTask: aiAgentWriteProcedure+ .input(StopHeteroBackgroundTaskSchema)+ .mutation(async ({ input, ctx }) => {+ // Only the user who started the run controls its live process.+ const [operation] = await ctx.serverDB+ .select({ userId: agentOperations.userId })+ .from(agentOperations)+ .where(eq(agentOperations.id, input.operationId))+ .limit(1);+ if (operation?.userId !== ctx.userId) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Operation not found or not owned by the caller',+ });+ }+ await assertCanUseOperationAgent({+ db: ctx.serverDB,+ operationId: input.operationId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ return stopHeteroBackgroundTask(input.operationId, input.taskId);+ }),/** Token-only atomic resolution path used by Mobile review/deep links. */resolveHeteroIntervention: aiAgentWriteProcedure.input(ResolveHeteroInterventionReviewSchema)diff --git a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.tsindex ab331a77728..64ee8837041 100644--- a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts@@ -58,6 +58,7 @@ function expected(): Array<[name: string, type: 'mutation' | 'query']> {['scheduleAgentRun', 'mutation'],['setQueuedMessages', 'mutation'],['startExecution', 'mutation'],+ ['stopHeteroBackgroundTask', 'mutation'],['stopPendingApproval', 'mutation'],['submitHeteroIntervention', 'mutation'],['updateClientTaskThreadStatus', 'mutation'],diff --git a/apps/server/src/routers/lambda/deviceWorkspaceGuard.taskOutput.test.ts b/apps/server/src/routers/lambda/deviceWorkspaceGuard.taskOutput.test.tsnew file mode 100644index 00000000000..344b178cfb0--- /dev/null+++ b/apps/server/src/routers/lambda/deviceWorkspaceGuard.taskOutput.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it, vi } from 'vitest';++import type { DeviceModel } from '@/database/models/device';++import {+ assertWorkspaceRootApproved,+ claudeCodeProjectKey,+ isClaudeCodeTaskOutputDir,+} from './deviceWorkspaceGuard';++const SESSION = '6dd6da3d-4cce-4776-b75b-3bea0332796d';+const ROOT = '/Users/me/proj';+const tasksDir = (cwd: string, tmp = '/private/tmp/claude-501') =>+ `${tmp}/${claudeCodeProjectKey(cwd)}/${SESSION}/tasks`;++const model = (workingDirs: string[]) =>+ ({+ findByDeviceId: vi+ .fn()+ .mockResolvedValue({ workingDirs: workingDirs.map((path) => ({ path })) }),+ }) as unknown as DeviceModel;++describe('Claude Code background task output grant', () => {+ it('keys a project the way Claude Code names its directory', () => {+ // Recorded from claude 2.1.308: cwd `/private/tmp/claude-501/-Users-…/scratchpad/ws`.+ expect(claudeCodeProjectKey('/private/tmp/claude-501/-Users-me/.claude/ws')).toBe(+ '-private-tmp-claude-501--Users-me--claude-ws',+ );+ });++ it('lets a preview read the tasks directory of an approved project', async () => {+ await expect(+ assertWorkspaceRootApproved(model([ROOT]), 'dev-1', tasksDir(ROOT)),+ ).resolves.toBeUndefined();+ expect(isClaudeCodeTaskOutputDir(`${tasksDir(ROOT)}/`, [ROOT])).toBe(true);+ expect(isClaudeCodeTaskOutputDir(tasksDir(ROOT, '/tmp/claude-0'), [ROOT])).toBe(true);+ });++ it('matches a macOS /tmp root through /private', () => {+ expect(isClaudeCodeTaskOutputDir(tasksDir('/private/tmp/ws'), ['/tmp/ws'])).toBe(true);+ expect(isClaudeCodeTaskOutputDir(tasksDir('/tmp/ws'), ['/private/tmp/ws'])).toBe(true);+ });++ it('refuses the tasks directory of a project that is not approved', async () => {+ await expect(+ assertWorkspaceRootApproved(model([ROOT]), 'dev-1', tasksDir('/Users/me/other')),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ // A sibling whose key only starts with the approved one is a different project.+ expect(isClaudeCodeTaskOutputDir(tasksDir(`${ROOT}-evil`), [ROOT])).toBe(false);+ });++ it('refuses anything but the session tasks directory itself', () => {+ const base = `/private/tmp/claude-501/${claudeCodeProjectKey(ROOT)}`;+ expect(isClaudeCodeTaskOutputDir(base, [ROOT])).toBe(false);+ expect(isClaudeCodeTaskOutputDir(`${base}/${SESSION}`, [ROOT])).toBe(false);+ expect(isClaudeCodeTaskOutputDir(`${base}/${SESSION}/tasks/nested`, [ROOT])).toBe(false);+ expect(isClaudeCodeTaskOutputDir(`${base}/not-a-session/tasks`, [ROOT])).toBe(false);+ expect(isClaudeCodeTaskOutputDir(`${base}/${SESSION}/../${SESSION}/tasks`, [ROOT])).toBe(false);+ expect(isClaudeCodeTaskOutputDir(`relative/claude-1/x/${SESSION}/tasks`, [ROOT])).toBe(false);+ });+});diff --git a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts b/apps/server/src/routers/lambda/deviceWorkspaceGuard.tsindex c941bbc9c6b..503712af2bd 100644--- a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts+++ b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts@@ -126,6 +126,43 @@ const isWithinMemoryGrant = (isPathWithinRoot(memoryDir, workingDirectory) && isProjectApproved(projectRoot),);+/**+ * Claude Code writes each background task's output to+ * `<tmp>/claude-<uid>/<project key>/<session id>/tasks/<task id>.output`, the+ * project key being the session's working directory with every+ * non-alphanumeric character replaced by `-`. The directory sits outside the+ * project, so a task's output is readable only through this derived grant: the+ * requested root must be exactly such a `tasks` directory whose project key+ * belongs to an approved root. Nothing is stored; the grant is re-derived from+ * the same server-owned roots on every read.+ */+const CLAUDE_CODE_TASK_OUTPUT_DIR =+ /^\/(?:[^/]+\/)*claude-\d+\/([^/]+)\/[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}\/tasks\/?$/i;++export const claudeCodeProjectKey = (cwd: string): string => cwd.replaceAll(/[^\da-z]/gi, '-');++/** macOS resolves `/tmp` and `/var` through `/private`; Claude Code keys the resolved path. */+const projectKeysOf = (root: string): string[] => {+ const trimmed = root.replace(/\/+$/, '');+ const aliases = [trimmed];+ if (/^\/(?:tmp|var)(?:\/|$)/.test(trimmed)) aliases.push(`/private${trimmed}`);+ if (/^\/private\/(?:tmp|var)(?:\/|$)/.test(trimmed))+ aliases.push(trimmed.slice('/private'.length));+ return aliases.map(claudeCodeProjectKey);+};++export const isClaudeCodeTaskOutputDir = (+ workingDirectory: string,+ approvedRoots: readonly string[],+): boolean => {+ if (workingDirectory.split('/').some((segment) => segment === '.' || segment === '..')) {+ return false;+ }+ const projectKey = CLAUDE_CODE_TASK_OUTPUT_DIR.exec(workingDirectory)?.[1];+ if (!projectKey) return false;+ return approvedRoots.some((root) => projectKeysOf(root).includes(projectKey));+};+/*** Validate that a client-supplied workspace root is actually one the user has* bound to this device.@@ -176,7 +213,8 @@ export const assertWorkspaceRootApproved = async (const approved =isApprovedRoot(workingDirectory) ||isWithinSkillRoots(deviceId, workingDirectory, isApprovedRoot) ||- isWithinMemoryGrant(deviceId, workingDirectory, isApprovedRoot);+ isWithinMemoryGrant(deviceId, workingDirectory, isApprovedRoot) ||+ isClaudeCodeTaskOutputDir(workingDirectory, approvedRoots);if (!approved) {throw new TRPCError({diff --git a/apps/server/src/services/aiAgent/steerQueue/heteroStopTask.test.ts b/apps/server/src/services/aiAgent/steerQueue/heteroStopTask.test.tsnew file mode 100644index 00000000000..93e53d3f66e--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/heteroStopTask.test.ts@@ -0,0 +1,48 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createHeteroControlFakeRedis } from '@/server/services/redis/heteroControl.fake';++import { reportHeteroControlResult, takeHeteroControl } from './heteroControl';+import { stopHeteroBackgroundTask, toHeteroStopTaskResult } from './heteroStopTask';++const getRedisServiceClient = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/redis/client', () => ({ getRedisServiceClient }));++beforeEach(() => {+ getRedisServiceClient.mockResolvedValue(createHeteroControlFakeRedis());+});++describe('stopHeteroBackgroundTask', () => {+ it('queues stop_task for the run and reports the run accepting it', async () => {+ const stopping = stopHeteroBackgroundTask('op-1', 'bys1w0wxo', { pollMs: 5, timeoutMs: 2000 });++ let message: Awaited<ReturnType<typeof takeHeteroControl>>;+ await vi.waitFor(async () => {+ message ??= await takeHeteroControl('op-1');+ expect(message).toBeDefined();+ });+ expect(message!).toMatchObject({ command: 'stop_task', params: { taskId: 'bys1w0wxo' } });+ await reportHeteroControlResult('op-1', message!.id, { status: 'ok' });++ await expect(stopping).resolves.toEqual({ status: 'accepted' });+ });++ it('calls a run nobody polls for unreachable', async () => {+ await expect(+ stopHeteroBackgroundTask('op-quiet', 'bys1w0wxo', { pollMs: 5, timeoutMs: 30 }),+ ).resolves.toEqual({ status: 'unreachable' });+ });+});++describe('toHeteroStopTaskResult', () => {+ it('maps every control state', () => {+ expect(toHeteroStopTaskResult({ status: 'unsupported' })).toEqual({ status: 'unsupported' });+ expect(toHeteroStopTaskResult({ error: 'No task found', status: 'error' })).toEqual({+ error: 'No task found',+ status: 'failed',+ });+ expect(toHeteroStopTaskResult({ status: 'claimed' })).toEqual({ status: 'timeout' });+ expect(toHeteroStopTaskResult({ status: 'pending' })).toEqual({ status: 'timeout' });+ expect(toHeteroStopTaskResult(undefined)).toEqual({ status: 'timeout' });+ });+});diff --git a/apps/server/src/services/aiAgent/steerQueue/heteroStopTask.ts b/apps/server/src/services/aiAgent/steerQueue/heteroStopTask.tsnew file mode 100644index 00000000000..316d710ece2--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/heteroStopTask.ts@@ -0,0 +1,67 @@+import type { HeteroControlState } from '@/server/services/redis/heteroControl';++import { sendHeteroControl } from './heteroControl';++/** Command name the `lh` steer loop registers its stop handler under. */+export const HETERO_STOP_TASK_COMMAND = 'stop_task';++/**+ * How long a stop waits for the run to claim and answer it. The `lh` handler+ * itself gives Claude Code 10 s to accept; the rest covers the steer poll.+ */+export const HETERO_STOP_TASK_TIMEOUT_MS = 20_000;++/**+ * What happened to a stop request. `accepted` only means Claude Code took the+ * request: the task is stopped once its `stopped` notification lands.+ * - `unsupported`: the run's `lh` has no stop handler;+ * - `unreachable`: no poller claimed the request — the run ended, or its `lh`+ * predates control messages;+ * - `timeout`: the run took it and never answered in time.+ */+export type HeteroStopTaskResult =+ | { status: 'accepted' }+ | { error: string; status: 'failed' }+ | { status: 'timeout' }+ | { status: 'unreachable' }+ | { status: 'unsupported' };++export const toHeteroStopTaskResult = (+ state: HeteroControlState | undefined,+): HeteroStopTaskResult => {+ switch (state?.status) {+ case 'ok': {+ return { status: 'accepted' };+ }+ case 'unsupported': {+ return { status: 'unsupported' };+ }+ case 'expired': {+ return { status: 'unreachable' };+ }+ case 'error': {+ return { error: state.error, status: 'failed' };+ }+ default: {+ return { status: 'timeout' };+ }+ }+};++/**+ * Ask a running `lh hetero exec` to stop one Claude Code background task. The+ * caller owns authorization of `operationId`.+ */+export const stopHeteroBackgroundTask = async (+ operationId: string,+ taskId: string,+ options: { pollMs?: number; timeoutMs?: number } = {},+): Promise<HeteroStopTaskResult> => {+ const { state } = await sendHeteroControl(+ operationId,+ HETERO_STOP_TASK_COMMAND,+ { taskId },+ { pollMs: options.pollMs, timeoutMs: options.timeoutMs ?? HETERO_STOP_TASK_TIMEOUT_MS },+ );+ return toHeteroStopTaskResult(state);+};diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.tsindex 1e529bf6bf3..7374cfcd01b 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/applyIntents.ts@@ -134,6 +134,11 @@ export async function applyMainIntent(return;}+ case 'updateBackgroundTask': {+ await applyBackgroundTask(deps, state, intent);+ return;+ }+case 'setToolIntervention': {await applyToolIntervention(deps, state, intent, stepIndex);return;@@ -198,6 +203,32 @@ async function applyToolResult(}}+/**+ * Store a background task snapshot on the tool message that started it. Only+ * the `backgroundTask` key is written: plugin state patches merge per key, so+ * the tool's own result state stays. The run's operation id goes with it so a+ * client can route a stop to this run and tell whether it is still alive.+ */+async function applyBackgroundTask(+ deps: HeterogeneousPersistenceHandlerDeps,+ state: OperationState,+ intent: Extract<MainAgentIntent, { kind: 'updateBackgroundTask' }>,+): Promise<void> {+ const toolMsgId = state.toolMsgIdByCallId.get(intent.toolCallId);+ if (!toolMsgId) {+ log('background_task for unknown toolCallId=%s op=%s', intent.toolCallId, state.operationId);+ return;+ }++ const backgroundTask = { ...intent.backgroundTask, operationId: state.operationId };+ const result = await deps.messageModel.updateToolMessage(toolMsgId, {+ pluginState: { backgroundTask },+ });+ if (!result.success) {+ throw new Error(`Failed to persist background_task for message ${toolMsgId}`);+ }+}+async function applyToolState(deps: HeterogeneousPersistenceHandlerDeps,state: OperationState,diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.backgroundTask.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.backgroundTask.test.tsnew file mode 100644index 00000000000..5c5a9327f77--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.backgroundTask.test.ts@@ -0,0 +1,68 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { __resetOperationStatesForTesting } from '.';+import { buildEvent, createHarness, ingest } from './eventBranchesTestUtils';++vi.mock('@/business/server/agent-run/agentInterventionReview', () => ({+ acknowledgeAgentInterventionProducerResolution: vi.fn(),+ notifyAgentInterventionRequired: vi.fn(),+}));++const bashCall = buildEvent('stream_chunk', 0, {+ chunkType: 'tools_calling',+ toolsCalling: [+ {+ apiName: 'Bash',+ arguments: '{}',+ id: 'toolu_bash',+ identifier: 'claude-code',+ type: 'default',+ },+ ],+});++const task = (status: string) => ({+ description: 'ping',+ startedAt: 1,+ status,+ taskId: 'bys1w0wxo',+ toolName: 'Bash',+});++describe('HeterogeneousPersistenceHandler — background_task', () => {+ beforeEach(() => __resetOperationStatesForTesting());+ afterEach(() => __resetOperationStatesForTesting());++ it('merges the snapshot into the starting tool message under backgroundTask', async () => {+ const h = createHarness();+ await ingest(h, [+ bashCall,+ buildEvent('tool_result', 1, {+ content: 'Command running in background',+ toolCallId: 'toolu_bash',+ }),+ buildEvent('background_task', 2, { task: task('running'), toolCallId: 'toolu_bash' }),+ buildEvent('agent_runtime_end', 3, {}),+ buildEvent('background_task', 4, { task: task('completed'), toolCallId: 'toolu_bash' }),+ ]);++ const writes = h.messageModel.updateToolMessage.mock.calls.filter(+ ([, patch]) => patch.pluginState?.backgroundTask,+ );+ expect(writes.map(([, patch]) => patch)).toEqual([+ { pluginState: { backgroundTask: { ...task('running'), operationId: h.operationId } } },+ { pluginState: { backgroundTask: { ...task('completed'), operationId: h.operationId } } },+ ]);+ const toolMessage = [...h.messages.values()].find((m) => m.tool_call_id === 'toolu_bash');+ expect(writes.every(([id]) => id === toolMessage?.id)).toBe(true);+ });++ it('skips a snapshot for a tool this run never persisted', async () => {+ const h = createHarness();+ await ingest(h, [+ buildEvent('background_task', 0, { task: task('running'), toolCallId: 'toolu_unknown' }),+ ]);+ expect(h.messageModel.updateToolMessage).not.toHaveBeenCalled();+ });+});diff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex 0c3d9540c02..f4d23803c3e 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -131,8 +131,6 @@"leaveFailed": "Couldn't leave the channel. Try again.","leaveSuccess": "You left the channel","main": "Channel conversation",- "memberActionsNamed": "Actions for {{name}}",- "members.agents": "Agents · {{count}}","member.remove": "Remove from channel","member.removeConfirmAgent": "Its replies in progress here stop. It stays in the project and can be invited again.","member.removeConfirmAgentStandalone": "Its replies in progress here stop. You can invite it again later.",@@ -140,6 +138,8 @@"member.removeConfirmTitle": "Remove {{name}} from the channel?","member.removeFailed": "Couldn't remove {{name}}. Try again.","member.removeNamed": "Remove {{name}} from the channel",+ "memberActionsNamed": "Actions for {{name}}",+ "members.agents": "Agents · {{count}}","members.hide": "Hide member list","members.show": "Show member list","membersCount": "Members · {{count}}",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 89b837adf17..60d65e0deb6 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -3676,6 +3676,21 @@"workingPanel.openMenu.title": "Open workspace panel","workingPanel.openMenu.tools": "Tools","workingPanel.openMenu.workspace": "Workspace",+ "workingPanel.overview.backgroundTasks.collapse": "Show less",+ "workingPanel.overview.backgroundTasks.locate": "Show in conversation",+ "workingPanel.overview.backgroundTasks.showAll": "Show all ({{count}})",+ "workingPanel.overview.backgroundTasks.status.completed": "Done",+ "workingPanel.overview.backgroundTasks.status.failed": "Failed",+ "workingPanel.overview.backgroundTasks.status.interrupted": "Interrupted",+ "workingPanel.overview.backgroundTasks.status.running": "Running",+ "workingPanel.overview.backgroundTasks.status.stopped": "Stopped",+ "workingPanel.overview.backgroundTasks.stop": "Stop",+ "workingPanel.overview.backgroundTasks.stopFailed": "Couldn't stop the task",+ "workingPanel.overview.backgroundTasks.stopNoAnswer": "The device hasn't answered yet. Try again in a moment.",+ "workingPanel.overview.backgroundTasks.stopUpgradeLh": "Update lh on the device to stop background tasks",+ "workingPanel.overview.backgroundTasks.stopping": "Stopping…",+ "workingPanel.overview.backgroundTasks.title": "Background tasks",+ "workingPanel.overview.backgroundTasks.viewOutput": "View output","workingPanel.overview.branch.detached": "Detached HEAD","workingPanel.overview.changes": "Changes","workingPanel.overview.changes.none": "No changes",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex 54a2bc3d429..83970c1b369 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -131,8 +131,6 @@"leaveFailed": "退出频道失败,请重试","leaveSuccess": "已退出频道","main": "频道对话",- "memberActionsNamed": "{{name}} 的操作",- "members.agents": "Agent · {{count}}","member.remove": "移出频道","member.removeConfirmAgent": "它在这里正在进行的回复会停止。它仍在项目中,之后可以再邀请。","member.removeConfirmAgentStandalone": "它在这里正在进行的回复会停止,之后可以再邀请。",@@ -140,6 +138,8 @@"member.removeConfirmTitle": "将「{{name}}」移出频道?","member.removeFailed": "移出「{{name}}」失败,请重试","member.removeNamed": "将 {{name}} 移出频道",+ "memberActionsNamed": "{{name}} 的操作",+ "members.agents": "Agent · {{count}}","members.hide": "收起成员列表","members.show": "展开成员列表","membersCount": "成员 · {{count}}",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex f4cf791dda5..16b615e1cb9 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -3676,6 +3676,21 @@"workingPanel.openMenu.title": "打开工作区面板","workingPanel.openMenu.tools": "工具","workingPanel.openMenu.workspace": "工作区",+ "workingPanel.overview.backgroundTasks.collapse": "收起",+ "workingPanel.overview.backgroundTasks.locate": "在对话中查看",+ "workingPanel.overview.backgroundTasks.showAll": "显示全部({{count}})",+ "workingPanel.overview.backgroundTasks.status.completed": "已完成",+ "workingPanel.overview.backgroundTasks.status.failed": "失败",+ "workingPanel.overview.backgroundTasks.status.interrupted": "已中断",+ "workingPanel.overview.backgroundTasks.status.running": "运行中",+ "workingPanel.overview.backgroundTasks.status.stopped": "已停止",+ "workingPanel.overview.backgroundTasks.stop": "停止",+ "workingPanel.overview.backgroundTasks.stopFailed": "无法停止任务",+ "workingPanel.overview.backgroundTasks.stopNoAnswer": "设备暂未响应,请稍后再试",+ "workingPanel.overview.backgroundTasks.stopUpgradeLh": "升级设备上的 lh 后才能停止后台任务",+ "workingPanel.overview.backgroundTasks.stopping": "正在停止…",+ "workingPanel.overview.backgroundTasks.title": "后台任务",+ "workingPanel.overview.backgroundTasks.viewOutput": "查看输出","workingPanel.overview.branch.detached": "游离 HEAD","workingPanel.overview.changes": "变更","workingPanel.overview.changes.none": "无改动",diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex 0bdbe50feec..0d2c9411c42 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -38,6 +38,12 @@ export type AgentStreamEventType =| 'tool_start'| 'tool_end'| 'tool_execute'+ /**+ * Snapshot of one background task a heterogeneous agent's tool started+ * (Claude Code `run_in_background` Bash, Monitor). Persisted on that tool+ * message's `pluginState.backgroundTask`.+ */+ | 'background_task'/*** Server → executor client: run one LLM attempt for a model provider only* the user's device can reach, and upload its protocol chunks back overdiff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex 0c5b0d18dae..3ae330da567 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -58,6 +58,7 @@ import type {ToolResultData,UsageData,} from '../types';+import { ClaudeCodeBackgroundTasks } from './claudeCodeBackgroundTasks';import { ClaudeCodeTaskSignals } from './claudeCodeTaskSignals';/**@@ -1183,6 +1184,7 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {private mainToolNamesById = new Map<string, string>();/** CC's long-running task lifecycle and the signal lineage it stamps on turns. */private readonly taskSignals: ClaudeCodeTaskSignals;+ private readonly backgroundTasks: ClaudeCodeBackgroundTasks;/*** True after a `user` event has been seen but the next turn hasn't yet* opened (`message_start` not yet fired). Carries the "this next turn@@ -1244,6 +1246,11 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {this.options = { ...DEFAULT_ADAPTER_OPTIONS, ...options };this.profile = profile;this.taskSignals = new ClaudeCodeTaskSignals(this.options.signalBackgroundTaskCompletion);+ // Claude Code only: other Claude-compatible CLIs take no stop_task control request.+ this.backgroundTasks = new ClaudeCodeBackgroundTasks(+ profile.agentType === 'claude-code',+ (data) => this.makeEvent('background_task', data),+ );}adapt(raw: any): HeterogeneousAgentEvent[] {@@ -1289,7 +1296,7 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {this.makeEvent('tool_end', this.buildToolEndData(id, false)),);this.pendingToolCalls.clear();- return events;+ return [...events, ...this.backgroundTasks.flush()];}// ─── Private handlers ───@@ -1299,25 +1306,14 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {return [this.makeEvent('stream_retry', getApiRetryData(raw, this.profile.agentType))];}- // CC's long-running task lifecycle (Monitor, etc.) — see ClaudeCodeTaskSignals.- if (raw.subtype === 'task_started' && raw.task_id && raw.tool_use_id) {- const toolUseId: string = raw.tool_use_id;- this.taskSignals.start(- raw.task_id,- toolUseId,- this.mainToolNamesById.get(toolUseId) ?? 'unknown',- this.mainToolInputsById.get(toolUseId),- );- return [];- }- if (raw.subtype === 'task_notification' && raw.task_id) {- this.taskSignals.end(raw.task_id);- return [];+ // CC's task lifecycle: callback-turn lineage + background task snapshots.+ if (ClaudeCodeBackgroundTasks.isTaskEvent(raw)) {+ return this.backgroundTasks.onSystem(raw, {+ mainToolInput: (id) => this.mainToolInputsById.get(id),+ mainToolName: (id) => this.mainToolNamesById.get(id),+ taskSignals: this.taskSignals,+ });}- // `task_updated` is a status patch (status: 'completed' fires- // alongside `task_notification`). Drop it — we drive lifecycle off- // task_started / task_notification only.- if (raw.subtype === 'task_updated') return [];if (raw.subtype !== 'init') return [];this.sessionId = raw.session_id;@@ -1942,6 +1938,7 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {toolCallId,} satisfies ToolResultData),);+ events.push(...this.backgroundTasks.onToolResult(toolCallId, resultContent));// Then emit tool_end (signals handler to refresh tool result UI)if (this.pendingToolCalls.has(toolCallId)) {diff --git a/packages/heterogeneous-agents/src/adapters/claudeCodeBackgroundTasks.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCodeBackgroundTasks.test.tsnew file mode 100644index 00000000000..b2b346dec95--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/claudeCodeBackgroundTasks.test.ts@@ -0,0 +1,280 @@+import { describe, expect, it } from 'vitest';++import type { BackgroundTaskEventData, HeterogeneousAgentEvent } from '../types';+import { ClaudeCodeAdapter, ClaudeCodeSdkAdapter, CodeBuddyAdapter } from '.';++// Shapes recorded from `claude -p --output-format stream-json` 2.1.308.+const OUTPUT = '/tmp/claude-501/proj/sess/tasks/bys1w0wxo.output';++const toolUse = (id: string, name: string, input: Record<string, unknown>) => ({+ message: { content: [{ id, input, name, type: 'tool_use' }], id: `msg_${id}` },+ type: 'assistant',+});++const taskStarted = (overrides: Record<string, unknown> = {}) => ({+ description: 'Run 60 pings to localhost in background',+ is_backgrounded: true,+ run_id: 'run_1',+ session_id: 'sess_1',+ subtype: 'task_started',+ task_id: 'bys1w0wxo',+ task_type: 'local_bash',+ tool_use_id: 'toolu_bash',+ type: 'system',+ ...overrides,+});++const toolResult = (toolUseId: string, content: string) => ({+ message: { content: [{ content, tool_use_id: toolUseId, type: 'tool_result' }] },+ type: 'user',+});++const notification = (overrides: Record<string, unknown> = {}) => ({+ output_file: OUTPUT,+ session_id: 'sess_1',+ status: 'completed',+ subtype: 'task_notification',+ summary: 'Run 60 pings to localhost in background',+ task_id: 'bys1w0wxo',+ tool_use_id: 'toolu_bash',+ type: 'system',+ ...overrides,+});++const snapshots = (events: HeterogeneousAgentEvent[]): BackgroundTaskEventData[] =>+ events.filter((e) => e.type === 'background_task').map((e) => e.data);++const startBackgroundBash = (adapter: ClaudeCodeAdapter) => {+ adapter.adapt(toolUse('toolu_bash', 'Bash', { command: 'ping -c 60 127.0.0.1' }));+ return snapshots(adapter.adapt(taskStarted()));+};++describe('Claude Code background tasks', () => {+ it('reports a background Bash from start to its notification', () => {+ const adapter = new ClaudeCodeAdapter();++ const [started] = startBackgroundBash(adapter);+ expect(started).toEqual({+ task: {+ description: 'Run 60 pings to localhost in background',+ startedAt: expect.any(Number),+ status: 'running',+ taskId: 'bys1w0wxo',+ taskType: 'local_bash',+ toolName: 'Bash',+ },+ toolCallId: 'toolu_bash',+ });++ // The immediate tool_result carries the output path; the snapshot follows the result.+ const resultEvents = adapter.adapt(+ toolResult(+ 'toolu_bash',+ `Command running in background with ID: bys1w0wxo. Output is being written to: ${OUTPUT}. You will be notified when it completes.`,+ ),+ );+ expect(resultEvents.map((e) => e.type)).toEqual(['tool_result', 'background_task', 'tool_end']);+ expect(snapshots(resultEvents)[0].task).toMatchObject({+ outputFile: OUTPUT,+ status: 'running',+ });++ const [ended] = snapshots(adapter.adapt(notification()));+ expect(ended.task).toMatchObject({+ endedAt: expect.any(Number),+ outputFile: OUTPUT,+ status: 'completed',+ summary: 'Run 60 pings to localhost in background',+ });+ // Nothing is left to interrupt.+ expect(snapshots(adapter.flush())).toEqual([]);+ });++ it('calls a task stopped once Claude Code reports it killed', () => {+ const adapter = new ClaudeCodeAdapter();+ startBackgroundBash(adapter);++ // CC patches the status as soon as the process ends; the notification+ // carrying the output may only come at its next turn boundary.+ const [patched] = snapshots(+ adapter.adapt({+ patch: { end_time: 1_794_866_273_908, status: 'killed' },+ subtype: 'task_updated',+ task_id: 'bys1w0wxo',+ type: 'system',+ }),+ );+ expect(patched.task).toMatchObject({ endedAt: 1_794_866_273_908, status: 'stopped' });+ // An ended task is not interrupted by the stream ending before its notification.+ expect(snapshots(adapter.flush())).toEqual([]);+ });++ it('keeps the stopped status and adds the output when the notification lands', () => {+ const adapter = new ClaudeCodeAdapter();+ startBackgroundBash(adapter);+ adapter.adapt({+ patch: { end_time: 1_794_866_273_908, status: 'killed' },+ subtype: 'task_updated',+ task_id: 'bys1w0wxo',+ type: 'system',+ });++ const [stopped] = snapshots(adapter.adapt(notification({ status: 'stopped' })));+ expect(stopped.task).toMatchObject({+ endedAt: 1_794_866_273_908,+ outputFile: OUTPUT,+ status: 'stopped',+ });+ });++ it('does not end a task on a non-terminal patch', () => {+ const adapter = new ClaudeCodeAdapter();+ startBackgroundBash(adapter);+ const [patched] = snapshots(+ adapter.adapt({+ patch: { status: 'paused' },+ subtype: 'task_updated',+ task_id: 'bys1w0wxo',+ type: 'system',+ }),+ );+ expect(patched.task.status).toBe('running');+ });++ it('keeps a failed task failed with its error', () => {+ const adapter = new ClaudeCodeAdapter();+ startBackgroundBash(adapter);+ adapter.adapt({+ patch: { error: 'exit code 2', status: 'failed' },+ subtype: 'task_updated',+ task_id: 'bys1w0wxo',+ type: 'system',+ });++ const [failed] = snapshots(adapter.adapt(notification({ status: 'failed' })));+ expect(failed.task).toMatchObject({ error: 'exit code 2', status: 'failed' });+ });++ it('marks a task still running at the end of the stream interrupted', () => {+ const adapter = new ClaudeCodeAdapter();+ startBackgroundBash(adapter);++ const [interrupted] = snapshots(adapter.flush());+ expect(interrupted.task).toMatchObject({ endedAt: expect.any(Number), status: 'interrupted' });+ expect(snapshots(adapter.flush())).toEqual([]);+ });++ it('reports a Monitor task under its own tool name', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt(toolUse('toolu_mon', 'Monitor', { command: 'ping -c 5 127.0.0.1' }));++ const [started] = snapshots(+ adapter.adapt(taskStarted({ task_id: 'bn4d0bue1', tool_use_id: 'toolu_mon' })),+ );+ expect(started).toMatchObject({ task: { toolName: 'Monitor' }, toolCallId: 'toolu_mon' });+ });++ it('leaves out async subagents', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt(+ toolUse('toolu_agent', 'Agent', {+ prompt: 'reply with the word ok',+ run_in_background: true,+ subagent_type: 'general-purpose',+ }),+ );++ const agentTask = taskStarted({+ subagent_type: 'general-purpose',+ task_id: 'aef2018f8c978dc18',+ task_type: 'local_agent',+ tool_use_id: 'toolu_agent',+ });+ expect(snapshots(adapter.adapt(agentTask))).toEqual([]);+ expect(+ snapshots(+ adapter.adapt(notification({ task_id: 'aef2018f8c978dc18', tool_use_id: 'toolu_agent' })),+ ),+ ).toEqual([]);+ expect(snapshots(adapter.flush())).toEqual([]);+ });++ it('reports a foreground tool only once it moves to the background', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt(toolUse('toolu_fg', 'Bash', { command: 'ping -c 8 127.0.0.1' }));++ const fgTask = taskStarted({+ is_backgrounded: false,+ task_id: 'bvzvn3s1f',+ tool_use_id: 'toolu_fg',+ });+ expect(snapshots(adapter.adapt(fgTask))).toEqual([]);++ const [backgrounded] = snapshots(+ adapter.adapt({+ patch: { is_backgrounded: true },+ subtype: 'task_updated',+ task_id: 'bvzvn3s1f',+ type: 'system',+ }),+ );+ expect(backgrounded.task).toMatchObject({ status: 'running', taskId: 'bvzvn3s1f' });+ });++ it('ignores a foreground tool that ends in the foreground', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt(toolUse('toolu_fg', 'Bash', { command: 'ping -c 8 127.0.0.1' }));+ adapter.adapt(+ taskStarted({ is_backgrounded: false, task_id: 'bvzvn3s1f', tool_use_id: 'toolu_fg' }),+ );++ const fgEnd = notification({ output_file: '', task_id: 'bvzvn3s1f', tool_use_id: 'toolu_fg' });+ expect(snapshots(adapter.adapt(fgEnd))).toEqual([]);+ expect(snapshots(adapter.flush())).toEqual([]);+ });++ it('ignores a resumed session reporting a previous run orphan', () => {+ const adapter = new ClaudeCodeAdapter();+ expect(snapshots(adapter.adapt(notification({ status: 'stopped' })))).toEqual([]);+ });++ it('ignores tasks started by a subagent inner tool', () => {+ const adapter = new ClaudeCodeAdapter();+ expect(snapshots(adapter.adapt(taskStarted({ tool_use_id: 'toolu_inner' })))).toEqual([]);+ });++ it('reports progress summaries', () => {+ const adapter = new ClaudeCodeAdapter();+ startBackgroundBash(adapter);++ const [progress] = snapshots(+ adapter.adapt({+ description: 'Pinging',+ last_tool_name: 'Bash',+ subtype: 'task_progress',+ summary: '20 packets received',+ task_id: 'bys1w0wxo',+ type: 'system',+ usage: { duration_ms: 20_000, tool_uses: 0, total_tokens: 0 },+ }),+ );+ expect(progress.task).toMatchObject({+ description: 'Pinging',+ lastToolName: 'Bash',+ summary: '20 packets received',+ });+ });++ it('reports through the SDK adapter too', () => {+ const adapter = new ClaudeCodeSdkAdapter();+ adapter.adapt(toolUse('toolu_bash', 'Bash', { command: 'ping -c 60 127.0.0.1' }));+ expect(snapshots(adapter.adapt(taskStarted()))).toHaveLength(1);+ });++ it('stays silent for other Claude-compatible CLIs', () => {+ const adapter = new CodeBuddyAdapter();+ adapter.adapt(toolUse('toolu_bash', 'Bash', { command: 'ping -c 60 127.0.0.1' }));+ expect(snapshots(adapter.adapt(taskStarted()))).toEqual([]);+ expect(snapshots(adapter.flush())).toEqual([]);+ });+});diff --git a/packages/heterogeneous-agents/src/adapters/claudeCodeBackgroundTasks.ts b/packages/heterogeneous-agents/src/adapters/claudeCodeBackgroundTasks.tsnew file mode 100644index 00000000000..999d2fbabf3--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/claudeCodeBackgroundTasks.ts@@ -0,0 +1,230 @@+import type {+ BackgroundTaskEventData,+ HeteroBackgroundTask,+ HeteroBackgroundTaskStatus,+ HeterogeneousAgentEvent,+} from '../types';+import type { ClaudeCodeTaskSignals } from './claudeCodeTaskSignals';++/** Agent tasks are subagents: the subagent thread list already shows them. */+const AGENT_TASK_TYPES = new Set(['local_agent', 'remote_agent']);+const SUBAGENT_TOOL_NAMES = new Set(['Agent', 'Task']);++const NOTIFICATION_STATUSES: Record<string, HeteroBackgroundTaskStatus> = {+ completed: 'completed',+ failed: 'failed',+ stopped: 'stopped',+};++/** `task_updated` statuses that end a task; CC's `killed` is the `stopped` notification's. */+const TERMINAL_PATCH_STATUSES: Record<string, HeteroBackgroundTaskStatus> = {+ completed: 'completed',+ failed: 'failed',+ killed: 'stopped',+};++/**+ * `run_in_background` Bash answers at once with the path it writes to:+ * "Command running in background with ID: <id>. Output is being written to:+ * <path>.output. …" — the only place the path shows before the task ends.+ */+const OUTPUT_PATH_PATTERN = /Output is being written to: (\S+?\.output)\b/;++interface TrackedTask {+ task: HeteroBackgroundTask;+ toolCallId: string;+ /**+ * CC also tracks a slow FOREGROUND tool as a task (`is_backgrounded: false`).+ * It is not a background task until a patch backgrounds it, so it is only+ * reported from then on.+ */+ visible: boolean;+}++export interface ClaudeCodeTaskEventContext {+ mainToolInput: (toolUseId: string) => Record<string, any> | undefined;+ /** Main-agent tool name for a `tool_use.id`; undefined for subagent inner tools. */+ mainToolName: (toolUseId: string) => string | undefined;+ taskSignals: ClaudeCodeTaskSignals;+}++/**+ * Claude Code background tasks, as complete snapshots for the tool message+ * that started each one.+ *+ * CC reports a task's life as `system` events: `task_started` →+ * `task_updated` / `task_progress` … → `task_notification`. Each one that+ * changes a visible task yields a full {@link BackgroundTaskEventData}, so+ * every consumer simply replaces the stored snapshot.+ *+ * A task ends only when Claude Code says it did: a terminal `task_updated`+ * status (`killed` → `stopped`) or its `task_notification`, never because a+ * stop was requested. CC patches the status the moment the process ends, but+ * may hold the notification until its next turn boundary, so the patch is what+ * keeps a stopped row from reading "running" for half a minute. A task still+ * running when the stream ends is `interrupted`.+ */+export class ClaudeCodeBackgroundTasks {+ private tasks = new Map<string, TrackedTask>();++ /** Every CC `task_*` system event belongs here, reported or not. */+ static isTaskEvent(raw: any): boolean {+ return typeof raw?.subtype === 'string' && raw.subtype.startsWith('task_');+ }++ /**+ * @param enabled Whether snapshots are reported at all; the task lineage of+ * {@link ClaudeCodeTaskSignals} is driven either way.+ * @param toEvent Wraps one snapshot into the adapter's `background_task` event.+ */+ constructor(+ private readonly enabled: boolean,+ private readonly toEvent: (data: BackgroundTaskEventData) => HeterogeneousAgentEvent,+ ) {}++ /**+ * One CC `task_*` system event. Also drives the callback-turn lineage of+ * {@link ClaudeCodeTaskSignals}, which sees every task, subagents included.+ */+ onSystem(raw: any, ctx: ClaudeCodeTaskEventContext): HeterogeneousAgentEvent[] {+ const taskId: unknown = raw.task_id;+ if (typeof taskId !== 'string' || !taskId) return [];++ switch (raw.subtype) {+ case 'task_started': {+ const toolUseId: unknown = raw.tool_use_id;+ if (typeof toolUseId !== 'string' || !toolUseId) return [];+ const toolName = ctx.mainToolName(toolUseId);+ ctx.taskSignals.start(+ taskId,+ toolUseId,+ toolName ?? 'unknown',+ ctx.mainToolInput(toolUseId),+ );+ return this.start(raw, taskId, toolUseId, toolName);+ }+ case 'task_updated': {+ return this.update(taskId, raw.patch);+ }+ case 'task_progress': {+ return this.progress(taskId, raw);+ }+ case 'task_notification': {+ ctx.taskSignals.end(taskId);+ return this.end(taskId, raw);+ }+ default: {+ return [];+ }+ }+ }++ /**+ * A tool_result: pick up the output path a background Bash answers with.+ * Only main-agent tools start tracked tasks, so a subagent's result never matches.+ */+ onToolResult(toolCallId: string, content: string): HeterogeneousAgentEvent[] {+ const path = OUTPUT_PATH_PATTERN.exec(content)?.[1];+ if (!path) return [];+ for (const tracked of this.tasks.values()) {+ if (tracked.toolCallId !== toolCallId || tracked.task.outputFile) continue;+ tracked.task = { ...tracked.task, outputFile: path };+ return this.snapshot(tracked);+ }+ return [];+ }++ /** The stream ended: every task still running lost its session. */+ flush(now = Date.now()): HeterogeneousAgentEvent[] {+ const out: HeterogeneousAgentEvent[] = [];+ for (const tracked of this.tasks.values()) {+ if (!tracked.visible || tracked.task.status !== 'running') continue;+ tracked.task = { ...tracked.task, endedAt: now, status: 'interrupted' };+ out.push(...this.snapshot(tracked));+ }+ this.tasks.clear();+ return out;+ }++ private start(+ raw: any,+ taskId: string,+ toolCallId: string,+ toolName: string | undefined,+ ): HeterogeneousAgentEvent[] {+ // Subagent inner tools have no main tool message to carry the snapshot.+ if (!toolName || SUBAGENT_TOOL_NAMES.has(toolName)) return [];+ if (AGENT_TASK_TYPES.has(raw.task_type) || raw.subagent_type) return [];++ const tracked: TrackedTask = {+ task: {+ description: typeof raw.description === 'string' ? raw.description : '',+ startedAt: Date.now(),+ status: 'running',+ taskId,+ ...(typeof raw.task_type === 'string' && { taskType: raw.task_type }),+ toolName,+ },+ toolCallId,+ visible: raw.is_backgrounded !== false,+ };+ this.tasks.set(taskId, tracked);+ return this.snapshot(tracked);+ }++ private update(taskId: string, patch: any): HeterogeneousAgentEvent[] {+ const tracked = this.tasks.get(taskId);+ if (!tracked || !patch || typeof patch !== 'object') return [];++ const next = { ...tracked.task };+ if (typeof patch.description === 'string' && patch.description) {+ next.description = patch.description;+ }+ if (typeof patch.error === 'string' && patch.error) next.error = patch.error;+ if (typeof patch.end_time === 'number') next.endedAt = patch.end_time;+ if (patch.is_backgrounded === true) tracked.visible = true;+ const ended = TERMINAL_PATCH_STATUSES[patch.status as string];+ if (ended && next.status === 'running') {+ next.status = ended;+ next.endedAt ??= Date.now();+ }+ tracked.task = next;+ return this.snapshot(tracked);+ }++ private progress(taskId: string, raw: any): HeterogeneousAgentEvent[] {+ const tracked = this.tasks.get(taskId);+ if (!tracked) return [];++ const next = { ...tracked.task };+ if (typeof raw.description === 'string' && raw.description) next.description = raw.description;+ if (typeof raw.summary === 'string' && raw.summary) next.summary = raw.summary;+ if (typeof raw.last_tool_name === 'string') next.lastToolName = raw.last_tool_name;+ tracked.task = next;+ return this.snapshot(tracked);+ }++ private end(taskId: string, raw: any): HeterogeneousAgentEvent[] {+ const tracked = this.tasks.get(taskId);+ // A notification for a task this run never started is a previous run's+ // orphan, reported when a session resumes: its own run already closed it.+ if (!tracked) return [];+ this.tasks.delete(taskId);++ const status = NOTIFICATION_STATUSES[raw.status as string] ?? 'completed';+ tracked.task = {+ ...tracked.task,+ endedAt: tracked.task.endedAt ?? Date.now(),+ status,+ ...(typeof raw.output_file === 'string' &&+ raw.output_file && { outputFile: raw.output_file }),+ ...(typeof raw.summary === 'string' && raw.summary && { summary: raw.summary }),+ };+ return this.snapshot(tracked);+ }++ private snapshot(tracked: TrackedTask): HeterogeneousAgentEvent[] {+ if (!this.enabled || !tracked.visible) return [];+ return [this.toEvent({ task: { ...tracked.task }, toolCallId: tracked.toolCallId })];+ }+}diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex 9bc09f518e0..9cbeef283d7 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -100,6 +100,7 @@ export type {MainResolveToolResultIntent,MainSetToolInterventionIntent,MainStreamContentIntent,+ MainUpdateBackgroundTaskIntent,MainUpdateToolStateIntent,PersistAssistantIntent,SetErrorIntent,@@ -171,6 +172,9 @@ export {export type {AgentEventAdapter,AgentProcessConfig,+ BackgroundTaskEventData,+ HeteroBackgroundTask,+ HeteroBackgroundTaskStatus,HeterogeneousAgentEvent,HeterogeneousEventType,HeterogeneousTerminalErrorData,diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/index.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/index.tsindex 8f9c43a879c..56f02308148 100644--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/index.ts+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/index.ts@@ -12,6 +12,7 @@ export type {MainResolveToolResultIntent,MainSetToolInterventionIntent,MainStreamContentIntent,+ MainUpdateBackgroundTaskIntent,MainUpdateToolStateIntent,PersistAssistantIntent,SetErrorIntent,diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.backgroundTask.test.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.backgroundTask.test.tsnew file mode 100644index 00000000000..f9d375a9568--- /dev/null+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.backgroundTask.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';++import type { HeteroBackgroundTask } from '../types';+import { createMainAgentRunState, reduceMainAgent } from './index';+import type { MainAgentReduceCtx } from './types';++const ctx: MainAgentReduceCtx = { newId: (kind) => `${kind}_1`, topicId: 'topic-1' };++const task: HeteroBackgroundTask = {+ description: 'ping',+ startedAt: 1,+ status: 'running',+ taskId: 'bys1w0wxo',+ toolName: 'Bash',+};++describe('reduceMainAgent background_task', () => {+ it('turns a snapshot into an updateBackgroundTask intent', () => {+ const state = createMainAgentRunState('msg_seed');+ const { intents, state: next } = reduceMainAgent(+ state,+ { data: { task, toolCallId: 'toolu_bash' }, type: 'background_task' },+ ctx,+ );++ expect(intents).toEqual([+ { backgroundTask: task, kind: 'updateBackgroundTask', toolCallId: 'toolu_bash' },+ ]);+ expect(next).toBe(state);+ });++ it('still reports a task after the run ended', () => {+ const ended = reduceMainAgent(+ createMainAgentRunState('msg_seed'),+ { data: {}, type: 'agent_runtime_end' },+ ctx,+ ).state;++ const { intents } = reduceMainAgent(+ ended,+ {+ data: { task: { ...task, status: 'completed' }, toolCallId: 'toolu_bash' },+ type: 'background_task',+ },+ ctx,+ );+ expect(intents).toHaveLength(1);+ });++ it('drops a malformed snapshot', () => {+ const state = createMainAgentRunState('msg_seed');+ for (const data of [{ task }, { task: { status: 'running' }, toolCallId: 't' }, {}]) {+ expect(reduceMainAgent(state, { data, type: 'background_task' }, ctx).intents).toEqual([]);+ }+ });+});diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.tsindex 09240eed1fb..7efd6bbdaf4 100644--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts@@ -609,6 +609,27 @@ const reduceTerminal = (return { intents: [...intents, ...ended.intents, ...delegated.intents], state: delegated.state };};+/**+ * A background task snapshot for a main-agent tool. Valid even after the run's+ * terminal event: on the `on-result` runtime-end strategy CC keeps reporting a+ * task after the result that ended the operation.+ */+const reduceBackgroundTask = (state: MainAgentRunState, data: any): ReduceResult => {+ const task = data?.task;+ if (+ typeof data?.toolCallId !== 'string' ||+ !data.toolCallId ||+ typeof task?.taskId !== 'string' ||+ typeof task.status !== 'string'+ ) {+ return { intents: [], state };+ }+ return {+ intents: [{ backgroundTask: task, kind: 'updateBackgroundTask', toolCallId: data.toolCallId }],+ state,+ };+};+/*** Reduce a single stream event. Returns the next state and intents to apply.* Subagent-scoped events are routed entirely through the subagent coordinator;@@ -665,6 +686,9 @@ export const reduce = (case 'visible_output_end': {return reduceVisibleOutputEnd(state);}+ case 'background_task': {+ return reduceBackgroundTask(state, data);+ }case 'agent_runtime_end':case 'error': {return reduceTerminal(state, event, ctx);diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.tsindex 8c5157655b8..5d72d55b3c1 100644--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts@@ -3,7 +3,7 @@ import type { ToolIntervention } from '@lobechat/types';import type { PersistToolBatchEntry, SubagentRunsState } from '../subagentCoordinator';import { createSubagentRunsState } from '../subagentCoordinator';-import type { ExternalSignalContext, ToolCallPayload } from '../types';+import type { ExternalSignalContext, HeteroBackgroundTask, ToolCallPayload } from '../types';/*** Main-agent run coordinator — shared, side-effect-free state machine for the@@ -193,6 +193,7 @@ export type MainAgentIntent =| MainStreamContentIntent| MainPersistToolBatchIntent| MainUpdateToolStateIntent+ | MainUpdateBackgroundTaskIntent| MainResolveToolResultIntent| MainSetToolInterventionIntent| MainRecordUsageIntent@@ -265,6 +266,18 @@ export interface MainUpdateToolStateIntent {toolCallId: string;}+/**+ * Store a background task's latest snapshot on the tool message that started+ * it, as `pluginState.backgroundTask`. It replaces that one key and leaves the+ * rest of the plugin state alone; unlike `updateToolState` it may land after+ * the tool's own result, since a background task outlives its call.+ */+export interface MainUpdateBackgroundTaskIntent {+ backgroundTask: HeteroBackgroundTask;+ kind: 'updateBackgroundTask';+ toolCallId: string;+}+/*** Resolve a main-agent tool_result. The interpreter looks up the tool-message* id from its `toolCallId → messageId` map (the run-global one, DB-backed ondiff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.tsindex dd92e23fe3d..7727062ed6e 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts@@ -261,6 +261,203 @@ describe('ClaudeAgentSdkSession plugins', () => {});});+describe('ClaudeAgentSdkSession.stopTask', () => {+ afterEach(() => {+ sdkQueryMock.mockReset();+ });++ const newSession = () =>+ new ClaudeAgentSdkSession({+ args: [],+ commandPath: 'claude',+ cwd: os.tmpdir(),+ env: {} as NodeJS.ProcessEnv,+ onEvents: () => {},+ onRawMessage: () => {},+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: () => {},+ operationId: 'op-sdk-stop',+ sessionId: 'session-1',+ stdinPayload: `${JSON.stringify({ message: { content: 'hi', role: 'user' }, type: 'user' })}\n`,+ });++ it('asks the running query to stop the task', async () => {+ const stopTask = vi.fn().mockResolvedValue(undefined);+ let release!: () => void;+ const held = new Promise<void>((resolve) => (release = resolve));+ sdkQueryMock.mockImplementation(() => ({+ async *[Symbol.asyncIterator]() {+ await held;+ yield* [];+ },+ close: vi.fn(),+ stopTask,+ }));++ const session = newSession();+ const running = session.run();+ await vi.waitFor(() => expect(sdkQueryMock).toHaveBeenCalled());++ await session.stopTask('bys1w0wxo');+ expect(stopTask).toHaveBeenCalledWith('bys1w0wxo');++ release();+ await running;+ });++ it('refuses once the query ended', async () => {+ sdkQueryMock.mockImplementation(() => ({+ async *[Symbol.asyncIterator]() {},+ close: vi.fn(),+ stopTask: vi.fn(),+ }));+ const session = newSession();+ await session.run();++ await expect(session.stopTask('bys1w0wxo')).rejects.toThrow('no longer running');+ });+});++describe('ClaudeAgentSdkSession input lifetime', () => {+ afterEach(() => {+ sdkQueryMock.mockReset();+ });++ const sessionWith = (script: (input: { ended: () => boolean }) => AsyncGenerator<any>) => {+ sdkQueryMock.mockImplementation(({ prompt }: { prompt: AsyncIterable<unknown> }) => {+ let inputEnded = false;+ void (async () => {+ for await (const _ of prompt) {+ // drain+ }+ inputEnded = true;+ })();+ const messages = script({ ended: () => inputEnded });+ return { [Symbol.asyncIterator]: () => messages, close: vi.fn(), stopTask: vi.fn() };+ });+ return new ClaudeAgentSdkSession({+ args: [],+ commandPath: 'claude',+ cwd: os.tmpdir(),+ env: {} as NodeJS.ProcessEnv,+ onEvents: () => {},+ onRawMessage: () => {},+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: () => {},+ operationId: 'op-sdk-input',+ resumeSessionId: 'cc-session',+ sessionId: 'session-1',+ stdinPayload: `${JSON.stringify({ message: { content: 'hi', role: 'user' }, type: 'user' })}\n`,+ });+ };++ const settle = () => new Promise((resolve) => setTimeout(resolve, 1200));+ const result = (extra: Record<string, unknown> = {}) => ({+ is_error: false,+ num_turns: 1,+ result: 'done',+ subtype: 'success',+ type: 'result',+ ...extra,+ });+ const notificationResult = (numTurns: number) =>+ result({ num_turns: numTurns, origin: { kind: 'task-notification' }, result: '' });+ const taskStarted = (id: string) => ({+ description: 'ping',+ subtype: 'task_started',+ task_id: id,+ tool_use_id: `toolu_${id}`,+ type: 'system',+ });+ const taskNotification = (id: string) => ({+ output_file: '',+ status: 'completed',+ subtype: 'task_notification',+ summary: 'ping',+ task_id: id,+ type: 'system',+ });++ // Recorded from a resumed desktop SDK run: the previous run's stopped task is+ // reported, its empty pass closes, then this run's own turn starts a task.+ it('keeps the input open for a task started after a resumed session reports leftovers', async () => {+ const seen: boolean[] = [];+ const session = sessionWith(async function* ({ ended }) {+ yield taskNotification('leftover');+ yield notificationResult(0);+ yield { model: 'claude-haiku', session_id: 'cc-session', subtype: 'init', type: 'system' };+ yield taskStarted('b1');+ yield result();+ await settle();+ seen.push(ended());+ yield taskNotification('b1');+ yield notificationResult(1);+ await settle();+ seen.push(ended());+ });++ await session.run();+ expect(seen).toEqual([false, true]);+ });++ it('keeps the input open while a second task still runs after the first one ends', async () => {+ const seen: boolean[] = [];+ const session = sessionWith(async function* ({ ended }) {+ yield taskStarted('b1');+ yield taskStarted('b2');+ yield result();+ yield taskNotification('b1');+ yield notificationResult(1);+ await settle();+ seen.push(ended());+ yield taskNotification('b2');+ yield notificationResult(1);+ await settle();+ seen.push(ended());+ });++ await session.run();+ expect(seen).toEqual([false, true]);+ });++ // Recorded from claude 2.1.308: `task_updated(killed)` then+ // `task_notification(stopped)`, and no `result` after it.+ it('ends the session when the last task is stopped between turns', async () => {+ const seen: boolean[] = [];+ const session = sessionWith(async function* ({ ended }) {+ yield taskStarted('b1');+ yield result();+ await settle();+ seen.push(ended());+ yield { ...taskNotification('b1'), status: 'stopped' };+ await settle();+ seen.push(ended());+ });++ await session.run();+ expect(seen).toEqual([false, true]);+ });++ it("leaves a task stopped mid-turn to that turn's own result", async () => {+ const seen: boolean[] = [];+ const session = sessionWith(async function* ({ ended }) {+ yield { model: 'claude-haiku', session_id: 'cc-session', subtype: 'init', type: 'system' };+ yield taskStarted('b1');+ yield { ...taskNotification('b1'), status: 'stopped' };+ await settle();+ seen.push(ended());+ yield result();+ await settle();+ seen.push(ended());+ });++ await session.run();+ expect(seen).toEqual([false, true]);+ });+});+describe('ClaudeAgentSdkSession steer', () => {afterEach(() => {sdkQueryMock.mockReset();diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex 090c769fb9e..bba853c00e9 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -255,6 +255,8 @@ export class ClaudeAgentSdkSession {/** Steered messages Claude Code has not replayed yet; input stays open for them. */private readonly unconsumed = new Set<string>();private taskNotificationPending = false;+ /** A turn is under way: its own `result` will decide about the input. */+ private turnOpen = true;constructor(private readonly options: ClaudeAgentSdkSessionOptions) {this.pipeline = new AgentStreamPipeline({@@ -324,6 +326,18 @@ export class ClaudeAgentSdkSession {}}+ /**+ * Stop one background task of the live session. CC answers with a+ * `task_notification` of status `stopped`, which is the only proof the stop+ * took: resolving here means the request was accepted, nothing more.+ *+ * @throws When no query is running any more.+ */+ async stopTask(taskId: string): Promise<void> {+ if (!this.queryHandle) throw new Error('The Claude Code session is no longer running');+ await this.queryHandle.stopTask(taskId);+ }+/*** Deliver a user message into the running session. Claude Code reads it at* its next tool boundary, so a running tool is never cut short (a message@@ -410,10 +424,35 @@ export class ClaudeAgentSdkSession {await this.options.onEvents(events);if (this.pipeline.sessionId) this.options.onSessionId(this.pipeline.sessionId);+ this.trackTurn(message);this.maybeCloseInputAfterResult(message);+ this.maybeCloseInputAfterStop(message);this.emitStatus(this.resolveRuntimeState());}+ private trackTurn(message: SDKMessage): void {+ if (message.type === 'result') this.turnOpen = false;+ else if (+ message.type === 'assistant' ||+ (message.type === 'system' && message.subtype === 'init')+ ) {+ this.turnOpen = true;+ }+ }++ /**+ * Claude Code wakes the model for a task that ended on its own, not for one+ * that was stopped: no `result` follows a `stopped` notification. Between+ * turns, the last task being stopped is therefore what ends the session.+ */+ private maybeCloseInputAfterStop(message: SDKMessage): void {+ if (message.type !== 'system' || message.subtype !== 'task_notification') return;+ if (message.status !== 'stopped' || this.turnOpen) return;+ // A steered message still waiting to be read starts the next turn.+ if (this.unconsumed.size > 0 || this.steerQueue.length > 0) return;+ if (this.activeTasks.size === 0 && !this.taskNotificationPending) this.closeInput = true;+ }+private async flushPipeline(): Promise<void> {const events = await this.pipeline.flush();this.sawErrorEvent ||= events.some((event) => event.type === 'error');@@ -461,11 +500,17 @@ export class ClaudeAgentSdkSession {}if (message.subtype === 'task_notification') {- this.taskNotificationPending = true;+ // A stopped task wakes no follow-up turn (see `maybeCloseInputAfterStop`).+ if (message.status !== 'stopped') this.taskNotificationPending = true;this.activeTasks.delete(message.task_id);}}+ /**+ * Close the input once nothing can still need it. It stays open while a task+ * lives: stopping one is a control request written to it, and with the input+ * closed Claude Code never reads the request.+ */private maybeCloseInputAfterResult(message: SDKMessage): void {if (message.type !== 'result') return;const notificationTurn = message.origin?.kind === 'task-notification';@@ -475,10 +520,9 @@ export class ClaudeAgentSdkSession {// it still has to be read and answered.if (this.unconsumed.size > 0 || this.steerQueue.length > 0) return;- if (notificationTurn) {- this.closeInput = true;- return;- }+ // A resumed session first reports the previous run's leftover tasks and+ // ends that pass with an empty result, before this run's own turn.+ if (notificationTurn && message.num_turns === 0) return;if (this.activeTasks.size === 0 && !this.taskNotificationPending) {this.closeInput = true;diff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.tsindex d24b801e9a6..27b22d798b4 100644--- a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.ts@@ -137,7 +137,7 @@ describe('ClaudeCodeLiveInput', () => {live.observe(line({- patch: { status: 'killed' },+ patch: { status: 'completed' },subtype: 'task_updated',task_id: 't-1',type: 'system',@@ -150,6 +150,46 @@ describe('ClaudeCodeLiveInput', () => {expect(live.isOpen).toBe(false);});+ // Recorded from claude 2.1.308: a stopped task reports `task_updated(killed)`+ // then `task_notification(stopped)`, and no turn follows.+ it.each([+ ['killed patch', { patch: { status: 'killed' }, subtype: 'task_updated' }],+ ['stopped notification', { status: 'stopped', subtype: 'task_notification' }],+ ])('closes at once when the last task is stopped between turns (%s)', (_, event) => {+ vi.useFakeTimers();+ const { live } = setup({ wakeUpGraceMs: 30_000 });+ live.send(userLine('first'), 'u-1');+ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ live.observe(line({ subtype: 'task_started', task_id: 't-1', type: 'system' }));+ live.observe(line({ subtype: 'success', type: 'result' }));++ live.observe(line({ ...event, task_id: 't-1', type: 'system' }));+ expect(live.isOpen).toBe(false);+ });++ it('keeps stdin for the other task, or the open turn, when one task is stopped', () => {+ const { live } = setup();+ live.send(userLine('first'), 'u-1');+ live.observe(line({ isReplay: true, type: 'user', uuid: 'u-1' }));+ live.observe(line({ subtype: 'task_started', task_id: 't-1', type: 'system' }));+ live.observe(line({ subtype: 'task_started', task_id: 't-2', type: 'system' }));+ live.observe(line({ subtype: 'success', type: 'result' }));++ live.observe(+ line({ status: 'stopped', subtype: 'task_notification', task_id: 't-1', type: 'system' }),+ );+ expect(live.isOpen).toBe(true);++ // Stopped mid-turn: that turn's own result decides.+ live.observe(line({ subtype: 'init', type: 'system' }));+ live.observe(+ line({ status: 'stopped', subtype: 'task_notification', task_id: 't-2', type: 'system' }),+ );+ expect(live.isOpen).toBe(true);+ live.observe(line({ subtype: 'success', type: 'result' }));+ expect(live.isOpen).toBe(false);+ });+it('waits for a message delivered mid-turn to be picked up before closing', () => {const { live } = setup();live.send(userLine('first'), 'u-1');diff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.tsindex 07142b060c4..a96eb6f126c 100644--- a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts@@ -13,8 +13,8 @@ const DEFAULT_IDLE_CLOSE_MS = 30 * 60 * 1000;/*** How long a task that ends between turns may wait for the main-agent turn its* notification wakes. Claude Code opens that turn within milliseconds; the- * grace only bounds an end that wakes nothing, such as a task killed between- * turns.+ * grace only bounds an end that unexpectedly wakes nothing. A stopped task+ * never wakes one, so it does not wait (see `observeSystem`).*/const DEFAULT_WAKE_UP_GRACE_MS = 30 * 1000;@@ -283,7 +283,13 @@ export class ClaudeCodeLiveInput {TERMINAL_TASK_STATUSES.has(message.patch?.status as string));if (ended && message.task_id) {this.activeTasks.delete(message.task_id);- this.awaitWakeUpTurn();+ // Claude Code wakes the model for a task that ended on its own, never for+ // one that was stopped: nothing is left to wait for.+ const stopped =+ message.patch?.status === 'killed' ||+ (message.subtype === 'task_notification' && message.status === 'stopped');+ if (stopped) this.closeIfIdle();+ else this.awaitWakeUpTurn();}}diff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeStopTask.test.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeStopTask.test.tsnew file mode 100644index 00000000000..3aa1c0bd9b8--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeStopTask.test.ts@@ -0,0 +1,71 @@+import { PassThrough } from 'node:stream';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { ClaudeCodeLiveInput } from './claudeCodeLiveInput';+import { STOP_TASK_ANSWER_TIMEOUT_MS, stopClaudeCodeTask } from './claudeCodeStopTask';++const createLiveInput = () => {+ const stdin = new PassThrough();+ const written: any[] = [];+ stdin.on('data', (chunk: Buffer) => {+ for (const raw of chunk.toString().split('\n')) if (raw) written.push(JSON.parse(raw));+ });+ const live = new ClaudeCodeLiveInput(stdin);+ return { live, send: live.sendControlRequest.bind(live), written };+};++/** Claude Code's answer, as recorded from `claude` 2.1.308. */+const answer = (requestId: string, response: Record<string, unknown>) =>+ `${JSON.stringify({ response: { request_id: requestId, ...response }, type: 'control_response' })}\n`;++describe('stopClaudeCodeTask', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('writes stop_task and resolves once Claude Code accepts', async () => {+ const { live, send, written } = createLiveInput();+ const stopping = stopClaudeCodeTask(send, 'bys1w0wxo');++ await vi.waitFor(() => expect(written).toHaveLength(1));+ expect(written[0]).toMatchObject({+ request: { subtype: 'stop_task', task_id: 'bys1w0wxo' },+ type: 'control_request',+ });+ live.observe(answer(written[0].request_id, { response: {}, subtype: 'success' }));+ await expect(stopping).resolves.toBeUndefined();+ });++ it('throws what Claude Code answers with', async () => {+ const { live, send, written } = createLiveInput();+ const stopping = stopClaudeCodeTask(send, 'missing');++ await vi.waitFor(() => expect(written).toHaveLength(1));+ live.observe(answer(written[0].request_id, { error: 'No task found', subtype: 'error' }));+ await expect(stopping).rejects.toThrow('No task found');+ });++ it('throws once the input closed', async () => {+ await expect(stopClaudeCodeTask(() => undefined, 't')).rejects.toThrow('no longer takes input');+ });++ it('gives up when Claude Code never answers', async () => {+ vi.useFakeTimers();+ const { send } = createLiveInput();+ const stopping = stopClaudeCodeTask(send, 't');+ const assertion = expect(stopping).rejects.toThrow('did not answer');++ await vi.advanceTimersByTimeAsync(STOP_TASK_ANSWER_TIMEOUT_MS);+ await assertion;+ });++ it('gives up when the signal aborts first', async () => {+ const { send } = createLiveInput();+ const controller = new AbortController();+ const stopping = stopClaudeCodeTask(send, 't', { signal: controller.signal });++ controller.abort();+ await expect(stopping).rejects.toThrow('ended before Claude Code answered');+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeStopTask.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeStopTask.tsnew file mode 100644index 00000000000..a55f9faa0da--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeStopTask.ts@@ -0,0 +1,55 @@+import type {+ ClaudeCodeControlRequest,+ ClaudeCodeControlRequestHandle,+} from './claudeCodeLiveInput';++/** How long Claude Code gets to accept a stop before the request is given up. */+export const STOP_TASK_ANSWER_TIMEOUT_MS = 10_000;++const waitForAnswer = <T>(answer: Promise<T>, timeoutMs: number, signal?: AbortSignal) =>+ new Promise<T>((resolve, reject) => {+ const onAbort = () => fail('The run ended before Claude Code answered');+ const fail = (message: string) => {+ clearTimeout(timer);+ signal?.removeEventListener('abort', onAbort);+ reject(new Error(message));+ };+ const timer = setTimeout(+ () => fail('Claude Code did not answer the stop request in time'),+ timeoutMs,+ );+ if (signal?.aborted) return onAbort();+ signal?.addEventListener('abort', onAbort, { once: true });+ void answer.then((value) => {+ clearTimeout(timer);+ signal?.removeEventListener('abort', onAbort);+ resolve(value);+ });+ });++/**+ * Stop one Claude Code background task through the session's live input: write+ * a `stop_task` control request and wait for Claude Code to accept it. The stop+ * is only proven by the task's `killed` / `stopped` report, which arrives on the+ * session's own output; this resolves when Claude Code took the request.+ *+ * @param send Writes a control request into the session's stdin; `undefined`+ * once that input has closed.+ * @throws When the input is closed, Claude Code refuses or never answers, or+ * `signal` aborts first.+ */+export const stopClaudeCodeTask = async (+ send: (request: ClaudeCodeControlRequest) => ClaudeCodeControlRequestHandle | undefined,+ taskId: string,+ options: { signal?: AbortSignal; timeoutMs?: number } = {},+): Promise<void> => {+ const sent = send({ subtype: 'stop_task', task_id: taskId });+ if (!sent) throw new Error('The Claude Code session no longer takes input');++ const answer = await waitForAnswer(+ sent.response,+ options.timeoutMs ?? STOP_TASK_ANSWER_TIMEOUT_MS,+ options.signal,+ );+ if (answer.subtype === 'error') throw new Error(answer.error);+};diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex ecbd20e29d7..2bf53496ad6 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -208,6 +208,7 @@ export {ClaudeCodeLiveInput,} from './claudeCodeLiveInput';export { readClaudeCodeSessionCost } from './claudeCodeSessionCost';+export { STOP_TASK_ANSWER_TIMEOUT_MS, stopClaudeCodeTask } from './claudeCodeStopTask';export {ensureClaudeCodeResumeTranscript,type EnsureResumeTranscriptReason,diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.tsindex ebb4b636368..d70f7a26a7c 100644--- a/packages/heterogeneous-agents/src/types.ts+++ b/packages/heterogeneous-agents/src/types.ts@@ -41,6 +41,12 @@ export type HeterogeneousEventType =*/| 'tool_result'| 'step_complete'+ /**+ * Snapshot of one background task a main-agent tool started (Claude Code+ * `run_in_background` Bash, Monitor). Persisted on that tool message's+ * `pluginState.backgroundTask`; see {@link BackgroundTaskEventData}.+ */+ | 'background_task'| 'agent_runtime_end'| 'error';@@ -327,6 +333,52 @@ export interface UsageData {totalTokens: number;}+/**+ * Lifecycle of a background task. `interrupted` is never reported by the agent:+ * it marks a task that was still running when its session or process ended.+ */+export type HeteroBackgroundTaskStatus =+ 'completed' | 'failed' | 'interrupted' | 'running' | 'stopped';++/**+ * Complete state of one background task, stored on the tool message that+ * started it as `pluginState.backgroundTask`. Every event carries the whole+ * snapshot, so a consumer replaces the stored value instead of merging.+ */+export interface HeteroBackgroundTask {+ description: string;+ /** Epoch ms the task ended at; absent while it runs. */+ endedAt?: number;+ error?: string;+ /** Tool the task is running, for a task that reports one (agent-like tasks). */+ lastToolName?: string;+ /**+ * Operation that hosts the task's session. Stamped by the interpreter, not+ * the adapter: it is how a client routes a stop and tells whether the+ * session is still alive.+ */+ operationId?: string;+ /** Absolute path of the task's output on the machine that runs the agent. */+ outputFile?: string;+ startedAt: number;+ status: HeteroBackgroundTaskStatus;+ /** Final summary reported with the task's end. */+ summary?: string;+ /** Agent-native task id (Claude Code `task_id`), the handle a stop targets. */+ taskId: string;+ /** Agent-native task kind, e.g. Claude Code `local_bash`. */+ taskType?: string;+ /** Tool that started the task, e.g. `Bash` or `Monitor`. */+ toolName: string;+}++/** Data shape for `background_task` events. */+export interface BackgroundTaskEventData {+ task: HeteroBackgroundTask;+ /** Main-agent tool call that started the task; owns the persisted snapshot. */+ toolCallId: string;+}+/*** Data shape for `step_complete` events. `phase` disambiguates the subtype:* - `turn_metadata`: per-turn snapshot of model + provider + usage (once per LLM call)diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex b5ed7016c77..c0db254571b 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3894,6 +3894,23 @@ export default {'workingPanel.openMenu.title': 'Open workspace panel','workingPanel.openMenu.tools': 'Tools','workingPanel.openMenu.workspace': 'Workspace',+ 'workingPanel.overview.backgroundTasks.collapse': 'Show less',+ 'workingPanel.overview.backgroundTasks.locate': 'Show in conversation',+ 'workingPanel.overview.backgroundTasks.showAll': 'Show all ({{count}})',+ 'workingPanel.overview.backgroundTasks.status.completed': 'Done',+ 'workingPanel.overview.backgroundTasks.status.failed': 'Failed',+ 'workingPanel.overview.backgroundTasks.status.interrupted': 'Interrupted',+ 'workingPanel.overview.backgroundTasks.status.running': 'Running',+ 'workingPanel.overview.backgroundTasks.status.stopped': 'Stopped',+ 'workingPanel.overview.backgroundTasks.stop': 'Stop',+ 'workingPanel.overview.backgroundTasks.stopFailed': "Couldn't stop the task",+ 'workingPanel.overview.backgroundTasks.stopNoAnswer':+ "The device hasn't answered yet. Try again in a moment.",+ 'workingPanel.overview.backgroundTasks.stopUpgradeLh':+ 'Update lh on the device to stop background tasks',+ 'workingPanel.overview.backgroundTasks.stopping': 'Stopping…',+ 'workingPanel.overview.backgroundTasks.title': 'Background tasks',+ 'workingPanel.overview.backgroundTasks.viewOutput': 'View output','workingPanel.overview.branch.detached': 'Detached HEAD','workingPanel.overview.changes': 'Changes','workingPanel.overview.changes.none': 'No changes',diff --git a/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/BackgroundTaskRow.tsx b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/BackgroundTaskRow.tsxnew file mode 100644index 00000000000..2dbe39af7d3--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/BackgroundTaskRow.tsx@@ -0,0 +1,159 @@+import type { HeteroBackgroundTaskStatus } from '@lobechat/heterogeneous-agents';+import { formatDuration } from '@lobechat/utils';+import { ActionIcon, Icon, toast, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import {+ CircleCheckIcon,+ CircleSlashIcon,+ CircleStopIcon,+ CircleXIcon,+ FileTextIcon,+ type LucideIcon,+ RadarIcon,+ SquareIcon,+ SquareTerminalIcon,+} from 'lucide-react';+import { type MouseEvent, useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import RingLoadingIcon from '@/components/RingLoading';++import { OverviewRow } from '../OverviewRow';+import type { BackgroundTaskItem, BackgroundTaskStopRoute } from './backgroundTaskList';+import { type StopBackgroundTaskFailure, useStopBackgroundTask } from './useStopBackgroundTask';++const styles = stylex.create({+ summary: {+ color: cssVar.colorTextTertiary,+ marginInlineStart: 6,+ },+});++const TOOL_ICONS: Record<string, LucideIcon> = { Bash: SquareTerminalIcon, Monitor: RadarIcon };++const STATUS_VISUAL: Record<+ Exclude<HeteroBackgroundTaskStatus, 'running'>,+ { color: string; icon: LucideIcon }+> = {+ completed: { color: cssVar.colorSuccess, icon: CircleCheckIcon },+ failed: { color: cssVar.colorError, icon: CircleXIcon },+ interrupted: { color: cssVar.colorWarning, icon: CircleSlashIcon },+ stopped: { color: cssVar.colorTextTertiary, icon: CircleStopIcon },+};++const FAILURE_KEYS = {+ failed: 'workingPanel.overview.backgroundTasks.stopFailed',+ noAnswer: 'workingPanel.overview.backgroundTasks.stopNoAnswer',+ upgradeLh: 'workingPanel.overview.backgroundTasks.stopUpgradeLh',+} as const satisfies Record<StopBackgroundTaskFailure, string>;++/** Epoch ms, ticking every second while `live`. */+const useNow = (live: boolean) => {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (!live) return;+ const interval = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(interval);+ }, [live]);+ return now;+};++const stopClick = (handler: () => void) => (event: MouseEvent) => {+ event.stopPropagation();+ handler();+};++interface BackgroundTaskRowProps {+ item: BackgroundTaskItem;+ onLocate: (item: BackgroundTaskItem) => void;+ /** Opens the output file; absent when this client cannot read the run's files. */+ onViewOutput?: (path: string) => void;+ stopRoute?: BackgroundTaskStopRoute;+}++export const BackgroundTaskRow = ({+ item,+ onLocate,+ onViewOutput,+ stopRoute,+}: BackgroundTaskRowProps) => {+ const { t } = useTranslation('chat');+ const { status, task } = item;+ const running = status === 'running';+ const now = useNow(running);++ const onFailure = useCallback(+ (failure: StopBackgroundTaskFailure) => toast.error(t(FAILURE_KEYS[failure])),+ [t],+ );+ const { canStop, stop, stopping } = useStopBackgroundTask({+ onFailure,+ operationId: task.operationId,+ route: stopRoute,+ running,+ taskId: task.taskId,+ });++ const elapsed = formatDuration(Math.max(0, (task.endedAt ?? now) - task.startedAt), {+ pad: true,+ });+ const statusLabel = stopping+ ? t('workingPanel.overview.backgroundTasks.stopping')+ : t(`workingPanel.overview.backgroundTasks.status.${status}`);+ const summary =+ !running && task.summary && task.summary !== task.description ? task.summary : undefined;+ const visual = running ? undefined : STATUS_VISUAL[status as keyof typeof STATUS_VISUAL];+ const outputFile = task.outputFile;++ return (+ <OverviewRow+ icon={TOOL_ICONS[task.toolName] ?? SquareTerminalIcon}+ iconSize={15}+ title={[task.description, summary].filter(Boolean).join('\n')}+ trailing={+ <>+ <span>{elapsed}</span>+ {outputFile && onViewOutput && (+ <ActionIcon+ icon={FileTextIcon}+ size={'small'}+ title={t('workingPanel.overview.backgroundTasks.viewOutput')}+ onClick={stopClick(() => onViewOutput(outputFile))}+ />+ )}+ {canStop && (+ <ActionIcon+ disabled={stopping}+ icon={SquareIcon}+ loading={stopping}+ size={'small'}+ title={+ stopping+ ? t('workingPanel.overview.backgroundTasks.stopping')+ : t('workingPanel.overview.backgroundTasks.stop')+ }+ onClick={stopClick(() => void stop())}+ />+ )}+ <Tooltip title={statusLabel}>+ <span aria-label={statusLabel} role={'img'}>+ {running ? (+ <RingLoadingIcon size={12} />+ ) : (+ <Icon icon={visual!.icon} size={14} style={{ color: visual!.color }} />+ )}+ </span>+ </Tooltip>+ </>+ }+ value={+ <>+ {task.description}+ {summary && <span {...stylex.props(styles.summary)}>{summary}</span>}+ </>+ }+ onClick={() => onLocate(item)}+ />+ );+};diff --git a/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/backgroundTaskList.test.ts b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/backgroundTaskList.test.tsnew file mode 100644index 00000000000..77aaad993bc--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/backgroundTaskList.test.ts@@ -0,0 +1,163 @@+import type { HeteroBackgroundTask } from '@lobechat/heterogeneous-agents';+import { describe, expect, it } from 'vitest';++import {+ collectBackgroundTasks,+ findLiveOperation,+ FINISHED_TASKS_PREVIEW,+ groupBackgroundTasks,+ locateToolCall,+ outputDirectoryOf,+ resolveStopRoute,+} from './backgroundTaskList';++const task = (overrides: Partial<HeteroBackgroundTask> = {}): HeteroBackgroundTask => ({+ description: 'ping',+ operationId: 'op-live',+ startedAt: 100,+ status: 'running',+ taskId: 't-1',+ toolName: 'Bash',+ ...overrides,+});++const toolMessage = (id: string, backgroundTask?: unknown) => ({+ id,+ pluginState: backgroundTask ? { backgroundTask } : undefined,+ role: 'tool',+ tool_call_id: `call-${id}`,+});++const isLive = (operationId: string | undefined) => operationId === 'op-live';++describe('collectBackgroundTasks', () => {+ it('lists tool messages that carry a task, newest first', () => {+ const items = collectBackgroundTasks(+ [+ toolMessage('a', task({ startedAt: 100, taskId: 'a' })),+ { id: 'assistant', role: 'assistant' },+ toolMessage('plain'),+ toolMessage('b', task({ endedAt: 500, status: 'completed', taskId: 'b' })),+ toolMessage('c', task({ startedAt: 300, taskId: 'c' })),+ ],+ isLive,+ );++ expect(items.map((item) => item.task.taskId)).toEqual(['b', 'c', 'a']);+ expect(items[0]).toMatchObject({ messageId: 'b', toolCallId: 'call-b' });+ });++ it('shows a running task whose run is gone as interrupted', () => {+ const [item] = collectBackgroundTasks(+ [toolMessage('a', task({ operationId: 'op-dead' }))],+ isLive,+ );+ expect(item.status).toBe('interrupted');+ expect(item.task.status).toBe('running');+ });++ it('keeps a finished task as reported, live run or not', () => {+ const [item] = collectBackgroundTasks(+ [toolMessage('a', task({ operationId: 'op-dead', status: 'stopped' }))],+ isLive,+ );+ expect(item.status).toBe('stopped');+ });++ it('skips malformed snapshots', () => {+ expect(+ collectBackgroundTasks(+ [+ toolMessage('a', { status: 'running' }),+ toolMessage('b', task({ status: 'weird' as any })),+ ],+ isLive,+ ),+ ).toEqual([]);+ });+});++describe('groupBackgroundTasks', () => {+ const items = collectBackgroundTasks(+ [+ toolMessage('run', task({ taskId: 'run' })),+ ...Array.from({ length: FINISHED_TASKS_PREVIEW + 2 }, (_, i) =>+ toolMessage(`done-${i}`, task({ endedAt: 1000 + i, status: 'completed', taskId: `d${i}` })),+ ),+ ],+ isLive,+ );++ it('shows every running task and the most recent finished ones', () => {+ const groups = groupBackgroundTasks(items, false);+ expect(groups.running.map((item) => item.task.taskId)).toEqual(['run']);+ expect(groups.finished).toHaveLength(FINISHED_TASKS_PREVIEW);+ expect(groups.finished[0].task.taskId).toBe(`d${FINISHED_TASKS_PREVIEW + 1}`);+ expect(groups.hiddenCount).toBe(2);+ });++ it('shows all finished tasks on request', () => {+ const groups = groupBackgroundTasks(items, true);+ expect(groups.finished).toHaveLength(FINISHED_TASKS_PREVIEW + 2);+ expect(groups.hiddenCount).toBe(0);+ });+});++describe('resolveStopRoute', () => {+ const operations = [+ { id: 'local-op', metadata: {}, status: 'running' },+ { id: 'gw-local', metadata: { serverOperationId: 'server-op' }, status: 'running' },+ { id: 'done-op', metadata: { serverOperationId: 'old-server-op' }, status: 'completed' },+ ];++ it('stops through this window when it hosts the session', () => {+ expect(resolveStopRoute(operations, 'local-op', true)).toBe('local');+ });++ it('stops through the server for a server-hosted run', () => {+ expect(resolveStopRoute(operations, 'server-op', false)).toBe('server');+ });++ it('offers nothing for a local CLI spawn or a finished run', () => {+ expect(resolveStopRoute(operations, 'local-op', false)).toBeUndefined();+ expect(resolveStopRoute(operations, 'old-server-op', false)).toBeUndefined();+ expect(resolveStopRoute(operations, undefined, false)).toBeUndefined();+ });++ it('finds a live run by local or server id', () => {+ expect(findLiveOperation(operations, 'server-op')?.id).toBe('gw-local');+ expect(findLiveOperation(operations, 'done-op')).toBeUndefined();+ });+});++describe('outputDirectoryOf', () => {+ it('returns the parent directory', () => {+ expect(outputDirectoryOf('/tmp/claude/tasks/b1.output')).toBe('/tmp/claude/tasks');+ expect(outputDirectoryOf('C:\\tmp\\b1.output')).toBe('C:\\tmp');+ });+});++describe('locateToolCall', () => {+ it('finds the assistant group that renders the tool call', () => {+ const messages = [+ { id: 'user-1' },+ { children: [{ id: 'block-1', tools: [{ id: 'call-other' }] }], id: 'group-1' },+ {+ children: [{ id: 'block-2' }, { id: 'block-3', tools: [{ id: 'call-bash' }] }],+ id: 'group-2',+ },+ ];+ expect(locateToolCall(messages, 'call-bash')).toEqual({ elementId: 'group-2', index: 2 });+ });++ it('finds a plain assistant message carrying the tool', () => {+ expect(locateToolCall([{ id: 'a', tools: [{ id: 'call-bash' }] }], 'call-bash')).toEqual({+ elementId: 'a',+ index: 0,+ });+ });++ it('returns nothing for a call not displayed', () => {+ expect(locateToolCall([{ id: 'a' }], 'call-bash')).toBeUndefined();+ });+});diff --git a/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/backgroundTaskList.ts b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/backgroundTaskList.tsnew file mode 100644index 00000000000..bea6745f8f1--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/backgroundTaskList.ts@@ -0,0 +1,155 @@+import type {+ HeteroBackgroundTask,+ HeteroBackgroundTaskStatus,+} from '@lobechat/heterogeneous-agents';++/** Finished tasks shown before "show all". */+export const FINISHED_TASKS_PREVIEW = 5;++const STATUSES = new Set<HeteroBackgroundTaskStatus>([+ 'completed',+ 'failed',+ 'interrupted',+ 'running',+ 'stopped',+]);++export interface BackgroundTaskItem {+ /** The tool message that started the task and carries its snapshot. */+ messageId: string;+ /**+ * What to show: a task stored as `running` whose run is gone (the app+ * restarted, the process died before it could say so) shows `interrupted`.+ */+ status: HeteroBackgroundTaskStatus;+ task: HeteroBackgroundTask;+ toolCallId: string;+}++interface ToolMessageLike {+ id: string;+ pluginState?: Record<string, any> | null;+ role?: string;+ tool_call_id?: string | null;+}++const readTask = (value: unknown): HeteroBackgroundTask | undefined => {+ const task = value as HeteroBackgroundTask | undefined;+ if (!task || typeof task.taskId !== 'string' || !STATUSES.has(task.status)) return;+ if (typeof task.startedAt !== 'number') return;+ return task;+};++/**+ * Every background task of the conversation, newest first.+ *+ * @param isRunLive Whether the run hosting a task (`task.operationId`) is+ * still alive in this client.+ */+export const collectBackgroundTasks = (+ messages: readonly ToolMessageLike[],+ isRunLive: (operationId: string | undefined) => boolean,+): BackgroundTaskItem[] => {+ const items: BackgroundTaskItem[] = [];+ for (const message of messages) {+ if (message.role !== 'tool' || !message.tool_call_id) continue;+ const task = readTask(message.pluginState?.backgroundTask);+ if (!task) continue;++ const status =+ task.status === 'running' && !isRunLive(task.operationId) ? 'interrupted' : task.status;+ items.push({ messageId: message.id, status, task, toolCallId: message.tool_call_id });+ }++ const sortKey = (item: BackgroundTaskItem) => item.task.endedAt ?? item.task.startedAt;+ return items.sort((a, b) => sortKey(b) - sortKey(a));+};++export interface BackgroundTaskGroups {+ /** Finished tasks currently shown. */+ finished: BackgroundTaskItem[];+ /** Finished tasks folded away behind "show all". */+ hiddenCount: number;+ running: BackgroundTaskItem[];+}++/** Every running task, and the most recent finished ones unless all are asked for. */+export const groupBackgroundTasks = (+ items: readonly BackgroundTaskItem[],+ showAllFinished: boolean,+): BackgroundTaskGroups => {+ const running = items.filter((item) => item.status === 'running');+ const allFinished = items.filter((item) => item.status !== 'running');+ const finished = showAllFinished ? allFinished : allFinished.slice(0, FINISHED_TASKS_PREVIEW);+ return { finished, hiddenCount: allFinished.length - finished.length, running };+};++interface OperationLike {+ id: string;+ metadata?: { serverOperationId?: string };+ status: string;+}++const LIVE_OPERATION_STATUSES = new Set(['paused', 'running']);++/**+ * How to stop a running task.+ * - `local`: this window hosts the run and can stop one task (SDK session);+ * - `server`: the run lives on a server-reached `lh` (device, gateway, cloud);+ * - `undefined`: no way to stop just this task (a plain local CLI spawn).+ */+export type BackgroundTaskStopRoute = 'local' | 'server';++/** The store operation that hosts a run, matched by local or server id. */+export const findLiveOperation = <T extends OperationLike>(+ operations: readonly T[],+ operationId: string | undefined,+): T | undefined => {+ if (!operationId) return;+ return operations.find(+ (op) =>+ LIVE_OPERATION_STATUSES.has(op.status) &&+ (op.id === operationId || op.metadata?.serverOperationId === operationId),+ );+};++export const resolveStopRoute = (+ operations: readonly OperationLike[],+ operationId: string | undefined,+ hasLocalStopper: boolean,+): BackgroundTaskStopRoute | undefined => {+ if (hasLocalStopper) return 'local';+ const operation = findLiveOperation(operations, operationId);+ if (operation && operation.metadata?.serverOperationId === operationId) return 'server';+ return undefined;+};++/** The directory holding an output file: the root a file read is scoped to. */+export const outputDirectoryOf = (path: string): string => {+ const index = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));+ return index > 0 ? path.slice(0, index) : path;+};++interface DisplayMessageLike {+ children?: Array<{ id: string; tools?: Array<{ id: string; result_msg_id?: string }> }>;+ id: string;+ tools?: Array<{ id: string; result_msg_id?: string }>;+}++/**+ * Where the tool call that started a task sits in the displayed conversation:+ * the index to scroll to and the element id to highlight. A tool renders inside+ * its assistant group, so the group is the target.+ */+export const locateToolCall = (+ displayMessages: readonly DisplayMessageLike[],+ toolCallId: string,+): { elementId: string; index: number } | undefined => {+ const owns = (tools?: DisplayMessageLike['tools']) =>+ tools?.some((tool) => tool.id === toolCallId);+ const index = displayMessages.findIndex(+ (message) => owns(message.tools) || message.children?.some((child) => owns(child.tools)),+ );+ if (index < 0) return;+ return { elementId: displayMessages[index].id, index };+};diff --git a/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/index.tsxnew file mode 100644index 00000000000..a27b6cb9c52--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/index.tsx@@ -0,0 +1,114 @@+'use client';++import { Button, Flexbox } from '@lobehub/ui';+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { highlightMessageWhenScrollSettles } from '@/features/Portal/TopicComments/messageLocator';+import { useChatStore } from '@/store/chat';+import { displayMessageSelectors } from '@/store/chat/selectors';+import { getLocalBackgroundTaskStopper } from '@/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++import { sectionStyles } from '../sectionStyles';+import {+ type BackgroundTaskItem,+ groupBackgroundTasks,+ locateToolCall,+ outputDirectoryOf,+ resolveStopRoute,+} from './backgroundTaskList';+import { BackgroundTaskRow } from './BackgroundTaskRow';+import { useBackgroundTasks } from './useBackgroundTasks';++interface BackgroundTasksSectionProps {+ /** Routes the output read to a connected device; empty for this device. */+ deviceId?: string;+ /** Whether this client can read the run's files (this device or a connected one). */+ outputReadable: boolean;+}++const locate = ({ toolCallId }: BackgroundTaskItem) => {+ const state = useChatStore.getState();+ const location = locateToolCall(displayMessageSelectors.mainDisplayChats(state), toolCallId);+ const scrollToIndex = state.mainConversationScrollToIndex;+ if (!location || !scrollToIndex) return;+ requestAnimationFrame(() => {+ scrollToIndex(location.index, { align: 'center', smooth: true });+ highlightMessageWhenScrollSettles(location.elementId);+ });+};++/**+ * Background tasks a Claude Code run started (`run_in_background` Bash,+ * Monitor), Better Coding Experience only. Running ones all show; finished ones+ * fold to the most recent few.+ */+const BackgroundTasksBody = ({ deviceId, outputReadable }: BackgroundTasksSectionProps) => {+ const { t } = useTranslation('chat');+ const { items, liveOperations } = useBackgroundTasks();+ const [showAllFinished, setShowAllFinished] = useState(false);+ const openLocalFile = useChatStore((s) => s.openLocalFile);++ const viewOutput = useCallback(+ (path: string) =>+ openLocalFile({+ allowExternalFilePreview: true,+ deviceId,+ filePath: path,+ workingDirectory: outputDirectoryOf(path),+ }),+ [deviceId, openLocalFile],+ );++ if (items.length === 0) return null;++ const { finished, hiddenCount, running } = groupBackgroundTasks(items, showAllFinished);++ const renderRow = (item: BackgroundTaskItem) => (+ <BackgroundTaskRow+ item={item}+ key={item.messageId}+ stopRoute={resolveStopRoute(+ liveOperations,+ item.task.operationId,+ !!item.task.operationId && !!getLocalBackgroundTaskStopper(item.task.operationId),+ )}+ onLocate={locate}+ onViewOutput={outputReadable ? viewOutput : undefined}+ />+ );++ return (+ <Flexbox className={sectionStyles.section}>+ <Flexbox horizontal align={'center'} className={sectionStyles.sectionHeader} gap={6}>+ <span className={sectionStyles.sectionTitle}>+ {t('workingPanel.overview.backgroundTasks.title')}+ </span>+ {running.length > 0 && <span className={sectionStyles.count}>{running.length}</span>}+ </Flexbox>+ {running.map(renderRow)}+ {finished.map(renderRow)}+ {(hiddenCount > 0 || showAllFinished) && (+ <Button+ size={'small'}+ style={{ alignSelf: 'flex-start' }}+ type={'text'}+ onClick={() => setShowAllFinished((value) => !value)}+ >+ {showAllFinished+ ? t('workingPanel.overview.backgroundTasks.collapse')+ : t('workingPanel.overview.backgroundTasks.showAll', { count: hiddenCount })}+ </Button>+ )}+ </Flexbox>+ );+};++/** Renders nothing unless the Better Coding Experience lab is on. */+export const BackgroundTasksSection = (props: BackgroundTasksSectionProps) => {+ const enabled = useUserStore(labPreferSelectors.enableBetterCodingExperience);+ if (!enabled) return null;+ return <BackgroundTasksBody {...props} />;+};diff --git a/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/useBackgroundTasks.ts b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/useBackgroundTasks.tsnew file mode 100644index 00000000000..02f8b34fe92--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/useBackgroundTasks.ts@@ -0,0 +1,51 @@+import { useMemo } from 'react';++import { useChatStore } from '@/store/chat';+import type { ChatStoreState } from '@/store/chat/initialState';+import { dbMessageSelectors } from '@/store/chat/selectors';++import { collectBackgroundTasks, findLiveOperation } from './backgroundTaskList';++interface LiveOperation {+ id: string;+ metadata: { serverOperationId?: string };+ status: string;+}++/**+ * The ids of every running operation, as one string: a stable selector value,+ * so streaming updates to an operation's metadata do not rerender the section.+ */+const liveOperationsKey = (s: ChatStoreState): string =>+ Object.values(s.operations)+ .filter((op) => op.status === 'running' || op.status === 'paused')+ .map((op) => `${op.id}\u0000${op.metadata?.serverOperationId ?? ''}`)+ .sort()+ .join('\u0001');++const parseLiveOperations = (key: string): LiveOperation[] =>+ key+ ? key.split('\u0001').map((entry) => {+ const [id, serverOperationId] = entry.split('\u0000');+ return {+ id,+ metadata: serverOperationId ? { serverOperationId } : {},+ status: 'running',+ };+ })+ : [];++/** The conversation's background tasks, and the runs still alive in this client. */+export const useBackgroundTasks = () => {+ const messages = useChatStore(dbMessageSelectors.activeDbMessages);+ const liveKey = useChatStore(liveOperationsKey);++ return useMemo(() => {+ const liveOperations = parseLiveOperations(liveKey);+ const items = collectBackgroundTasks(+ messages,+ (operationId) => !!findLiveOperation(liveOperations, operationId),+ );+ return { items, liveOperations };+ }, [liveKey, messages]);+};diff --git a/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/useStopBackgroundTask.test.ts b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/useStopBackgroundTask.test.tsnew file mode 100644index 00000000000..5186cba6302--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/useStopBackgroundTask.test.ts@@ -0,0 +1,105 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerLocalBackgroundTaskStopper } from '@/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks';++import { STOP_PENDING_RESET_MS, useStopBackgroundTask } from './useStopBackgroundTask';++const stopHeteroBackgroundTask = vi.hoisted(() => vi.fn());+vi.mock('@/services/aiAgent', () => ({ aiAgentService: { stopHeteroBackgroundTask } }));++const setup = (props: Partial<Parameters<typeof useStopBackgroundTask>[0]> = {}) => {+ const onFailure = vi.fn();+ const hook = renderHook(+ (p: Parameters<typeof useStopBackgroundTask>[0]) => useStopBackgroundTask(p),+ {+ initialProps: {+ onFailure,+ operationId: 'op-1',+ route: 'server',+ running: true,+ taskId: 'b1',+ ...props,+ },+ },+ );+ return { ...hook, onFailure };+};++describe('useStopBackgroundTask', () => {+ beforeEach(() => {+ stopHeteroBackgroundTask.mockReset();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it('keeps showing stopping after the server accepted, until the task ends', async () => {+ stopHeteroBackgroundTask.mockResolvedValue({ status: 'accepted' });+ const { result, rerender, onFailure } = setup();++ await act(() => result.current.stop());+ expect(stopHeteroBackgroundTask).toHaveBeenCalledWith({ operationId: 'op-1', taskId: 'b1' });+ expect(result.current.stopping).toBe(true);+ expect(onFailure).not.toHaveBeenCalled();++ rerender({ onFailure, operationId: 'op-1', route: 'server', running: false, taskId: 'b1' });+ expect(result.current.stopping).toBe(false);+ expect(result.current.canStop).toBe(false);+ });++ it.each([+ ['unsupported', 'upgradeLh'],+ ['unreachable', 'upgradeLh'],+ ['timeout', 'noAnswer'],+ ['failed', 'failed'],+ ])('reports a %s stop as %s', async (status, failure) => {+ stopHeteroBackgroundTask.mockResolvedValue({ error: 'x', status });+ const { result, onFailure } = setup();++ await act(() => result.current.stop());+ expect(onFailure).toHaveBeenCalledWith(failure);+ expect(result.current.stopping).toBe(false);+ });++ it('stops through the local session that registered for the run', async () => {+ const stop = vi.fn().mockResolvedValue(undefined);+ const unregister = registerLocalBackgroundTaskStopper('op-local', stop);+ const { result } = setup({ operationId: 'op-local', route: 'local' });++ await act(() => result.current.stop());+ expect(stop).toHaveBeenCalledWith('b1');+ expect(stopHeteroBackgroundTask).not.toHaveBeenCalled();+ unregister();+ });++ it('reports a local session that refused', async () => {+ const unregister = registerLocalBackgroundTaskStopper(+ 'op-local',+ vi.fn().mockRejectedValue(new Error('no longer running')),+ );+ const { result, onFailure } = setup({ operationId: 'op-local', route: 'local' });++ await act(() => result.current.stop());+ expect(onFailure).toHaveBeenCalledWith('failed');+ unregister();+ });++ it('frees the button when the stopped snapshot never arrives', async () => {+ vi.useFakeTimers();+ stopHeteroBackgroundTask.mockResolvedValue({ status: 'accepted' });+ const { result } = setup();++ await act(() => result.current.stop());+ expect(result.current.stopping).toBe(true);+ act(() => {+ vi.advanceTimersByTime(STOP_PENDING_RESET_MS);+ });+ expect(result.current.stopping).toBe(false);+ });++ it('cannot stop without a route', () => {+ const { result } = setup({ route: undefined });+ expect(result.current.canStop).toBe(false);+ });+});diff --git a/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/useStopBackgroundTask.ts b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/useStopBackgroundTask.tsnew file mode 100644index 00000000000..4914d854496--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/useStopBackgroundTask.ts@@ -0,0 +1,103 @@+import { useCallback, useEffect, useState } from 'react';++import { aiAgentService } from '@/services/aiAgent';+import { getLocalBackgroundTaskStopper } from '@/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks';++import type { BackgroundTaskStopRoute } from './backgroundTaskList';++/**+ * Why a stop did not go through, as the user should read it:+ * - `upgradeLh`: the device's `lh` cannot stop a task, or never picked the+ * request up (an `lh` older than control messages never does);+ * - `noAnswer`: the device took the request and did not answer in time;+ * - `failed`: anything else.+ */+export type StopBackgroundTaskFailure = 'failed' | 'noAnswer' | 'upgradeLh';++/**+ * A stop accepted by Claude Code whose `stopped` snapshot never came back+ * frees the button after this long, so the user can try again.+ */+export const STOP_PENDING_RESET_MS = 20_000;++const requestStop = async (+ route: BackgroundTaskStopRoute,+ operationId: string,+ taskId: string,+): Promise<StopBackgroundTaskFailure | undefined> => {+ if (route === 'local') {+ const stop = getLocalBackgroundTaskStopper(operationId);+ if (!stop) return 'failed';+ await stop(taskId);+ return;+ }++ const result = await aiAgentService.stopHeteroBackgroundTask({ operationId, taskId });+ switch (result.status) {+ case 'accepted': {+ return;+ }+ case 'unreachable':+ case 'unsupported': {+ return 'upgradeLh';+ }+ case 'timeout': {+ return 'noAnswer';+ }+ default: {+ return 'failed';+ }+ }+};++interface UseStopBackgroundTaskParams {+ onFailure: (failure: StopBackgroundTaskFailure) => void;+ operationId: string | undefined;+ route: BackgroundTaskStopRoute | undefined;+ /** Whether the task still shows as running. */+ running: boolean;+ taskId: string;+}++/**+ * Stop one background task. The task only reads as stopped once its `stopped`+ * snapshot lands; until then the row shows "stopping".+ */+export const useStopBackgroundTask = ({+ onFailure,+ operationId,+ route,+ running,+ taskId,+}: UseStopBackgroundTaskParams) => {+ const [stopping, setStopping] = useState(false);++ // The snapshot that ends the task also ends the wait.+ useEffect(() => {+ if (!running) setStopping(false);+ }, [running]);++ useEffect(() => {+ if (!stopping) return;+ const timer = setTimeout(() => setStopping(false), STOP_PENDING_RESET_MS);+ return () => clearTimeout(timer);+ }, [stopping]);++ const stop = useCallback(async () => {+ if (!route || !operationId || stopping) return;+ setStopping(true);+ let failure: StopBackgroundTaskFailure | undefined;+ try {+ failure = await requestStop(route, operationId, taskId);+ } catch (error) {+ console.error('[BackgroundTasks] stop failed:', error);+ failure = 'failed';+ }+ if (failure) {+ setStopping(false);+ onFailure(failure);+ }+ }, [onFailure, operationId, route, stopping, taskId]);++ return { canStop: !!route && !!operationId && running, stop, stopping };+};diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsxindex 1cf61db048a..6080e61f9b3 100644--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx@@ -54,6 +54,7 @@ import { labPreferSelectors } from '@/store/user/selectors';import GoalSection from '../GoalSection';import ProgressSection from '../ProgressSection';import { toLinkedPullRequest } from '../PullRequest/useSidebarPullRequests';+import { BackgroundTasksSection } from './BackgroundTasks';import DeviceStatusSection from './DeviceStatusSection';import {collectChangeStats,@@ -509,6 +510,9 @@ const Overview = memo<OverviewProps>(/>)}+ {/* Claude Code background tasks; async subagents stay in the thread list below. */}+ <BackgroundTasksSection deviceId={deviceId} outputReadable={environmentAvailable} />+{/* Thread rows open in the Portal; the list labels itself as subagents andsits in its own section so the resource rows below aren't grouped under it. */}{topicId && <ThreadListSection topicId={topicId} />}diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex 1074fe92560..24aa417bac0 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -461,6 +461,15 @@ class AiAgentService {return await lambdaClient.aiAgent.getOperationStatus.query(params);}+ /**+ * Stop one Claude Code background task of a run hosted by `lh hetero exec`.+ * `accepted` only means Claude Code took the request; the task's `stopped`+ * snapshot arrives through the run's own stream.+ */+ async stopHeteroBackgroundTask(params: { operationId: string; taskId: string }) {+ return await lambdaClient.aiAgent.stopHeteroBackgroundTask.mutate(params);+ }+/*** Interrupt a running task*/diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.tsindex b35e10d5b2f..ebf01b4776f 100644--- a/src/services/electron/heterogeneousAgent.ts+++ b/src/services/electron/heterogeneousAgent.ts@@ -94,6 +94,11 @@ class HeterogeneousAgentService {return this.ipc.heterogeneousAgent.cancelSession({ sessionId });}+ /** Stop one background task of a local Claude Code SDK run. */+ async stopBackgroundTask(sessionId: string, taskId: string) {+ return this.ipc.heterogeneousAgent.stopBackgroundTask({ sessionId, taskId });+ }+async stopSession(sessionId: string) {return this.ipc.heterogeneousAgent.stopSession({ sessionId });}diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.tsnew file mode 100644index 00000000000..c1e16f87962--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.ts@@ -0,0 +1,207 @@+/** Claude Code background tasks of a run this desktop hosts itself. */++import { beforeEach, describe, expect, it, vi } from 'vitest';++import { messageService } from '@/services/message';+import { useUserStore } from '@/store/user';++import { getLocalBackgroundTaskStopper } from '../transports/hetero/backgroundTasks';+import { executeHeterogeneousAgent } from '../transports/hetero/heterogeneousAgentExecutor';+import {+ ccInit,+ ccResult,+ ccText,+ ccToolResult,+ ccToolUse,+ createMockStore,+ defaultParams,+ setupIpcCapture,+} from './heterogeneousAgentExecutor.testUtils';++const followUp = vi.hoisted(() => ({ mode: 'queue' as 'legacy' | 'queue' | 'steer' }));+vi.mock('../lifecycle/followUpMode', () => ({ getFollowUpMode: () => followUp.mode }));++const mockSendPrompt = vi.fn();+const mockStartSession = vi.fn();+const mockStopBackgroundTask = vi.fn();++vi.mock('@/services/message', () => ({+ messageService: {+ batchMutate: vi.fn(async (operations: any[]) => ({+ results: operations.map((operation, index) => ({ index, success: true, ...operation })),+ success: true,+ })),+ createMessage: vi.fn(async (params: any) => ({ id: params.id })),+ getMessages: vi.fn(async () => []),+ updateMessage: vi.fn(async () => undefined),+ updateMessageError: vi.fn(async () => ({ success: true })),+ updateToolMessage: vi.fn(async () => undefined),+ },+}));++vi.mock('@/services/electron/heterogeneousAgent', () => ({+ heterogeneousAgentService: {+ cancelSession: vi.fn(async () => undefined),+ getClaudeCodeIdentity: vi.fn(async () => null),+ getCodexQuota: vi.fn(async () => null),+ getSessionInfo: vi.fn(async () => ({})),+ sendPrompt: (...args: any[]) => mockSendPrompt(...args),+ startSession: (...args: any[]) => mockStartSession(...args),+ stopBackgroundTask: (...args: any[]) => mockStopBackgroundTask(...args),+ stopSession: vi.fn(async () => undefined),+ },+}));++vi.mock('@/services/aiAgent', () => ({+ aiAgentService: {+ beginLocalHeteroRunFee: vi.fn(async () => ({ feeId: 'fee-1' })),+ finishLocalHeteroRunFee: vi.fn(async () => ({ success: true })),+ },+}));++vi.mock('@/services/agentQuota', () => ({+ agentQuotaService: {+ recordUsage: vi.fn(async () => undefined),+ selectAccountForAgent: vi.fn(async () => null),+ },+}));++vi.mock('../transports/gateway/gatewayEventHandler', () => ({+ createGatewayEventHandler: vi.fn(() => vi.fn()),+}));++const OUTPUT = '/tmp/claude-501/proj/sess/tasks/bys1w0wxo.output';++const taskStarted = {+ description: 'Ping in background',+ is_backgrounded: true,+ subtype: 'task_started',+ task_id: 'bys1w0wxo',+ task_type: 'local_bash',+ tool_use_id: 'toolu_bash',+ type: 'system',+};++const taskNotification = {+ output_file: OUTPUT,+ status: 'completed',+ subtype: 'task_notification',+ summary: 'Ping in background',+ task_id: 'bys1w0wxo',+ tool_use_id: 'toolu_bash',+ type: 'system',+};++/** Every durable background task write, in order. */+const backgroundTaskWrites = () =>+ vi+ .mocked(messageService.batchMutate)+ .mock.calls.flatMap(([operations]) => operations)+ .filter((op: any) => op.type === 'updateToolMessage' && op.value.pluginState?.backgroundTask)+ .map((op: any) => ({ id: op.id, task: op.value.pluginState.backgroundTask }));++const withSdkLab = async (enabled: boolean, run: () => Promise<void>) => {+ const previous = useUserStore.getState().preference.lab;+ useUserStore.setState((state) => ({+ preference: {+ ...state.preference,+ lab: { ...state.preference.lab, enableClaudeCodeSdk: enabled },+ },+ }));+ try {+ await run();+ } finally {+ useUserStore.setState((state) => ({ preference: { ...state.preference, lab: previous } }));+ }+};++describe('heterogeneousAgentExecutor background tasks', () => {+ let ipc: ReturnType<typeof setupIpcCapture>;+ let stopperDuringRun: ReturnType<typeof getLocalBackgroundTaskStopper>;++ beforeEach(() => {+ vi.clearAllMocks();+ ipc = setupIpcCapture();+ stopperDuringRun = undefined;+ followUp.mode = 'queue';+ mockStartSession.mockResolvedValue({ sessionId: 'ipc-sess-1' });+ mockSendPrompt.mockImplementation(async (params: any) => {+ ipc.emitRawLine(params.sessionId, ccInit());+ ipc.emitRawLine(+ params.sessionId,+ ccToolUse('msg-1', 'toolu_bash', 'Bash', { command: 'ping' }),+ );+ ipc.emitRawLine(params.sessionId, taskStarted);+ ipc.emitRawLine(+ params.sessionId,+ ccToolResult(+ 'toolu_bash',+ `Command running in background. Output is being written to: ${OUTPUT}.`,+ ),+ );+ ipc.emitRawLine(params.sessionId, ccText('msg-2', 'started'));+ ipc.emitRawLine(params.sessionId, ccResult());+ stopperDuringRun = getLocalBackgroundTaskStopper(defaultParams.operationId);+ ipc.emitRawLine(params.sessionId, taskNotification);+ ipc.emitComplete(params.sessionId);+ });+ });++ it('stores each snapshot on the Bash tool message with the run operation', async () => {+ const store = createMockStore();+ await executeHeterogeneousAgent(() => store, defaultParams);++ const writes = backgroundTaskWrites();+ expect(writes.map((w) => w.task.status)).toEqual(['running', 'running', 'completed']);+ expect(new Set(writes.map((w) => w.id)).size).toBe(1);+ expect(writes.at(-1)!.task).toMatchObject({+ operationId: defaultParams.operationId,+ outputFile: OUTPUT,+ summary: 'Ping in background',+ taskId: 'bys1w0wxo',+ toolName: 'Bash',+ });++ // The live store gets the same snapshot under its own key only.+ const live = store.internal_dispatchMessage.mock.calls+ .map(([action]: any[]) => action)+ .filter((action: any) => action.type === 'updatePluginState');+ expect(live.at(-1)).toMatchObject({+ id: writes[0].id,+ key: 'backgroundTask',+ value: { status: 'completed' },+ });+ });++ it('offers a stop for an SDK session only while the run lives', async () => {+ await withSdkLab(true, () => executeHeterogeneousAgent(() => createMockStore(), defaultParams));++ expect(stopperDuringRun).toBeDefined();+ mockStopBackgroundTask.mockResolvedValue(undefined);+ await stopperDuringRun!('bys1w0wxo');+ expect(mockStopBackgroundTask).toHaveBeenCalledWith('ipc-sess-1', 'bys1w0wxo');+ expect(getLocalBackgroundTaskStopper(defaultParams.operationId)).toBeUndefined();+ });++ it('offers no stop for a one-shot CLI spawn (Queue mode closes its stdin)', async () => {+ await withSdkLab(false, () =>+ executeHeterogeneousAgent(() => createMockStore(), defaultParams),+ );+ expect(mockSendPrompt.mock.calls[0][0]).not.toHaveProperty('liveSteer');+ expect(stopperDuringRun).toBeUndefined();+ });++ it('offers a stop for a CLI spawned with live input for Steer', async () => {+ followUp.mode = 'steer';+ await withSdkLab(false, () =>+ executeHeterogeneousAgent(() => createMockStore(), defaultParams),+ );++ expect(mockSendPrompt.mock.calls[0][0]).toMatchObject({ liveSteer: true });+ expect(stopperDuringRun).toBeDefined();+ mockStopBackgroundTask.mockResolvedValue(undefined);+ await stopperDuringRun!('bys1w0wxo');+ expect(mockStopBackgroundTask).toHaveBeenCalledWith('ipc-sess-1', 'bys1w0wxo');+ expect(getLocalBackgroundTaskStopper(defaultParams.operationId)).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex ab8acc2b3b8..6b44d624a20 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -1169,11 +1169,11 @@ export const createGatewayEventHandler = (break;}+ case 'background_task':case 'step_complete': {+ // Sub-agent progress, live steer reads and background tasks, not step boundaries.+ const sideEvent = resolveStepSideEvent(get, event, context, dispatchContext);const data = event.data as StepCompleteData | undefined;-- // Sub-agent progress and live steer reads, not step boundaries.- const sideEvent = resolveStepSideEvent(get, data, context, dispatchContext);if (sideEvent) {if (sideEvent.apply) enqueue(sideEvent.apply);break;diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.test.tsnew file mode 100644index 00000000000..dedce33e084--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it, vi } from 'vitest';++import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import { resolveStepSideEvent } from './stepSideEvent';++const context = { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any;+const dispatchContext = { operationId: 'local-op' };++const task = {+ description: 'ping',+ startedAt: 1,+ status: 'running',+ taskId: 'b1',+ toolName: 'Bash',+};++const createStore = () => {+ const store = {+ dbMessagesMap: {+ [messageMapKey(context)]: [+ { id: 'msg-assistant', role: 'assistant' },+ { id: 'msg-tool', role: 'tool', tool_call_id: 'toolu_bash' },+ ],+ },+ internal_dispatchMessage: vi.fn(),+ };+ return { get: () => store as any, store };+};++describe('resolveStepSideEvent background_task', () => {+ it('patches the snapshot onto the starting tool row with the server operation', () => {+ const { get, store } = createStore();+ const side = resolveStepSideEvent(+ get,+ {+ data: { task, toolCallId: 'toolu_bash' },+ operationId: 'server-op',+ type: 'background_task',+ },+ context,+ dispatchContext,+ );++ side?.apply?.();+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'msg-tool',+ key: 'backgroundTask',+ type: 'updatePluginState',+ value: { ...task, operationId: 'server-op' },+ },+ dispatchContext,+ );+ });++ it('waits for the refetch when the tool row is not loaded yet', () => {+ const { get, store } = createStore();+ const side = resolveStepSideEvent(+ get,+ {+ data: { task, toolCallId: 'toolu_other' },+ operationId: 'server-op',+ type: 'background_task',+ },+ context,+ dispatchContext,+ );++ side?.apply?.();+ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();+ });++ it('is consumed even when malformed, so it never counts as a step boundary', () => {+ const { get } = createStore();+ expect(+ resolveStepSideEvent(+ get,+ { data: {}, operationId: 'op', type: 'background_task' },+ context,+ dispatchContext,+ ),+ ).toEqual({});+ });++ it('leaves a real step boundary to the handler', () => {+ const { get } = createStore();+ expect(+ resolveStepSideEvent(+ get,+ { data: { phase: 'execution_complete' }, operationId: 'op', type: 'step_complete' },+ context,+ dispatchContext,+ ),+ ).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.tsindex 80dcdfb5463..246ddd19b5a 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts@@ -1,7 +1,13 @@-import type { StepCompleteData, SubAgentProgressData } from '@lobechat/agent-gateway-client';+import type {+ AgentStreamEvent,+ StepCompleteData,+ SubAgentProgressData,+} from '@lobechat/agent-gateway-client';+import type { BackgroundTaskEventData } from '@lobechat/heterogeneous-agents';import type { ConversationContext } from '@lobechat/types';import type { ChatStore } from '@/store/chat/store';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { insertSteerMessage } from './streamStartSeed';@@ -10,6 +16,36 @@ import { insertSteerMessage } from './streamStartSeed';* boundary. `apply` is the store update it asks for (none when it carries* nothing to show); the caller enqueues it behind pending refetches.*/+/**+ * A heterogeneous run's background task snapshot, published by the server after+ * it persisted the same value on the tool message. Applied in memory to the+ * starting tool row; a row not loaded yet gets it from the DB on its refetch.+ */+const applyBackgroundTaskSnapshot = (+ get: () => ChatStore,+ { task, toolCallId }: BackgroundTaskEventData,+ target: {+ context: ConversationContext;+ dispatchContext: { operationId: string };+ operationId: string | undefined;+ },+) => {+ const { context, dispatchContext, operationId } = target;+ const messages = get().dbMessagesMap[messageMapKey(context)] ?? [];+ const toolMessage = messages.find((m) => m.role === 'tool' && m.tool_call_id === toolCallId);+ if (!toolMessage) return;++ get().internal_dispatchMessage(+ {+ id: toolMessage.id,+ key: 'backgroundTask',+ type: 'updatePluginState',+ value: { ...task, ...(operationId && { operationId }) },+ },+ dispatchContext,+ );+};+export interface StepSideEvent {apply?: () => void;}@@ -34,10 +70,22 @@ export interface StepSideEvent {*/export const resolveStepSideEvent = (get: () => ChatStore,- data: StepCompleteData | undefined,+ event: Pick<AgentStreamEvent, 'data' | 'operationId' | 'type'>,context: ConversationContext,dispatchContext: { operationId: string },): StepSideEvent | undefined => {+ if (event.type === 'background_task') {+ const snapshot = event.data as BackgroundTaskEventData | undefined;+ if (!snapshot?.toolCallId || !snapshot.task) return {};+ // The server run's operation id: what a stop is routed to.+ const operationId = event.operationId || snapshot.task.operationId;+ return {+ apply: () =>+ applyBackgroundTaskSnapshot(get, snapshot, { context, dispatchContext, operationId }),+ };+ }++ const data = event.data as StepCompleteData | undefined;if (data?.phase === 'subagent_progress') {const progress = data as SubAgentProgressData;if (!progress.toolMessageId) return {};diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks.tsnew file mode 100644index 00000000000..c956797ac40--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks.ts@@ -0,0 +1,69 @@+import type { HeteroBackgroundTask } from '@lobechat/heterogeneous-agents';++import type { MessageQueryContext } from '@/services/message';+import type { ChatStore } from '@/store/chat/store';++import type { createMessageWriteBatcher } from './messageWriteBatcher';++type MessageWriteBatcher = ReturnType<typeof createMessageWriteBatcher>;++/**+ * Stops one background task of a run hosted in this window. Resolves once the+ * agent accepted the request; the task only counts as stopped when its+ * `stopped` notification lands on the tool message.+ */+export type LocalBackgroundTaskStopper = (taskId: string) => Promise<void>;++const localStoppers = new Map<string, LocalBackgroundTaskStopper>();++/**+ * Register how to stop the background tasks of a local run, for as long as+ * its session lives. Only runtimes that can stop a single task register (the+ * Claude Code SDK session); a plain CLI spawn has closed its stdin.+ *+ * @returns Unregister; a no-op once a newer registration took the operation.+ */+export const registerLocalBackgroundTaskStopper = (+ operationId: string,+ stop: LocalBackgroundTaskStopper,+): (() => void) => {+ localStoppers.set(operationId, stop);+ return () => {+ if (localStoppers.get(operationId) === stop) localStoppers.delete(operationId);+ };+};++export const getLocalBackgroundTaskStopper = (+ operationId: string,+): LocalBackgroundTaskStopper | undefined => localStoppers.get(operationId);++interface WriteBackgroundTaskParams {+ messageWriteCtx?: MessageQueryContext;+ operationId: string;+ task: HeteroBackgroundTask;+ toolMessageId: string;+}++/**+ * Store a background task snapshot on its tool message, durable and live.+ * Only the `backgroundTask` key is written, so the tool's own result state+ * stays; the operation id goes with it so the sidebar can route a stop and+ * tell whether the run is still alive.+ */+export const writeBackgroundTaskSnapshot = (+ get: () => Pick<ChatStore, 'internal_dispatchMessage'>,+ batcher: Pick<MessageWriteBatcher, 'enqueueToolMessageUpdate'>,+ { messageWriteCtx, operationId, task, toolMessageId }: WriteBackgroundTaskParams,+): void => {+ const backgroundTask = { ...task, operationId };+ batcher.enqueueToolMessageUpdate(+ toolMessageId,+ { pluginState: { backgroundTask } },+ messageWriteCtx,+ (err) => console.error('[HeterogeneousAgent] Failed to persist background task:', err),+ );+ get().internal_dispatchMessage(+ { id: toolMessageId, key: 'backgroundTask', type: 'updatePluginState', value: backgroundTask },+ { operationId },+ );+};diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex af915d49efc..44654ed88e5 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -72,7 +72,6 @@ import { hydrateProjectedToolMessages } from '@/services/message/hydrateProjecteimport { threadService } from '@/services/thread';import { workService } from '@/services/work';import { topicSelectors } from '@/store/chat/selectors';-import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';import { type StreamRetryMetadata } from '@/store/chat/slices/operation/types';import { type ChatStore, useChatStore } from '@/store/chat/store';import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';@@ -88,6 +87,7 @@ import type { RunScope } from '../../lifecycle/types';import { createGatewayEventHandler } from '../gateway/gatewayEventHandler';import { isCompletedRuntimeEnd } from '../gateway/runtimeEndReason';import { withHeteroContext } from '../viewedTaskPrompt';+import { registerLocalBackgroundTaskStopper, writeBackgroundTaskSnapshot } from './backgroundTasks';import { markUnfinishedToolsCancelled } from './cancelledTools';import { getNativeHeteroSessionBindingKey, isRecoverableResumeError } from './heteroResume';import { preserveSkippedIntervention } from './interventionAck';@@ -108,6 +108,7 @@ import {createSubagentStoreDispatcher,type SubagentStoreDispatcher,} from './subagentStoreDispatcher';+import { createToolStateSnapshotClaimer } from './toolStateSnapshot';/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */const generateThreadId = () => `thd_${createNanoId(16)()}`;@@ -609,6 +610,7 @@ export const executeHeterogeneousAgent = async (let ipcRunSessionId: string | undefined;let unsubscribe: (() => void) | undefined;+ let unregisterTaskStopper: (() => void) | undefined;let completed = false;const runFee: LocalRunFeeClaim = params.runFee ?? {};let fallbackPromise: Promise<void> | undefined;@@ -644,7 +646,6 @@ export const executeHeterogeneousAgent = async (// a subagent finalizes, so unscoped bridge requests cannot create main copies.const toolMsgIdByCallId: Map<string, string> = new Map();const toolThreadIdByCallId = new Map<string, string>();- const lastAppliedToolStateSeqByCallId = new Map<string, number>();const mainToolCallIds = new Set<string>();/** Terminal results reject later state until a new tool_start reopens the call id. */const completedToolStateCallIds = new Set<string>();@@ -966,26 +967,7 @@ export const executeHeterogeneousAgent = async (pendingToolFlush.set(toolMsgId, toolUpdate);});};- const claimToolStateSnapshot = (- toolCallId: string,- toolMsgId: string,- snapshotSeq: number,- ): NonNullable<UIChatMessage['metadata']> | undefined => {- const stored = dbMessageSelectors.getDbMessageById(toolMsgId)(get());- const durableSeq =- stored?.metadata?.heterogeneousToolStateOperationId === operationId &&- typeof stored.metadata.heterogeneousToolStateSeq === 'number'- ? stored.metadata.heterogeneousToolStateSeq- : 0;- const lastApplied = Math.max(durableSeq, lastAppliedToolStateSeqByCallId.get(toolCallId) ?? 0);- if (snapshotSeq <= lastApplied) return;-- lastAppliedToolStateSeqByCallId.set(toolCallId, snapshotSeq);- return {- heterogeneousToolStateOperationId: operationId,- heterogeneousToolStateSeq: snapshotSeq,- };- };+ const claimToolStateSnapshot = createToolStateSnapshotClaimer(get, operationId);const retryWithoutResume = (error: unknown): boolean => {if (resumeFallbackTriggered ||@@ -1444,6 +1426,17 @@ export const executeHeterogeneousAgent = async (// The persisted row owns the thread for bridge transitions as well as tool results.const applyMainIntent = async (intent: MainAgentIntent) => {switch (intent.kind) {+ case 'updateBackgroundTask': {+ const toolMsgId = toolMsgIdByCallId.get(intent.toolCallId);+ if (!toolMsgId || !mainToolCallIds.has(intent.toolCallId)) return;+ writeBackgroundTaskSnapshot(get, messageWriteBatcher, {+ messageWriteCtx,+ operationId,+ task: intent.backgroundTask,+ toolMessageId: toolMsgId,+ });+ return;+ }case 'setToolIntervention': {const toolMsgId = toolMsgIdByCallId.get(intent.toolCallId);if (!toolMsgId) throw new Error(`Missing intervention tool: ${intent.toolCallId}`);@@ -1899,7 +1892,7 @@ export const executeHeterogeneousAgent = async (}: undefined;- // Start session (pass resumeSessionId for multi-turn --resume)+ const useClaudeCodeSdk = labPreferSelectors.enableClaudeCodeSdk(useUserStore.getState());const result = await heterogeneousAgentService.startSession({agentType: adapterType,args: spawnArgs,@@ -1918,7 +1911,7 @@ export const executeHeterogeneousAgent = async (: undefined,providerBinding,resumeSessionId,- useClaudeCodeSdk: labPreferSelectors.enableClaudeCodeSdk(useUserStore.getState()),+ useClaudeCodeSdk,useCodexAppServer: labPreferSelectors.enableCodexAppServer(useUserStore.getState()),});activeSessionBindingKey =@@ -2085,11 +2078,11 @@ export const executeHeterogeneousAgent = async (return;}- // tool_state is interpreted locally after the preceding tools_calling- // intent has registered its tool row. Do not also forward it to the- // gateway handler: that path would bootstrap-refetch while the local+ // tool_state / background_task are interpreted locally after the preceding+ // tools_calling intent has registered its tool row. Do not also forward them+ // to the gateway handler: that path would bootstrap-refetch while the local// write-behind create may still be queued.- if (event.type === 'stream_chunk' && event.data?.chunkType === 'tool_state') {+ if (event.type === 'background_task' || event.data?.chunkType === 'tool_state') {sawStreamedEvent = true;persistQueue = persistQueue.then(() => reduceAndApplyMain(event));return;@@ -2500,6 +2493,12 @@ export const executeHeterogeneousAgent = async (set: (id) => void (mainState = { ...mainState, lastSpineMessageId: id }),},});+ // A task stop needs open input (SDK, or a CLI kept open for Steer); a one-shot CLI has none.+ if (adapterType === 'claude-code' && (useClaudeCodeSdk || localSteer)) {+ unregisterTaskStopper = registerLocalBackgroundTaskStopper(operationId, (taskId) =>+ heterogeneousAgentService.stopBackgroundTask(sidForCancel, taskId),+ );+ }// Send the prompt — blocks until process exitsconst sendResult = await heterogeneousAgentService.sendPrompt({agentId: context.agentId,@@ -2624,6 +2623,7 @@ export const executeHeterogeneousAgent = async (.catch((err) => console.error('[HeterogeneousAgent] cancelled tool cleanup failed:', err));}unsubscribe?.();+ unregisterTaskStopper?.();localSteer?.settle();// The desktop IPC session only owns this run's config and process handles.// Multi-turn resume uses the native agentSessionId persisted above, so thediff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/toolStateSnapshot.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/toolStateSnapshot.tsnew file mode 100644index 00000000000..1d28c328c65--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/toolStateSnapshot.ts@@ -0,0 +1,37 @@+import type { UIChatMessage } from '@lobechat/types';++import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';+import type { ChatStore } from '@/store/chat/store';++/**+ * Claim the right to apply a main-agent `tool_state` snapshot. A snapshot is+ * applied only when its sequence beats both the one stored on the tool row for+ * this operation and the last one this run applied.+ *+ * @returns The metadata to stamp with the applied snapshot, or `undefined` for+ * a stale snapshot that must be dropped.+ */+export const createToolStateSnapshotClaimer = (get: () => ChatStore, operationId: string) => {+ const lastAppliedSeqByCallId = new Map<string, number>();++ return (+ toolCallId: string,+ toolMsgId: string,+ snapshotSeq: number,+ ): NonNullable<UIChatMessage['metadata']> | undefined => {+ const stored = dbMessageSelectors.getDbMessageById(toolMsgId)(get());+ const durableSeq =+ stored?.metadata?.heterogeneousToolStateOperationId === operationId &&+ typeof stored.metadata.heterogeneousToolStateSeq === 'number'+ ? stored.metadata.heterogeneousToolStateSeq+ : 0;+ const lastApplied = Math.max(durableSeq, lastAppliedSeqByCallId.get(toolCallId) ?? 0);+ if (snapshotSeq <= lastApplied) return;++ lastAppliedSeqByCallId.set(toolCallId, snapshotSeq);+ return {+ heterogeneousToolStateOperationId: operationId,+ heterogeneousToolStateSeq: snapshotSeq,+ };+ };+};