Skip to content
199 changes: 196 additions & 3 deletions packages/channels/base/src/ChannelBase.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9318,7 +9318,9 @@ describe('ChannelBase', () => {
const firstCancel = ch.handleInbound(envelope({ text: '/cancel' }));
const secondCancel = ch.handleInbound(envelope({ text: '/cancel' }));

expect(bridge.cancelSession).toHaveBeenCalledTimes(1);
await vi.waitFor(() =>
expect(bridge.cancelSession).toHaveBeenCalledTimes(1),
);
resolveCancel();
await Promise.all([firstCancel, secondCancel]);
resolvePrompt('late response');
Expand Down Expand Up @@ -15910,7 +15912,7 @@ describe('ChannelBase', () => {
title: 'CI failed again',
});
secondRun.catch(() => undefined);
await Promise.resolve();
await new Promise((resolve) => setImmediate(resolve));
(
ch as unknown as {
sessionGenerations: Map<string, number>;
Expand Down Expand Up @@ -16012,6 +16014,197 @@ describe('ChannelBase', () => {
.calls[1][1] as string;
expect(collectedPrompt).toContain('follow-up while webhook runs');
});

it('rechecks bridge recovery before a webhook prompt starts', async () => {
const recoveryState: { current?: Promise<void> } = {};
let releaseRecovery: (() => void) | undefined;
let releaseMemoryRead: (() => void) | undefined;
const memoryRead = new Promise<string>((resolve) => {
releaseMemoryRead = () => resolve('');
});
const channelMemory = createChannelMemory();
channelMemory.readChannelMemory.mockReturnValue(memoryRead);
const ch = createChannel(
{ approvalMode: 'yolo', webhooks },
{ bridgeRecovery: () => recoveryState.current, channelMemory },
);
ch.proactiveSupported = true;

const run = ch.runWebhookTask(webhookTask);
await vi.waitFor(() =>
expect(channelMemory.readChannelMemory).toHaveBeenCalledTimes(1),
);
recoveryState.current = new Promise<void>((resolve) => {
releaseRecovery = resolve;
});
releaseMemoryRead!();
await Promise.resolve();

expect(bridge.prompt).not.toHaveBeenCalled();

releaseRecovery!();
await expect(run).resolves.toBe('agent response');

expect(bridge.prompt).toHaveBeenCalledTimes(1);
});
});

it('waits for bridge recovery before resolving an inbound session', async () => {
let releaseBridge: (() => void) | undefined;
const bridgeReady = new Promise<void>((resolve) => {
releaseBridge = resolve;
});
const ch = createChannel({}, { bridgeRecovery: () => bridgeReady });

const inbound = ch.handleInbound(envelope());
await Promise.resolve();
expect(bridge.newSession).not.toHaveBeenCalled();
expect(bridge.prompt).not.toHaveBeenCalled();

releaseBridge!();
await inbound;

expect(bridge.prompt).toHaveBeenCalledTimes(1);
});

it('waits for bridge recovery after adapter-specific preflight', async () => {
let releaseBridge: (() => void) | undefined;
const bridgeReady = new Promise<void>((resolve) => {
releaseBridge = resolve;
});
const ch = createChannel({}, { bridgeRecovery: () => bridgeReady });

const inbound = ch.processAfterAdapterPreflight(envelope());
await Promise.resolve();
expect(bridge.newSession).not.toHaveBeenCalled();
expect(bridge.prompt).not.toHaveBeenCalled();

releaseBridge!();
await inbound;

expect(bridge.prompt).toHaveBeenCalledTimes(1);
});

it('rechecks bridge recovery after inbound preprocessing has started', async () => {
const recoveryState: { current?: Promise<void> } = {};
let releaseRecovery: (() => void) | undefined;
let releaseContactRecord: (() => void) | undefined;
const contactRecord = new Promise<void>((resolve) => {
releaseContactRecord = resolve;
});
const ch = createChannel(
{},
{
bridgeRecovery: () => recoveryState.current,
observedContacts: {
record: vi.fn().mockImplementation(() => contactRecord),
},
},
);

const inbound = ch.handleInbound(envelope());
await vi.waitFor(() => expect(bridge.newSession).not.toHaveBeenCalled());
recoveryState.current = new Promise<void>((resolve) => {
releaseRecovery = resolve;
});
releaseContactRecord!();
await Promise.resolve();

expect(bridge.newSession).not.toHaveBeenCalled();
expect(bridge.prompt).not.toHaveBeenCalled();

releaseRecovery!();
await inbound;

expect(bridge.prompt).toHaveBeenCalledTimes(1);
});

it('waits for bridge recovery before running a loop prompt', async () => {
let releaseBridge: (() => void) | undefined;
const bridgeReady = new Promise<void>((resolve) => {
releaseBridge = resolve;
});
const ch = createChannel({}, { bridgeRecovery: () => bridgeReady });
ch.proactiveSupported = true;

const loopRun = ch.runLoopPrompt({
id: 'job-recovery-gate',
channelName: 'test-chan',
target: {
channelName: 'test-chan',
senderId: 'alice',
chatId: 'chat-1',
isGroup: false,
},
cwd: '/tmp',
cron: '0 9 * * *',
prompt: 'post summary',
recurring: true,
enabled: true,
createdBy: 'Alice',
createdAt: '2026-06-30T01:00:00.000Z',
consecutiveFailures: 0,
runCount: 0,
});
await Promise.resolve();
expect(bridge.newSession).not.toHaveBeenCalled();
expect(bridge.prompt).not.toHaveBeenCalled();

releaseBridge!();
await expect(loopRun).resolves.toBe('agent response');

expect(bridge.prompt).toHaveBeenCalledTimes(1);
});

it('rechecks bridge recovery before a loop prompt starts', async () => {
const recoveryState: { current?: Promise<void> } = {};
let releaseRecovery: (() => void) | undefined;
let releaseMemoryRead: (() => void) | undefined;
const memoryRead = new Promise<string>((resolve) => {
releaseMemoryRead = () => resolve('');
});
const channelMemory = createChannelMemory();
channelMemory.readChannelMemory.mockReturnValue(memoryRead);
const ch = createChannel(
{},
{ bridgeRecovery: () => recoveryState.current, channelMemory },
);
ch.proactiveSupported = true;

const loopRun = ch.runLoopPrompt({
id: 'job-late-recovery-gate',
channelName: 'test-chan',
target: {
channelName: 'test-chan',
senderId: 'alice',
chatId: 'chat-1',
isGroup: false,
},
cwd: '/tmp',
cron: '0 9 * * *',
prompt: 'post summary',
recurring: true,
enabled: true,
createdBy: 'Alice',
createdAt: '2026-06-30T01:00:00.000Z',
consecutiveFailures: 0,
runCount: 0,
});
await vi.waitFor(() =>
expect(channelMemory.readChannelMemory).toHaveBeenCalledTimes(1),
);
recoveryState.current = new Promise<void>((resolve) => {
releaseRecovery = resolve;
});
releaseMemoryRead!();
await Promise.resolve();

expect(bridge.prompt).not.toHaveBeenCalled();

releaseRecovery!();
await expect(loopRun).resolves.toBe('agent response');

expect(bridge.prompt).toHaveBeenCalledTimes(1);
});

it('runs a loop prompt as a follow-up and pushes the result proactively', async () => {
Expand Down Expand Up @@ -17253,7 +17446,7 @@ describe('ChannelBase', () => {
consecutiveFailures: 0,
runCount: 0,
});
await Promise.resolve();
await new Promise((resolve) => setImmediate(resolve));
expect(bridge.prompt).toHaveBeenCalledOnce();
(
ch as unknown as { sessionGenerations: Map<string, number> }
Expand Down
21 changes: 21 additions & 0 deletions packages/channels/base/src/ChannelBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,8 @@ export interface ChannelBaseOptions {
* events directly.
*/
registerBridgeEvents?: boolean;
/** Return the active bridge recovery barrier, if recovery is in progress. */
bridgeRecovery?: () => Promise<void> | undefined;
groupHistoryPath?: string;
loopController?: ChannelLoopController;
observedContacts?: {
Expand Down Expand Up @@ -379,6 +381,7 @@ export abstract class ChannelBase {
/** Per-session promise chain to serialize prompt + send (followup mode). */
private sessionQueues: Map<string, Promise<void>> = new Map();
private readonly registerBridgeEvents: boolean;
private readonly bridgeRecovery?: () => Promise<void> | undefined;
/**
* Per-session generation, bumped by /clear. A queued followup turn captures the
* generation when it enqueues and bails if /clear bumped it before the turn ran,
Expand Down Expand Up @@ -804,6 +807,7 @@ export abstract class ChannelBase {
);
this.loopController = options?.loopController;
this.observedContacts = options?.observedContacts;
this.bridgeRecovery = options?.bridgeRecovery;

this.groupGate = new GroupGate(config.groupPolicy, config.groups);
this.dmGate = new DmGate(config.dmPolicy);
Expand Down Expand Up @@ -1461,6 +1465,7 @@ export abstract class ChannelBase {
throw new Error(`Loop ${job.id} target is no longer authorized.`);
}

await this.waitForBridgeRecovery();
const sessionId = await this.router.resolve(
this.name,
job.target.senderId,
Expand Down Expand Up @@ -1611,6 +1616,7 @@ export abstract class ChannelBase {
heldChunks.length = 0;
this.onResponseBoundary(job.target.chatId, sessionId);
};
await this.waitForBridgeRecovery();
const promptBridge = this.bridge;
promptBridge.on('textChunk', onChunk);
promptBridge.on('responseBoundary', onResponseBoundary);
Expand Down Expand Up @@ -1778,6 +1784,7 @@ export abstract class ChannelBase {
): Promise<string | undefined> {
const target = this.resolveWebhookTaskTarget(task);

await this.waitForBridgeRecovery();
const sessionId = await this.router.resolve(
this.name,
target.senderId,
Expand Down Expand Up @@ -1906,6 +1913,7 @@ export abstract class ChannelBase {
releaseHeldChunks();
}
};
await this.waitForBridgeRecovery();
const promptBridge = this.bridge;
promptBridge.on('textChunk', onChunk);

Expand Down Expand Up @@ -4904,6 +4912,12 @@ export abstract class ChannelBase {
this.preflightedEnvelopes.add(envelope);
}

/** Wait until the currently active bridge recovery, if any, has completed. */
private async waitForBridgeRecovery(): Promise<void> {
const bridgeRecovery = this.bridgeRecovery?.();
if (bridgeRecovery) await bridgeRecovery;
}

/**
* Process an inbound message after preflight gates have passed.
*
Expand All @@ -4912,6 +4926,7 @@ export abstract class ChannelBase {
* already preflighted, such as during collect-buffer drain.
*/
protected async processInbound(envelope: Envelope): Promise<void> {
await this.waitForBridgeRecovery();
if (!this.preflightedEnvelopes.delete(envelope)) {
throw new Error(
'processInbound called without a successful preflightInbound check.',
Expand Down Expand Up @@ -5002,6 +5017,9 @@ export abstract class ChannelBase {
}
}

// Preprocessing above can await memory/command hooks; recovery may have
// started since the entry check. Recheck immediately before session routing.
await this.waitForBridgeRecovery();
const sessionId = await this.router.resolve(
this.name,
envelope.senderId,
Expand Down Expand Up @@ -5487,6 +5505,9 @@ export abstract class ChannelBase {
);
streamer?.stop();
};
// Queue wait and memory recall can outlive a bridge crash. Capture the
// bridge only after the latest recovery has restored session routing.
await this.waitForBridgeRecovery();
const promptBridge = this.bridge;
promptBridge.on('textChunk', onChunk);
promptBridge.on('responseBoundary', onResponseBoundary);
Expand Down
Loading
Loading