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.

🐛 fix: preserve request context in structured generation (#20515)

YuTengjing6aaeeeee6af4
diff --git a/.agents/skills/deep-review/references/dimensions/ai-coding-bad-habits.md b/.agents/skills/deep-review/references/dimensions/ai-coding-bad-habits.md
index 40c57674a4a..a1c87808bf1 100644
--- a/.agents/skills/deep-review/references/dimensions/ai-coding-bad-habits.md
+++ b/.agents/skills/deep-review/references/dimensions/ai-coding-bad-habits.md
@@ -27,6 +27,12 @@ seam), report it there instead; never emit the same finding twice.
extend. Pay special attention to one-off helpers that hide a single narrow branch at a generic
property such as `type`, `status`, or `mode`; keep variant policy in its owning layer or make the
exceptional condition explicit at the decision point.
+- **Patch instead of a necessary local refactor**: a change appends positional parameters, flags,
+ branches, or wrappers to preserve the old shape even though the new requirement exposes its
+ limitations. A smaller diff is not sufficient justification: identify concrete ambiguity,
+ duplicated policy, or coupled call sites, then prefer the smallest coherent refactor of the
+ affected interface and callers. Do not use this rule to demand unrelated cleanup or break a
+ released contract.
- **Partial refactor**: a renamed concept leaves stale filenames, tests, exports, docs, or adjacent
identifiers; a compatibility alias, forwarding wrapper, or `const newName = oldName` remains even
though no caller needs it. Complete the semantic rename across the affected unit, following the
@@ -64,6 +70,19 @@ type: getBlockErrorType(finishReason);
only hides one image-generation condition. Keep the condition explicit at the decision point when
that is clearest, or move the policy into the image/provider adapter that owns it.
+### Extending a positional interface instead of clarifying it
+
+```ts
+// Adding request context to an internal service:
+new FollowUpActionService(db, userId, undefined, userAgent);
+```
+
+Appending another optional positional parameter makes callers depend on argument order and
+placeholder values. When these internal callers can migrate together, use a typed options object
+such as `new FollowUpActionService({ db, userId, userAgent })` and update them together. Judge the
+actual call-site ambiguity and compatibility boundary, not a universal parameter-count threshold;
+do not turn a local refactor into a redesign of the service or its public APIs.
+
### Rename that stops at the exported symbol
```ts
@@ -133,7 +152,9 @@ Run five focused passes:
1. **Scope locality**: name each new condition/helper and ask whether its vocabulary is narrower than
the file or abstraction containing it. Trace the pipeline and existing extension seams before
deciding the code belongs elsewhere. A narrow report does not prove the root cause is narrow.
-2. **Refactor closure**: for renamed concepts, search both old and new names across symbols,
+2. **Refactor closure**: first check whether an additive patch avoids a necessary local interface
+ change solely to minimize the diff; trace affected callers and compatibility constraints. For
+ renamed concepts, search both old and new names across symbols,
filenames, exports, tests, docs, and import paths. Search every alias/wrapper for callers. Keep a
compatibility shim only when a released caller or staged migration needs it, and require a
deprecation/removal story.
diff --git a/.agents/skills/typescript/SKILL.md b/.agents/skills/typescript/SKILL.md
index 95a0dc4c1e2..87785557458 100644
--- a/.agents/skills/typescript/SKILL.md
+++ b/.agents/skills/typescript/SKILL.md
@@ -21,7 +21,7 @@ user-invocable: false
## Async Patterns
-- **Async-first for IO**: new IO code (fs, child\_process, etc.) must use async APIs at its boundaries — use promise-based variants like `import { readFile } from 'fs/promises'`, never `*Sync` by default. Function coloring is asymmetric: async→sync migration is never needed, while sync→async (when IO gets slower, gains concurrency, or grows a subprocess/network call) forces rewriting every caller up the chain — sync-first debt that compounds. Micro-costs of async (thread-pool dispatch, cache races) are not valid reasons: races are solved by caching the promise instead of the result
+- **Async-first for IO**: new IO code (fs, child_process, etc.) must use async APIs at its boundaries — use promise-based variants like `import { readFile } from 'fs/promises'`, never `*Sync` by default. Function coloring is asymmetric: async→sync migration is never needed, while sync→async (when IO gets slower, gains concurrency, or grows a subprocess/network call) forces rewriting every caller up the chain — sync-first debt that compounds. Micro-costs of async (thread-pool dispatch, cache races) are not valid reasons: races are solved by caching the promise instead of the result
- `*Sync` is acceptable in exactly one place: call sites locked inside a synchronous contract you don't control — an existing sync signature chain (don't virally refactor a legacy sync chain in a bugfix, but new standalone modules must not extend such chains), or sync-only callbacks like `process.on('exit')`. Module-load-time and CLI startup init are NOT exceptions — use top-level `await` (ESM) there
## Imports
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
index 3165cacba46..10c1dfcc2b1 100644
--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
@@ -1570,6 +1570,37 @@ describe('aiChatRouter', () => {
);
});
+ it.each([undefined, 'Mozilla/5.0', 'LobeHub-Mobile/ios-v1.0.5'])(
+ 'preserves extensible metadata and uses request UA %s',
+ async (userAgent) => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const generateObject = vi.fn().mockResolvedValue({ completion: 'ok' });
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ generateObject } as any);
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {}, userAgent } as any);
+
+ await caller.outputJSON({
+ messages: [],
+ metadata: {
+ correlationId: 'cid-1',
+ privateOption: true,
+ topicId: 'topic-1',
+ trigger: 'custom_feature',
+ userAgent: 'LobeHub-Mobile/android-v1.0.5',
+ },
+ model: 'test-model',
+ provider: 'test-provider',
+ });
+
+ expect(generateObject.mock.calls[0][1].metadata).toEqual({
+ correlationId: 'cid-1',
+ privateOption: true,
+ topicId: 'topic-1',
+ trigger: 'custom_feature',
+ userAgent,
+ });
+ },
+ );
+
it('merges caller metadata over the default trigger and forwards tracing', async () => {
const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
const mockGenerateObject = vi.fn().mockResolvedValue({ completion: 'hi there' });
diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.ts
index 8f9c55e1858..38eef89cfec 100644
--- a/apps/server/src/routers/lambda/aiChat.ts
+++ b/apps/server/src/routers/lambda/aiChat.ts
@@ -172,7 +172,12 @@ export const aiChatRouter = router({
tools: input.tools,
},
{
- metadata: { trigger: RequestTrigger.Chat, ...input.metadata },
+ metadata: {
+ trigger: RequestTrigger.Chat,
+ ...input.metadata,
+ // Preserve extensible metadata while using the originating request's UA.
+ userAgent: ctx.userAgent,
+ },
tracing: { ...input.tracing, tracingId },
},
);
diff --git a/apps/server/src/routers/lambda/followUpAction.ts b/apps/server/src/routers/lambda/followUpAction.ts
index 87055092854..0a1d54e5ce0 100644
--- a/apps/server/src/routers/lambda/followUpAction.ts
+++ b/apps/server/src/routers/lambda/followUpAction.ts
@@ -8,10 +8,14 @@ import { FollowUpActionService } from '@/server/services/followUpAction';
const followUpProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
- const wsId = ctx.workspaceId ?? undefined;
return opts.next({
ctx: {
- followUpService: new FollowUpActionService(ctx.serverDB, ctx.userId, wsId),
+ followUpService: new FollowUpActionService({
+ db: ctx.serverDB,
+ userAgent: ctx.userAgent,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ }),
},
});
});
diff --git a/apps/server/src/services/followUpAction/index.test.ts b/apps/server/src/services/followUpAction/index.test.ts
index aae2238bffb..fb098a01d4c 100644
--- a/apps/server/src/services/followUpAction/index.test.ts
+++ b/apps/server/src/services/followUpAction/index.test.ts
@@ -2,6 +2,7 @@
import { ModelRuntime } from '@lobechat/model-runtime';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as DatabaseModule from '@/database/core/db-adaptor';
import { notShareVisitorMessage } from '@/database/utils/shareVisitor';
import * as ModelRuntimeModule from '@/server/modules/ModelRuntime';
import * as TracingServiceModule from '@/server/services/llmGenerationTracing';
@@ -35,7 +36,7 @@ describe('FollowUpActionService.extract', () => {
runtimeMock = { generateObject: vi.fn() };
vi.spyOn(ModelRuntimeModule, 'initModelRuntimeFromDB').mockResolvedValue(runtimeMock as any);
- svc = new FollowUpActionService(dbMock, TEST_USER);
+ svc = new FollowUpActionService({ db: dbMock, userId: TEST_USER });
});
afterEach(() => {
@@ -43,6 +44,27 @@ describe('FollowUpActionService.extract', () => {
vi.unstubAllGlobals();
});
+ it('preserves the originating mobile request through the router and service', async () => {
+ const { followUpActionRouter } = await import('@/server/routers/lambda/followUpAction');
+ const userAgent = 'LobeHub-Mobile/ios-v1.0.5';
+ queryFindFirstSpy.mockResolvedValue({ id: FOUND_MSG, content: 'Choose a next step.' });
+ runtimeMock.generateObject.mockImplementation(async (_payload, options) => {
+ if (options.metadata.userAgent !== userAgent) throw new Error('Missing request identity');
+ return { chips: [{ label: 'Continue', message: 'Continue please' }] };
+ });
+ vi.spyOn(DatabaseModule, 'getServerDB').mockResolvedValue(dbMock);
+ const caller = followUpActionRouter.createCaller({
+ serverDB: dbMock,
+ userAgent,
+ userId: TEST_USER,
+ } as any);
+
+ expect(await caller.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC })).toMatchObject({
+ chips: [{ label: 'Continue', message: 'Continue please' }],
+ messageId: FOUND_MSG,
+ });
+ });
+
it('reuses the source topic in outgoing OpenCode requests across extractions', async () => {
const sessions: (string | null)[] = [];
queryFindFirstSpy.mockResolvedValue({ id: FOUND_MSG, content: 'Choose a next step.' });
@@ -272,7 +294,7 @@ describe('FollowUpActionService.extract', () => {
});
it('filters workspace mode by workspaceId and forwards it to model runtime', async () => {
- svc = new FollowUpActionService(dbMock, TEST_USER, 'workspace-1');
+ svc = new FollowUpActionService({ db: dbMock, userId: TEST_USER, workspaceId: 'workspace-1' });
queryFindFirstSpy.mockResolvedValue({ id: FOUND_MSG, content: 'q?' });
runtimeMock.generateObject.mockResolvedValue({ chips: [] });
diff --git a/apps/server/src/services/followUpAction/index.ts b/apps/server/src/services/followUpAction/index.ts
index ed04c7150fd..2a768edfb71 100644
--- a/apps/server/src/services/followUpAction/index.ts
+++ b/apps/server/src/services/followUpAction/index.ts
@@ -22,15 +22,24 @@ const log = debug('lobe-server:follow-up-action-service');
const EMPTY_RESULT = (messageId: string): FollowUpExtractResult => ({ chips: [], messageId });
+interface FollowUpActionServiceOptions {
+ db: LobeChatDatabase;
+ userAgent?: string;
+ userId: string;
+ workspaceId?: string;
+}
+
export class FollowUpActionService {
private readonly db: LobeChatDatabase;
private readonly userId: string;
private readonly workspaceId?: string;
+ private readonly userAgent?: string;
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ constructor({ db, userAgent, userId, workspaceId }: FollowUpActionServiceOptions) {
this.db = db;
this.userId = userId;
this.workspaceId = workspaceId;
+ this.userAgent = userAgent;
}
async extract({
@@ -92,7 +101,8 @@ export class FollowUpActionService {
schema: FOLLOW_UP_JSON_SCHEMA,
},
{
- metadata: { topicId, trigger: RequestTrigger.FollowUp },
+ // Keep the originating request identity for downstream model hooks.
+ metadata: { topicId, trigger: RequestTrigger.FollowUp, userAgent: this.userAgent },
tracing: {
promptVersion: FOLLOW_UP_PROMPT_VERSION,
scenario: TRACING_SCENARIOS.FollowUp,