Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
1e7f411
🫀 feat: Let a Job Owner Keep a Silent Run Alive
danny-avila Nov 14, 2026
a43ec02
🧶 refactor: Share One Fold From Child Frames to Content Parts
danny-avila Nov 14, 2026
c9b618f
🏷️ feat: Mark the Generation Job of a Background Subagent Task
danny-avila Nov 14, 2026
1a754b6
🧵 feat: Run a Background Child as a Resumable Generation Job
danny-avila Nov 14, 2026
7cc8b3f
🪢 feat: Stream a Background Child Through Its Own Generation Job
danny-avila Nov 14, 2026
a9a9b3d
🔌 feat: Give the Server's Task Store Its Child Stream
danny-avila Nov 14, 2026
80db8e6
🚧 fix: Refuse Chat Abort and Steer on a Background Child's Job
danny-avila Nov 14, 2026
2a8dae4
🧹 fix: Evict a Finished Job Before a Live One at Capacity
danny-avila Nov 14, 2026
e232a12
🛰️ test: Read a Background Child's Stream From Another Replica
danny-avila Nov 14, 2026
baa75b5
🧽 chore: Sort Imports in the Child Stream Files
danny-avila Nov 14, 2026
4e031c5
🧪 test: Expect the Child Stream Lever in the Activity Defaults
danny-avila Nov 14, 2026
5420227
📜 feat: Store What a Background Child Streamed as Standard Content (#…
danny-avila Nov 14, 2026
f265873
🛟 fix: Keep a Stalled or Failing Child Stream From Touching Its Child
danny-avila Nov 14, 2026
65173f3
🧯 fix: Let a Child Stream Observe Its Run Without Ever Stopping It
danny-avila Nov 14, 2026
5b52e4a
♻️ fix: Replace a Dead Background Child's Job on Its Thread
danny-avila Nov 14, 2026
c7a21e4
🧱 fix: Fail the Abort Guard Closed and Budget Content Against the Who…
danny-avila Nov 14, 2026
cd6b424
🪶 refactor: Settle a Child Stream Once and Fold a Frame It Cannot Copy
danny-avila Nov 14, 2026
1611161
🧪 test: Cover the Child Stream's Failure Branches and the Content Fold
danny-avila Nov 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions api/server/routes/agents/__tests__/abort.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,41 @@ describe('Agent Abort Endpoint', () => {
);
});

it('should refuse to abort a background child job, which its task store owns', async () => {
const jobStreamId = 'child-thread-123';

mockGenerationJobManager.getJob.mockResolvedValue({
metadata: {
userId: 'test-user-123',
subagentTaskId: 'task-1',
subagentParentConversationId: 'parent-1',
},
});

const response = await request(app)
.post('/api/agents/chat/abort')
.send({ conversationId: jobStreamId });

expect(response.status).toBe(409);
expect(response.body).toMatchObject({ code: 'CHILD_THREAD_READ_ONLY' });
expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled();
expect(mockSaveMessage).not.toHaveBeenCalled();
expect(mockSaveConvo).not.toHaveBeenCalled();
});

it("should answer 403, not 409, for another user's background child job", async () => {
mockGenerationJobManager.getJob.mockResolvedValue({
metadata: { userId: 'other-user-456', subagentTaskId: 'task-1' },
});

const response = await request(app)
.post('/api/agents/chat/abort')
.send({ conversationId: 'child-thread-123' });

expect(response.status).toBe(403);
expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled();
});

it('should fail closed when job has no userId metadata', async () => {
const jobStreamId = 'test-stream-123';

Expand Down
10 changes: 10 additions & 0 deletions api/server/routes/agents/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const {
reportLocatorTraversalFailure,
isEnabled,
GenerationJobManager,
backgroundChildJobRefusal,
TERMINAL_PUBLICATION_RECONNECT_ERROR,
hasPersistableAbortContent,
announceStoppedReply,
Expand Down Expand Up @@ -728,6 +729,15 @@ router.post('/chat/abort', chatConfigMiddleware, async (req, res, next) => {
if (hasTenantMismatch(job, req.user)) {
return sendGenerationJson(res, 403, { error: 'Unauthorized' }, requestProtocolVersion);
}
const childRefusal = backgroundChildJobRefusal(job);
if (childRefusal) {
return sendGenerationJson(
res,
childRefusal.status,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Move the abort refusal branch into the TypeScript boundary

This adds a new validation branch and HTTP-response decision to the legacy CJS route. Root AGENTS.md explicitly says that /api holds wiring, not behavior, and applies that restriction to branches and validation added while editing existing CJS files. Although the refusal predicate lives in TypeScript, the new control flow remains here; move the refusal handling into the TypeScript request boundary and leave this file wiring the handler.

AGENTS.md reference: AGENTS.md:L80-L84

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 65173f3. The refusal is now createBackgroundChildAbortGuard in packages/api/src/agents/guard.ts: it resolves the abort target, reads the job, and answers 409 only for the owner's background child job. api/server/routes/agents/index.js registers it ahead of the abort handler and no longer contains the branch. Covered by the new background child abort guard cases in guard.spec.ts (owner, other user, other tenant, ownerless job, placeholder, missing id, store failure) and the existing route cases in abort.spec.js.

childRefusal.body,
requestProtocolVersion,
);
}
const generationProtocolVersion = negotiateExistingGenerationProtocol(req, job);
responseProtocolVersion = generationProtocolVersion;
res.set(GENERATION_PROTOCOL_HEADER, String(generationProtocolVersion));
Expand Down
2 changes: 2 additions & 0 deletions api/server/services/Endpoints/agents/subagentThreadStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const {
duplicateIoRedisClient,
createIoRedisSubscriber,
createSubagentThreadTaskStore,
createChildGenerationHost,
createSubagentCompletionWakeupHandler,
GenerationJobManager,
RedisSubagentTaskControlTransport,
Expand Down Expand Up @@ -80,6 +81,7 @@ const subagentThreadTaskStore = createSubagentThreadTaskStore(
renewOwnerAdmission: db.renewSubagentAdmission,
releaseOwnerAdmission: db.releaseSubagentAdmission,
cancelUnroutedTask: cancelUnroutedGeneration,
childGenerations: createChildGenerationHost(GenerationJobManager),
onTaskPrepared: completionWakeupHandler,
onTaskSettled: (userId, conversationId, taskIds) =>
expediteCompletionWakeups({ user: userId, conversationId, taskIds }),
Expand Down
11 changes: 11 additions & 0 deletions api/server/services/Endpoints/agents/subagentThreadStore.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const mockTaskStore = {
destroyActivityStream: jest.fn(),
};
const mockCompletionWakeupHandler = jest.fn().mockResolvedValue(undefined);
const mockChildGenerations = { open: jest.fn() };
const mockGenerationJobManager = { getJob: jest.fn(), abortJob: jest.fn() };

jest.mock('@librechat/api', () => ({
cacheConfig: { USE_REDIS: true, REDIS_KEY_PREFIX: 'test:' },
Expand All @@ -15,6 +17,8 @@ jest.mock('@librechat/api', () => ({
duplicateIoRedisClient: jest.fn(),
createIoRedisSubscriber: jest.fn(),
createSubagentThreadTaskStore: jest.fn(() => mockTaskStore),
createChildGenerationHost: jest.fn(() => mockChildGenerations),
GenerationJobManager: mockGenerationJobManager,
createSubagentCompletionWakeupHandler: jest.fn(() => mockCompletionWakeupHandler),
RedisSubagentTaskControlTransport: jest.fn(),
RedisEventTransport: jest.fn(),
Expand Down Expand Up @@ -54,12 +58,14 @@ const {
registerShutdownTask,
duplicateIoRedisClient,
createIoRedisSubscriber,
createChildGenerationHost,
createSubagentThreadTaskStore,
} = require('@librechat/api');
const subagentThreadTaskStore = require('./subagentThreadStore');
const { configureSubagentTaskRouting } = subagentThreadTaskStore;
const taskStoreOptions = createSubagentThreadTaskStore.mock.calls[0][1];
const taskStoreMethods = createSubagentThreadTaskStore.mock.calls[0][0];
const childGenerationHostArgs = createChildGenerationHost.mock.calls[0];
const db = require('~/models');
const activityPrepareRegistration = registerShutdownTask.mock.calls.find(
([name]) => name === 'subagent activity streams prepare',
Expand All @@ -76,6 +82,11 @@ describe('subagent thread Redis lifecycle', () => {
expect(taskStoreMethods.getSubagentTaskControlReplay).toBe(db.getSubagentTaskControlReplay);
});

it('gives the host store a child stream backed by the generation job manager', () => {
expect(childGenerationHostArgs).toEqual([mockGenerationJobManager]);
expect(taskStoreOptions.childGenerations).toBe(mockChildGenerations);
});

it('pre-registers completion wakeups for every prepared task', async () => {
await taskStoreOptions.onTaskPrepared({ taskId: 'task-1' });

Expand Down
24 changes: 24 additions & 0 deletions packages/api/src/agents/guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,30 @@ import { isAgentEventRetentionActive } from './eventRetention';
export const CHILD_THREAD_READ_ONLY_ERROR =
'This subagent thread is view-only. Continue it from its parent agent or create a separate chat.';

export const CHILD_THREAD_READ_ONLY_CODE = 'CHILD_THREAD_READ_ONLY';

export type BackgroundChildJobRefusal = {
status: 409;
body: { code: typeof CHILD_THREAD_READ_ONLY_CODE; error: string };
};

/**
* The answer for a chat route asked to end or steer a background child's job. The subagent
* task store owns that run: it stops and steers the child through its own control endpoint
* and writes the child's rows itself, so a chat route acting on the job would write a second,
* chat-shaped history into a view-only thread. Null for every other job.
*/
export function backgroundChildJobRefusal(
job: { metadata?: { subagentTaskId?: string } } | null | undefined,
): BackgroundChildJobRefusal | null {
const taskId = job?.metadata?.subagentTaskId;
if (taskId == null || taskId === '') return null;
return {
status: 409,
body: { code: CHILD_THREAD_READ_ONLY_CODE, error: CHILD_THREAD_READ_ONLY_ERROR },
};
}

interface SubagentTurnBody {
conversationId?: unknown;
arg?: { conversationId?: unknown };
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/agents/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export * from './subagentThreads';
export * from './subagentActivity';
export * from './aggregation';
export * from './subagentContent';
export * from './subagentGeneration';
export * from './subagentIdentity';
export * from './subagentCompletionWakeup';
export * from './subagentTaskRouting';
Expand Down
24 changes: 24 additions & 0 deletions packages/api/src/agents/steering/__tests__/request.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,30 @@ describe('handleSteerRequest (real in-memory job manager)', () => {
await expect(GenerationJobManager.steering.peek(streamId)).resolves.toEqual([]);
});

it('409s for a background child job and queues nothing', async () => {
const streamId = 'steer-req-background-child';
await GenerationJobManager.createJob(streamId, user.id, streamId, {
initialMetadata: { subagentTaskId: 'task-1', subagentParentConversationId: 'parent' },
});

const result = await handleSteerRequest(user, { conversationId: streamId, text: 'x' });

expect(result).toEqual({ status: 409, body: { code: 'CHILD_THREAD_READ_ONLY' } });
await expect(GenerationJobManager.steering.peek(streamId)).resolves.toEqual([]);
});

it('403s for another user on a background child job before any other answer', async () => {
const streamId = 'steer-req-background-child-owner';
await GenerationJobManager.createJob(streamId, 'someone-else', streamId, {
initialMetadata: { subagentTaskId: 'task-1', subagentParentConversationId: 'parent' },
});

const result = await handleSteerRequest(user, { conversationId: streamId, text: 'x' });

expect(result.status).toBe(403);
expect(result.body.code).toBe('UNAUTHORIZED');
});

it('409s while the run is paused for human review', async () => {
const streamId = 'steer-req-paused';
await GenerationJobManager.createJob(streamId, user.id);
Expand Down
6 changes: 6 additions & 0 deletions packages/api/src/agents/steering/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
STEER_ENQUEUE_QUEUE_FULL,
STEER_ENQUEUE_RECEIPT_FULL,
} from '~/stream/interfaces/IJobStore';
import { backgroundChildJobRefusal, CHILD_THREAD_READ_ONLY_CODE } from '~/agents/guard';
import { toSteerFileRef, collectFileIds, buildOwnerFilter } from './refs';
import { GenerationJobManager } from '~/stream/GenerationJobManager';
import { sanitizeFileForTransmit } from '../../utils/message';
Expand Down Expand Up @@ -544,6 +545,11 @@ async function handleSteerRequestInternal(
if (expectedGeneration.value != null && job.createdAt !== expectedGeneration.value) {
return { status: 409, body: { code: 'RUN_REPLACED' } };
}
/** The subagent task store runs a background child and injects guidance through its
* own control path; a steer queued here would be accepted and never drained. */
if (backgroundChildJobRefusal(job) != null) {
return { status: 409, body: { code: CHILD_THREAD_READ_ONLY_CODE } };
}

/** A steer is model-bound instruction text for the ORIGINATING agent, so it
* must clear the same role/ACL gates the chat path runs — revoked access
Expand Down
108 changes: 61 additions & 47 deletions packages/api/src/agents/subagentContent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ import type {
import type { SubagentUpdateEvent } from '@librechat/agents';
import type { Response } from 'express';
import type { ServerRequest } from '~/types';
import { createToolTimingAdapter, createToolTimingTracker } from './toolTiming';
import { toWireRunSteps } from '~/stream/interfaces/IJobStore';
import { createToolTimingAdapter } from './toolTiming';
import { getSafeErrorMetadata } from '~/utils/errors';

const CONTENT_GRAPH_EVENTS = {
Expand Down Expand Up @@ -380,6 +380,63 @@ export class SubagentContentJournal {
}
}

export type SubagentContentFold = {
readonly aggregator: ReturnType<typeof createContentAggregator>;
/** Synchronous, so a caller can fold a frame and publish it without yielding in between. */
apply(frame: SubagentContentFrame): void;
};

/** Folds public child frames into content parts the way main chat aggregates its own stream. */
export function createSubagentContentFold(): SubagentContentFold {
const aggregator = createContentAggregator();
const tracker = createToolTimingTracker();
const timing = createToolTimingAdapter({ emit: () => undefined });
const apply = (frame: SubagentContentFrame): void => {
if (frame.event === SteerEvents.ON_STEER_APPLIED) {
aggregator.contentParts[frame.data.index] = frame.data.part;
return;
}
if (frame.event === StepEvents.ON_RUN_STEP_CLOSED) {
const step = aggregator.stepMap.get(frame.data.id);
if (step != null) step.status = frame.data.status;
const part = step == null ? undefined : aggregator.contentParts[step.index];
if (part?.type === ContentTypes.TOOL_CALL && part.tool_call != null) {
part.tool_call.runStepStatus = frame.data.status;
Object.assign(part.tool_call, getRunStepCloseMetadata(frame.data));
const duration = getRunStepDurationMs(frame.data);
if (duration != null) part.tool_call.runStepDurationMs = duration;
}
return;
}
if (frame.event === StepEvents.ON_RUN_STEP_DELTA) {
for (const marker of tracker.observe(frame.data)) {
timing.child(aggregator, { phase: 'tool_preparation', data: marker });
}
}
/** SDK and wire enums have identical values, as in main-chat Redis recovery. */
if (
frame.event !== StepEvents.ON_TOOL_PREPARATION &&
frame.event !== StepEvents.ON_TOOL_CALLS_DISPATCHED
) {
aggregator.aggregateContent({
event: CONTENT_GRAPH_EVENTS[frame.event],
data: frame.data,
} as Parameters<typeof aggregator.aggregateContent>[0]);
}
if (frame.event === StepEvents.ON_MESSAGE_DELTA) {
const step = aggregator.stepMap.get(frame.data.id);
const part = step == null ? undefined : aggregator.contentParts[step.index];
if (part?.type === ContentTypes.TEXT && step?.stepDetails.type === 'message_creation') {
const creation = step.stepDetails.message_creation;
const phase = creation != null && 'phase' in creation ? creation.phase : undefined;
if (phase === 'commentary' || phase === 'final_answer') part.phase = phase;
}
}
timing.child(aggregator, { phase: frame.event.slice(3), data: frame.data });
};
return { aggregator, apply };
}

type ContentReadMethods = Pick<
SubagentContentMethods,
'getSubagentContentHead' | 'streamSubagentContentBatches'
Expand Down Expand Up @@ -431,14 +488,8 @@ export async function readSubagentContent(
},
};
}
const aggregator = createContentAggregator();
const timing = createToolTimingAdapter({
emit: (event) =>
timing.child(aggregator, {
phase: event.event.slice(3),
data: event.data,
}),
});
const fold = createSubagentContentFold();
const { aggregator } = fold;
const events: SubagentContentEvent[] = [];
let throughSequence = afterSequence ?? -1;
let revision: number | undefined;
Expand Down Expand Up @@ -484,44 +535,7 @@ export async function readSubagentContent(
events.push(entry);
continue;
}
const frame = entry.frame;
if (frame.event === SteerEvents.ON_STEER_APPLIED) {
aggregator.contentParts[frame.data.index] = frame.data.part;
continue;
}
if (frame.event === StepEvents.ON_RUN_STEP_CLOSED) {
const step = aggregator.stepMap.get(frame.data.id);
if (step != null) step.status = frame.data.status;
const part = step == null ? undefined : aggregator.contentParts[step.index];
if (part?.type === ContentTypes.TOOL_CALL && part.tool_call != null) {
part.tool_call.runStepStatus = frame.data.status;
Object.assign(part.tool_call, getRunStepCloseMetadata(frame.data));
const duration = getRunStepDurationMs(frame.data);
if (duration != null) part.tool_call.runStepDurationMs = duration;
}
continue;
}
if (frame.event === StepEvents.ON_RUN_STEP_DELTA) await timing.delta(frame.data);
/** SDK and wire enums have identical values, as in main-chat Redis recovery. */
if (
frame.event !== StepEvents.ON_TOOL_PREPARATION &&
frame.event !== StepEvents.ON_TOOL_CALLS_DISPATCHED
) {
aggregator.aggregateContent({
event: CONTENT_GRAPH_EVENTS[frame.event],
data: frame.data,
} as Parameters<typeof aggregator.aggregateContent>[0]);
}
if (frame.event === StepEvents.ON_MESSAGE_DELTA) {
const step = aggregator.stepMap.get(frame.data.id);
const part = step == null ? undefined : aggregator.contentParts[step.index];
if (part?.type === ContentTypes.TEXT && step?.stepDetails.type === 'message_creation') {
const creation = step.stepDetails.message_creation;
const phase = creation != null && 'phase' in creation ? creation.phase : undefined;
if (phase === 'commentary' || phase === 'final_answer') part.phase = phase;
}
}
timing.child(aggregator, { phase: frame.event.slice(3), data: frame.data });
fold.apply(entry.frame);
}
throughSequence = batch.throughSequence;
revision = batch.revision;
Expand Down
Loading
Loading