Skip to content

🤯 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.

✨ feat(channel): retry a reply that could not reach its device (#23103)

Arvin Xua580105b479a
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index d76fac4b64f..49145ebec68 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -269,6 +269,12 @@ export const channelRouter = router({
await ctx.channelService.removeThread(input.channelId, input.threadId);
return { success: true };
}),
+ retryJob: channelProcedure
+ .input(z.object({ channelId, jobId: z.uuid() }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.channelService.retryJob(input.channelId, input.jobId);
+ return { success: true };
+ }),
retryRouting: channelProcedure
.input(z.object({ channelId, messageId: z.uuid() }))
.mutation(async ({ ctx, input }) => ({
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index a10906f74c0..a36a2992708 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -408,6 +408,12 @@ export class ChannelService {
return message;
};
+ retryJob = async (channelId: string, jobId: string) => {
+ const job = await this.repository.retryJob(channelId, jobId);
+ await Promise.all([wakeChannel(channelId), this.changed(channelId)]);
+ return job;
+ };
+
stop = async (channelId: string, scope: ChannelStopScope) => {
const writers = await this.repository.stop(channelId, scope);
await new ChannelCoordinator(this.db).stopWriters(writers);
diff --git a/apps/server/src/services/channel/README.md b/apps/server/src/services/channel/README.md
index 700f9aeb7b7..17a95797271 100644
--- a/apps/server/src/services/channel/README.md
+++ b/apps/server/src/services/channel/README.md
@@ -8,7 +8,7 @@ replies never trigger another classification.
## Enable
-Configure a TypeSafe API key through the deployment's \`TYPESAFE_API_KEY\` environment variable,
+Configure a TypeSafe API key through the deployment's \`TYPESAFE\_API\_KEY\` environment variable,
or in the sender's provider settings (workspace provider settings in workspace scope).
Routing is enabled by default. Configure its switch and decision model in Settings → Service Models → Advanced → Channels:
@@ -138,6 +138,8 @@ select that member. Explicit mentions cannot overtake those decisions; unrelated
and other Channels remain independent. A failed, skipped or stopped decision releases the wait.
`channel.retryRouting({ channelId, messageId })` lets the author/admin retry an unassigned message;
sending a new message with an explicit mention remains available.
+`channel.retryJob({ channelId, jobId })` lets the requester/admin re-queue a reply that failed
+because its device could not be reached; it waits for the device like any queued reply.
`routing_decided` audit details record the model/provider, prompt version, scenario, probabilities,
token count, latency, and each member's own rule verdicts (`wakeRules`). No raw provider errors are stored. Runtime hooks still receive
diff --git a/packages/database/src/repositories/channel/README.md b/packages/database/src/repositories/channel/README.md
index 1779e7e01de..949bd47391e 100644
--- a/packages/database/src/repositories/channel/README.md
+++ b/packages/database/src/repositories/channel/README.md
@@ -201,6 +201,9 @@ all-candidate fallback. Stopping a reply still fences it; root completion never
Operation completion is not proof that a device process ended. Only `releaseWriter` after
confirmed termination, or `retireReservation` for an untouched operation, releases the writer.
Isolation frees the member but keeps the device/directory lock. Never retry an unknown delivery.
+ `retryJob` re-queues only a failed job whose device could not be reached
+ (`DeviceGatewayNotConfigured`), with its writer released and nothing accepted or published;
+ the next claim opens a fresh operation.
- A job blocked only by another writer in its member's directory moves its conversation branch
(a Thread, or the main timeline) into a git worktree instead of waiting: the coordinator asks
the device to cut `lobe-channel/<member>-<branch>` from that directory's HEAD under
diff --git a/packages/database/src/repositories/channel/__tests__/retryJob.test.ts b/packages/database/src/repositories/channel/__tests__/retryJob.test.ts
new file mode 100644
index 00000000000..113ac8f8f59
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/retryJob.test.ts
@@ -0,0 +1,99 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agentOperations, channelJobs } from '../../../schemas';
+import { ChannelExecutionRepository } from '..';
+import { createChannelFixture, jobsOf, lease } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-retry-job');
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+const execution = new ChannelExecutionRepository(db);
+
+/** A reply claimed and failed with `error`; `released` settles its writer as a stop would. */
+const failedReply = async (
+ error: Record<string, unknown>,
+ { released = true, sender = 'owner' }: { released?: boolean; sender?: 'member' | 'owner' } = {},
+) => {
+ const team = await fixture.createTeamChannel();
+ await fixture.addAgent(team.channel.id, 'Device Agent');
+ const message = await (sender === 'owner' ? team.asOwner : team.asMember).send(team.channel.id, {
+ content: 'hi',
+ requestKey: `retry-${sender}`,
+ routing: 'fallback',
+ });
+ const [job] = await jobsOf(db, message.id);
+ await execution.claim(team.channel.id, job.id, lease);
+ const [claimed] = await db.select().from(channelJobs).where(eq(channelJobs.id, job.id));
+ await db
+ .update(agentOperations)
+ .set({ error, status: 'error' })
+ .where(eq(agentOperations.id, claimed.operationId!));
+ await execution.fail(team.channel.id, job.id, { message: 'Agent could not start' });
+ if (released) await execution.releaseWriter(team.channel.id, job.id);
+ return { ...team, failed: claimed };
+};
+
+const deviceUnreachable = {
+ deviceRoute: { deviceId: 'device-1' },
+ message: 'The device this agent runs on is offline',
+ type: 'DeviceGatewayNotConfigured',
+};
+
+describe('Retrying a reply that could not reach its device', () => {
+ it('queues the same delivery again, and a new claim runs it on a fresh operation', async () => {
+ const { asOwner, channel, failed } = await failedReply(deviceUnreachable);
+
+ const retried = await asOwner.retryJob(channel.id, failed.id);
+ expect(retried).toMatchObject({
+ id: failed.id,
+ operationId: null,
+ publicationRevoked: false,
+ status: 'queued',
+ writerHeld: false,
+ });
+ expect((await asOwner.detail(channel.id)).jobs[0]).toMatchObject({
+ errorType: null,
+ status: 'queued',
+ });
+
+ const claim = await execution.claim(channel.id, failed.id, lease);
+ expect(claim?.job.status).toBe('running');
+ expect(claim?.job.operationId).not.toBe(failed.operationId);
+ });
+
+ it('lets the requester retry their own reply but no other member', async () => {
+ const own = await failedReply(deviceUnreachable, { sender: 'member' });
+ await expect(own.asMember.retryJob(own.channel.id, own.failed.id)).resolves.toMatchObject({
+ status: 'queued',
+ });
+ await fixture.cleanup();
+ await fixture.setup();
+
+ const other = await failedReply(deviceUnreachable);
+ await expect(other.asMember.retryJob(other.channel.id, other.failed.id)).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ });
+
+ it('refuses a reply that failed for another reason, since it may have run', async () => {
+ const { asOwner, channel, failed } = await failedReply({
+ message: 'Unsupported model',
+ type: 'ProviderBizError',
+ });
+ await expect(asOwner.retryJob(channel.id, failed.id)).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ });
+
+ it('refuses a reply whose writer has not been released yet', async () => {
+ const { asOwner, channel, failed } = await failedReply(deviceUnreachable, { released: false });
+ await expect(asOwner.retryJob(channel.id, failed.id)).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ });
+});
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index 3d2f00b8fd1..4010f11d6c8 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -35,6 +35,7 @@ import { lockPeerPair, peerOf, requireMutualContacts } from './peer';
import { addChannelUser, channelUserCandidates, newChannelUserCandidates } from './people';
import type { ChannelAgentPostInput } from './post';
import { postAgentMessage } from './post';
+import { retryJob } from './retry';
import { retryRouting } from './routing';
import type { ChannelSendInput } from './send';
import { sendMessage } from './send';
@@ -927,6 +928,23 @@ export class ChannelRepository {
return retryRouting(tx, channelId, messageId);
});
+ /**
+ * Queues a reply that could not reach its device again. Like a stop, only its requester or an
+ * admin may retry it.
+ */
+ retryJob = async (channelId: string, jobId: string): Promise<ChannelJobItem> =>
+ this.write(channelId, async (tx, { member }) => {
+ if (!hasRole(member.role, 'admin')) {
+ const [job] = await tx
+ .select({ requesterMemberId: channelJobs.requesterMemberId })
+ .from(channelJobs)
+ .where(and(eq(channelJobs.channelId, channelId), eq(channelJobs.id, jobId)));
+ if (job && job.requesterMemberId !== member.id)
+ throw new ChannelError('FORBIDDEN', 'Only the requester or an admin can retry this job');
+ }
+ return retryJob(tx, channelId, jobId);
+ });
+
private addOwner = async (tx: Transaction, channelId: string) => {
const [member] = await tx
.insert(channelMembers)
diff --git a/packages/database/src/repositories/channel/retry.ts b/packages/database/src/repositories/channel/retry.ts
new file mode 100644
index 00000000000..4463181a9b0
--- /dev/null
+++ b/packages/database/src/repositories/channel/retry.ts
@@ -0,0 +1,72 @@
+import { and, eq, sql } from 'drizzle-orm';
+
+import type { ChannelJobItem } from '../../schemas';
+import { agentOperations, channelJobs } from '../../schemas';
+import type { Transaction } from '../../type';
+import { assertThreadOpen, findThread } from './delivery';
+import { ChannelError } from './error';
+import { audit } from './transaction';
+
+/** The operation error type of a run whose device could not be reached. */
+const DEVICE_UNREACHABLE = 'DeviceGatewayNotConfigured';
+
+/**
+ * Queues a reply that failed before it started again. Only a reply whose device could not be
+ * reached qualifies, and only once its writer is released: nothing ran, nothing was accepted
+ * or published, so running it again cannot repeat work. Deliveries are unique per message and
+ * member, so the job itself goes back to the queue, keeping its place in message order. The
+ * next claim reads the Agent's current settings and environment and opens a fresh operation;
+ * the failed one stays on its topic as history.
+ */
+export const retryJob = async (
+ tx: Transaction,
+ channelId: string,
+ jobId: string,
+): Promise<ChannelJobItem> => {
+ const [row] = await tx
+ .select({ errorType: sql<string | null>`${agentOperations.error}->>'type'`, job: channelJobs })
+ .from(channelJobs)
+ .leftJoin(agentOperations, eq(agentOperations.id, channelJobs.operationId))
+ .where(and(eq(channelJobs.channelId, channelId), eq(channelJobs.id, jobId)));
+ if (!row) throw new ChannelError('NOT_FOUND', 'Job not found');
+ const { errorType, job } = row;
+ assertThreadOpen(await findThread(tx, channelId, job.threadId));
+ if (
+ job.status !== 'failed' ||
+ errorType !== DEVICE_UNREACHABLE ||
+ job.acceptedAt ||
+ job.draft !== null ||
+ job.publishedMessageId
+ )
+ throw new ChannelError(
+ 'CONFLICT',
+ 'Only a reply that could not reach its device can be retried',
+ );
+ if (job.writerHeld)
+ throw new ChannelError('CONFLICT', 'The failed reply is still being released');
+
+ const [retried] = await tx
+ .update(channelJobs)
+ .set({
+ acceptedAt: null,
+ blockedCode: null,
+ blockedReason: null,
+ claimedAt: null,
+ deviceId: null,
+ executionConfig: null,
+ isolatedAt: null,
+ leaseExpiresAt: null,
+ leaseOwner: null,
+ manifest: null,
+ operationId: null,
+ publicationRevoked: false,
+ status: 'queued',
+ topicId: null,
+ workingDirectory: null,
+ })
+ .where(eq(channelJobs.id, job.id))
+ .returning();
+ await audit(tx, channelId, 'job_retried', job.id, { operationId: job.operationId });
+
+ return retried;
+};