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.

♻️ refactor: drop redundant type guards on typed data (#17134)

YuTengjingb7d0f109bcf5
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts
index 6bc30e2a0db..43f863bc02f 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerSubAgentTransport.ts
@@ -4,7 +4,6 @@ import type {
ExecSubAgentResult,
ExecVirtualSubAgentParams,
} from '@lobechat/types';
-import { pickString, toRecord } from '@lobechat/utils/object';
import type { RuntimeExecutorContext } from '../context';
@@ -16,26 +15,6 @@ const fallbackResult = (error: string): ExecSubAgentResult => ({
threadId: '',
});
-const normalizeResult = (value: unknown): ExecSubAgentResult => {
- const result = toRecord(value);
- if (!result) {
- return {
- assistantMessageId: '',
- operationId: '',
- success: true,
- threadId: '',
- };
- }
-
- return {
- assistantMessageId: pickString(result.assistantMessageId) ?? '',
- error: pickString(result.error),
- operationId: pickString(result.operationId) ?? '',
- success: result.success !== false,
- threadId: pickString(result.threadId) ?? '',
- };
-};
-
/**
* Server {@link SubAgentTransport} adapter — delegates child-run creation to
* callbacks injected by AiAgentService while the package owns executor flow.
@@ -46,7 +25,7 @@ export class ServerSubAgentTransport implements SubAgentTransport {
async execSubAgent(params: ExecSubAgentParams): Promise<ExecSubAgentResult> {
if (!this.ctx.execSubAgent) return fallbackResult('Sub-agent dispatch is not available.');
- return normalizeResult(await this.ctx.execSubAgent(params));
+ return this.ctx.execSubAgent(params);
}
async execVirtualSubAgent(params: ExecVirtualSubAgentParams): Promise<ExecSubAgentResult> {
@@ -54,6 +33,6 @@ export class ServerSubAgentTransport implements SubAgentTransport {
return fallbackResult('Virtual sub-agent dispatch is not available.');
}
- return normalizeResult(await this.ctx.execVirtualSubAgent(params));
+ return this.ctx.execVirtualSubAgent(params);
}
}
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.ts
index c8869e4267d..8ed6ba0cd8d 100644
--- a/apps/server/src/modules/AgentRuntime/context.ts
+++ b/apps/server/src/modules/AgentRuntime/context.ts
@@ -1,6 +1,10 @@
import { type AgentState } from '@lobechat/agent-runtime';
import { type BotPlatformContext } from '@lobechat/context-engine';
-import { type ExecSubAgentParams, type ExecVirtualSubAgentParams } from '@lobechat/types';
+import {
+ type ExecSubAgentParams,
+ type ExecSubAgentResult,
+ type ExecVirtualSubAgentParams,
+} from '@lobechat/types';
import { type MessageModel } from '@/database/models/message';
import { type LobeChatDatabase } from '@/database/type';
@@ -38,13 +42,13 @@ export interface RuntimeExecutorContext {
* Injected by AiAgentService so exec_sub_agent / exec_sub_agents executors
* can dispatch callAgent-triggered runs without a circular import.
*/
- execSubAgent?: (params: ExecSubAgentParams) => Promise<unknown>;
+ execSubAgent?: (params: ExecSubAgentParams) => Promise<ExecSubAgentResult>;
/**
* Callback to fork a `lobe-agent.callSubAgent` virtual child run. Unlike
* execSubAgent, this path installs the async completion bridge and marks the
* child operation as a sub-agent.
*/
- execVirtualSubAgent?: (params: ExecVirtualSubAgentParams) => Promise<unknown>;
+ execVirtualSubAgent?: (params: ExecVirtualSubAgentParams) => Promise<ExecSubAgentResult>;
hookDispatcher?: HookDispatcher;
loadAgentState?: (operationId: string) => Promise<AgentState | null>;
messageModel: MessageModel;
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 930914c4064..435fa185b2d 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -32,6 +32,7 @@ import {
import {
type ChatToolPayload,
type ExecSubAgentParams,
+ type ExecSubAgentResult,
type ExecVirtualSubAgentParams,
type UIChatMessage,
} from '@lobechat/types';
@@ -202,13 +203,13 @@ export interface AgentRuntimeDelegate {
* (AiAgentService.execSubAgent → execAgent: agent-config resolution, tool
* engine, context engineering, createOperation).
*/
- execSubAgent?: (params: ExecSubAgentParams) => Promise<unknown>;
+ execSubAgent?: (params: ExecSubAgentParams) => Promise<ExecSubAgentResult>;
/**
* Fork a `lobe-agent.callSubAgent` virtual child run. The child is marked as a
* sub-agent and owns the completion bridge that backfills the parent tool
* placeholder before resuming the parked parent operation.
*/
- execVirtualSubAgent?: (params: ExecVirtualSubAgentParams) => Promise<unknown>;
+ execVirtualSubAgent?: (params: ExecVirtualSubAgentParams) => Promise<ExecSubAgentResult>;
}
export interface AgentRuntimeServiceOptions {
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts
index 14d6474b1d4..f0b2a6f0a06 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts
@@ -1,5 +1,4 @@
import type { BriefAction } from '@lobechat/types';
-import { isTrimmedNonEmptyString } from '@lobechat/utils';
import { z } from 'zod';
import type {
@@ -161,8 +160,7 @@ export type NonMergeableSelfReviewProposalActionPlan = ActionPlan & {
* Snapshot-aware action accepted by proposal metadata projection.
*/
export type SelfReviewProposalActionPlan =
- | MergeableSelfReviewProposalActionPlan
- | NonMergeableSelfReviewProposalActionPlan;
+ MergeableSelfReviewProposalActionPlan | NonMergeableSelfReviewProposalActionPlan;
/**
* Snapshot-aware self-iteration plan accepted by proposal metadata projection.
@@ -322,16 +320,16 @@ const hasCompleteMergeableSnapshot = (
if (actionType === 'refine_skill') {
return (
- isTrimmedNonEmptyString(snapshot.agentDocumentId) &&
- isTrimmedNonEmptyString(snapshot.documentId) &&
- isTrimmedNonEmptyString(snapshot.contentHash) &&
+ !!snapshot.agentDocumentId?.trim() &&
+ !!snapshot.documentId?.trim() &&
+ !!snapshot.contentHash?.trim() &&
snapshot.managed === true &&
snapshot.writable === true
);
}
if (actionType === 'create_skill') {
- return snapshot.absent === true && isTrimmedNonEmptyString(snapshot.skillName);
+ return snapshot.absent === true && !!snapshot.skillName?.trim();
}
return false;
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 876117b945e..5239a4359b2 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -69,7 +69,6 @@ import {
ThreadType,
} from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
-import { isRecord } from '@lobechat/utils/object';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
@@ -173,9 +172,7 @@ const createGraphAwareAgentFactory =
return upstreamFactory(config);
}
- const runtimeAgentConfig = isRecord(config.agentConfig)
- ? (config.agentConfig as LobeAgentConfig)
- : undefined;
+ const runtimeAgentConfig = config.agentConfig as LobeAgentConfig | undefined;
const graph = runtimeAgentConfig?.chatConfig?.graph;
if (runtimeAgentConfig?.chatConfig?.enableGraphMode && graph) {
const graphResult = ReasoningGraphSchema.safeParse(graph);
diff --git a/packages/model-runtime/src/core/usageConverters/openai.ts b/packages/model-runtime/src/core/usageConverters/openai.ts
index 7d6d083892b..41a52baa1ec 100644
--- a/packages/model-runtime/src/core/usageConverters/openai.ts
+++ b/packages/model-runtime/src/core/usageConverters/openai.ts
@@ -1,5 +1,4 @@
import type { ModelTokensUsage, ModelUsage } from '@lobechat/types';
-import { isRecord } from '@lobechat/utils/object';
import debug from 'debug';
import type { Pricing } from 'model-bank';
import type OpenAI from 'openai';
@@ -23,17 +22,25 @@ const shouldKeepUsageValue = (key: string, value: unknown) => {
};
/**
- * OpenAI GPT-5.6+ reports cache writes as `cache_write_tokens` under usage details.
- * The field is not yet in all openai SDK type snapshots, so read it defensively.
- *
+ * OpenAI GPT-5.6+ reports cache writes as `cache_write_tokens` under usage details,
+ * a field not yet present in the openai SDK type snapshots — extend the SDK detail
+ * shapes locally until the SDK catches up.
+ */
+type CacheWriteUsageDetails =
+ | (NonNullable<OpenAI.Completions.CompletionUsage['prompt_tokens_details']> & {
+ cache_write_tokens?: number;
+ })
+ | (NonNullable<OpenAI.Responses.ResponseUsage['input_tokens_details']> & {
+ cache_write_tokens?: number;
+ });
+
+/**
* Billing note: write tokens are a subset of total input tokens and are charged at
* 1.25× uncached input. They must be excluded from the uncached (1×) miss bucket so
* computeChatCost does not double-charge textInput + textInput_cacheWrite.
*/
-const readCacheWriteTokens = (details: unknown): number | undefined => {
- if (!isRecord(details)) return undefined;
-
- const value = details.cache_write_tokens;
+const readCacheWriteTokens = (details: CacheWriteUsageDetails | undefined): number | undefined => {
+ const value = details?.cache_write_tokens;
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
};
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
index 618ad7a2cbd..48856b32753 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
@@ -3,7 +3,6 @@
import { isDesktop } from '@lobechat/const';
import type { WorkingDirEntry } from '@lobechat/types';
import { getWorkingDirSourcePath } from '@lobechat/types';
-import { isRecord } from '@lobechat/utils';
import { ActionIcon, Flexbox, Icon, Input, Popover, Tooltip } from '@lobehub/ui';
import { toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
@@ -193,8 +192,8 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const isValidWorkingDirEntry = (entry: unknown): entry is WorkingDirEntry =>
- isRecord(entry) && !!getWorkingDirectoryPathString(entry.path);
+const isValidWorkingDirEntry = (entry: WorkingDirEntry): boolean =>
+ !!getWorkingDirectoryPathString(entry.path);
type FolderEntry = { path: string; repoType?: 'git' | 'github' };
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
index a56f9789ebe..fed25c6caed 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
@@ -1,8 +1,8 @@
'use client';
import { isDesktop } from '@lobechat/const';
+import type { WorkingDirEntry } from '@lobechat/types';
import { getWorkingDirEffectivePath } from '@lobechat/types';
-import { isRecord } from '@lobechat/utils';
import { memo } from 'react';
import SafeBoundary from '@/components/ErrorBoundary';
@@ -24,12 +24,9 @@ interface WorkingDirectorySectionProps {
agentId: string;
}
-const getEntryEffectivePath = (entry: unknown) => {
- if (!isRecord(entry)) return;
-
+const getEntryEffectivePath = (entry: WorkingDirEntry) => {
const sourcePath = getWorkingDirectoryPathString(entry.path);
- const git = isRecord(entry.git) ? entry.git : undefined;
- return getWorkingDirectoryPathString(git?.activeWorktree) ?? sourcePath;
+ return getWorkingDirectoryPathString(entry.git?.activeWorktree) ?? sourcePath;
};
/**
@@ -81,7 +78,7 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent
// WorktreeSwitcher commits `sourcePath` as the WorkingDirEntry.path, rewriting
// the topic's repo source to the linked worktree and breaking later switches.
const sourceWorkingDirectory =
- (isRecord(currentEntry) ? getWorkingDirectoryPathString(currentEntry.path) : undefined) ??
+ getWorkingDirectoryPathString(currentEntry?.path) ??
getWorkingDirectoryPathString(persistedConfig?.path) ??
effectiveWorkingDirectory;
diff --git a/src/features/Conversation/Error/PlanLimitCard/budget.ts b/src/features/Conversation/Error/PlanLimitCard/budget.ts
index 45c8c85ad72..11bfb22a4e6 100644
--- a/src/features/Conversation/Error/PlanLimitCard/budget.ts
+++ b/src/features/Conversation/Error/PlanLimitCard/budget.ts
@@ -1,5 +1,4 @@
import { Plans } from '@lobechat/types';
-import { isRecord } from '@lobechat/utils';
export type PlanLimitPricingBasis = 'approximate' | 'estimated' | 'exact' | 'unknown';
@@ -19,12 +18,8 @@ export interface PlanLimitBudgetContext {
export const getBudgetContextFromErrorBody = (
body: unknown,
): PlanLimitBudgetContext | undefined => {
- if (!isRecord(body)) return undefined;
-
- const { budget } = body as { budget?: unknown };
- if (!isRecord(budget)) return undefined;
-
- return budget as PlanLimitBudgetContext;
+ const budget = (body as { budget?: PlanLimitBudgetContext } | null | undefined)?.budget;
+ return budget && typeof budget === 'object' ? budget : undefined;
};
const PLAN_VALUES = new Set<string>(Object.values(Plans));
diff --git a/src/helpers/workingDirectoryPath.ts b/src/helpers/workingDirectoryPath.ts
index f8896b3ae6c..c12e104fa1a 100644
--- a/src/helpers/workingDirectoryPath.ts
+++ b/src/helpers/workingDirectoryPath.ts
@@ -1,5 +1,4 @@
import type { WorkingDirConfig, WorkingDirRepoType } from '@lobechat/types';
-import { pickString } from '@lobechat/utils';
import { isDesktop } from '@/const/version';
@@ -23,14 +22,14 @@ export const getConfigRepoType = (config?: WorkingDirConfig): WorkingDirRepoType
return config.repoType ?? (isDesktop ? undefined : 'github');
};
-export const getWorkingDirectoryPathString = (path: unknown) => {
- const value = pickString(path)?.trim();
+export const getWorkingDirectoryPathString = (path?: string | null) => {
+ const value = path?.trim();
return value || undefined;
};
// Last non-empty path segment — the folder name. Also yields the repo name for
// a web github URL (".../owner/repo" -> "repo").
-export const getWorkingDirectoryName = (path: unknown) => {
+export const getWorkingDirectoryName = (path?: string | null) => {
const value = getWorkingDirectoryPathString(path);
if (!value) return;
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index f221c8b16a2..4aee9430822 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -91,10 +91,13 @@ const currentTopicWorkingDirectory = (s: ChatStoreState): string | undefined =>
const activeTopic = currentActiveTopic(s);
if (!activeTopic) return;
+ // Route the raw `workingDirectory` through the extractor too: it is typed as a
+ // string, but a malformed legacy topic may have persisted a `WorkingDirConfig`
+ // object into it (see #17050 and `getTopicMetadataWorkingDirectorySourcePath`),
+ // and this selector's declared `string | undefined` must hold at runtime.
if (isDesktop) {
- return (
- getWorkingDirEffectivePath(activeTopic.metadata?.workingDirectoryConfig) ??
- activeTopic.metadata?.workingDirectory
+ return getWorkingDirEffectivePath(
+ activeTopic.metadata?.workingDirectoryConfig ?? activeTopic.metadata?.workingDirectory,
);
}
@@ -102,8 +105,7 @@ const currentTopicWorkingDirectory = (s: ChatStoreState): string | undefined =>
const meta = activeTopic.metadata;
return (
meta?.repos?.[0] ??
- getWorkingDirEffectivePath(meta?.workingDirectoryConfig) ??
- meta?.workingDirectory
+ getWorkingDirEffectivePath(meta?.workingDirectoryConfig ?? meta?.workingDirectory)
);
};