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(desktop): misc independent fixes (vite fetch cap, gateway loading, token animation) (#15541)

Arvin Xuc5c047e4b53b
diff --git a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts
index ee53be75ca8..ecf0182dd88 100644
--- a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts
@@ -286,6 +286,43 @@ export class StaticRendererFallback implements RendererFallbackStrategy {
}
}
+/**
+ * Minimal FIFO semaphore: bounds the number of concurrently-held slots and hands
+ * waiters their turn in arrival order. `acquire()` resolves with an idempotent
+ * release function.
+ */
+class Semaphore {
+ private active = 0;
+ private readonly waiters: Array<() => void> = [];
+
+ constructor(private readonly max: number) {}
+
+ async acquire(): Promise<() => void> {
+ if (this.active >= this.max) {
+ await new Promise<void>((resolve) => this.waiters.push(resolve));
+ }
+ this.active += 1;
+
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ this.active -= 1;
+ this.waiters.shift()?.();
+ };
+ }
+}
+
+/**
+ * Cap on concurrent dev-server fetches. Since #15304 unified dev under `app://`,
+ * every renderer asset round-trips through the main process `net` stack instead
+ * of being fetched straight from Vite by the renderer. A cold start (thousands of
+ * module requests) or a non-default UI language (every i18n namespace fetched
+ * over HTTP, ~50 at once) can otherwise exhaust the net request pool and surface
+ * as `ERR_INSUFFICIENT_RESOURCES`. Bound the in-flight burst instead.
+ */
+const VITE_FETCH_CONCURRENCY = 64;
+
/**
* Development fallback: forward the request to the electron-vite dev server.
* Non-backend `app://renderer/<path>` requests get round-tripped through the
@@ -299,6 +336,7 @@ export class StaticRendererFallback implements RendererFallbackStrategy {
export class ViteRendererFallback implements RendererFallbackStrategy {
private readonly viteOrigin: string;
private readonly logger = createLogger('core:ViteRendererFallback');
+ private readonly gate = new Semaphore(VITE_FETCH_CONCURRENCY);
constructor(viteOrigin: string) {
this.viteOrigin = viteOrigin.replace(/\/+$/, '');
@@ -322,11 +360,39 @@ export class ViteRendererFallback implements RendererFallbackStrategy {
init.duplex = 'half';
}
+ const release = await this.gate.acquire();
try {
- return await net.fetch(target, init);
+ const response = await net.fetch(target, init);
+ // Hold the slot until the body is fully drained (or cancelled) so streaming
+ // responses count against the limit for their whole lifetime, not just until
+ // headers arrive. Bodyless responses release immediately.
+ return this.releaseOnBodyDone(response, release);
} catch (error) {
+ release();
this.logger.error(`Vite dev server fetch failed: ${target}`, error);
return new Response('Vite Dev Server Unavailable', { status: 502 });
}
}
+
+ /**
+ * Wrap the response body in a passthrough that invokes `release` once the stream
+ * closes, errors, or is cancelled downstream — keeping the semaphore slot held
+ * for the request's true lifetime without buffering (so media Range/streaming is
+ * preserved). Returns a new Response carrying the wrapped body.
+ */
+ private releaseOnBodyDone(response: Response, release: () => void): Response {
+ if (!response.body) {
+ release();
+ return response;
+ }
+
+ const passthrough = new TransformStream();
+ void response.body.pipeTo(passthrough.writable).then(release, release);
+
+ return new Response(passthrough.readable, {
+ headers: response.headers,
+ status: response.status,
+ statusText: response.statusText,
+ });
+ }
}
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/Agent.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/Agent.tsx
index 2e37425e77e..18b5fb68223 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/Agent.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/Agent.tsx
@@ -1,5 +1,6 @@
'use client';
+import { AnimatedNumber } from '@lobechat/shared-tool-ui/components';
import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
import { Tooltip } from '@lobehub/ui';
@@ -175,7 +176,11 @@ export const AgentInspector = memo<BuiltinInspectorProps<AgentArgs>>(
{metrics.toolCalls > 0 && metrics.totalTokens > 0 && (
<span className={styles.metricsDot}>·</span>
)}
- {metrics.totalTokens > 0 && <span>{formatTokens(metrics.totalTokens)}</span>}
+ {metrics.totalTokens > 0 && (
+ <span>
+ <AnimatedNumber formatter={formatTokens} value={metrics.totalTokens} />
+ </span>
+ )}
</span>
</Tooltip>
) : null;
diff --git a/packages/shared-tool-ui/src/components/AnimatedNumber.tsx b/packages/shared-tool-ui/src/components/AnimatedNumber.tsx
new file mode 100644
index 00000000000..338bfe99129
--- /dev/null
+++ b/packages/shared-tool-ui/src/components/AnimatedNumber.tsx
@@ -0,0 +1,71 @@
+'use client';
+
+import { memo, useEffect, useRef, useState } from 'react';
+
+interface AnimatedNumberProps {
+ /**
+ * Animation duration in ms.
+ * @default 500
+ */
+ duration?: number;
+ /**
+ * Render the in-flight (possibly fractional) value. Without it the value is
+ * rounded and rendered via `toLocaleString`.
+ */
+ formatter?: (value: number) => string;
+ value: number;
+}
+
+/**
+ * Counts the displayed number up (or down) to `value` whenever it changes,
+ * using `requestAnimationFrame` + easeOutCubic. The first mount snaps to the
+ * initial value (no count-up from zero), so only subsequent updates animate —
+ * e.g. token totals ticking up while a subagent streams.
+ */
+export const AnimatedNumber = memo<AnimatedNumberProps>(({ value, duration = 500, formatter }) => {
+ const [displayValue, setDisplayValue] = useState(value);
+ const frameRef = useRef<number>(undefined);
+ const startTimeRef = useRef<number>(undefined);
+ const startValueRef = useRef(value);
+
+ useEffect(() => {
+ const startValue = startValueRef.current;
+ const diff = value - startValue;
+
+ if (diff === 0) return;
+
+ const animate = (currentTime: number) => {
+ if (!startTimeRef.current) {
+ startTimeRef.current = currentTime;
+ }
+
+ const elapsed = currentTime - startTimeRef.current;
+ const progress = Math.min(elapsed / duration, 1);
+
+ // easeOutCubic
+ const easeProgress = 1 - (1 - progress) ** 3;
+ const current = startValue + diff * easeProgress;
+
+ setDisplayValue(current);
+
+ if (progress < 1) {
+ frameRef.current = requestAnimationFrame(animate);
+ } else {
+ startValueRef.current = value;
+ startTimeRef.current = undefined;
+ }
+ };
+
+ frameRef.current = requestAnimationFrame(animate);
+
+ return () => {
+ if (frameRef.current) {
+ cancelAnimationFrame(frameRef.current);
+ }
+ };
+ }, [value, duration]);
+
+ return formatter ? formatter(displayValue) : Math.round(displayValue).toLocaleString();
+});
+
+AnimatedNumber.displayName = 'AnimatedNumber';
diff --git a/packages/shared-tool-ui/src/components/index.ts b/packages/shared-tool-ui/src/components/index.ts
index cd21dd6b261..3b62ad75a9f 100644
--- a/packages/shared-tool-ui/src/components/index.ts
+++ b/packages/shared-tool-ui/src/components/index.ts
@@ -1,2 +1,3 @@
+export { AnimatedNumber } from './AnimatedNumber';
export { FilePathDisplay } from './FilePathDisplay';
export { ToolResultCard } from './ToolResultCard';
diff --git a/src/features/Electron/titlebar/TabBar/styles.ts b/src/features/Electron/titlebar/TabBar/styles.ts
index 5a78e8e60e6..d5afea02d26 100644
--- a/src/features/Electron/titlebar/TabBar/styles.ts
+++ b/src/features/Electron/titlebar/TabBar/styles.ts
@@ -56,7 +56,7 @@ export const useStyles = createStaticStyles(({ css, cssVar }) => ({
width: 180px;
padding-block: 2px;
- padding-inline-start: 10px;
+ padding-inline: 10px 4px;
border-radius: ${cssVar.borderRadiusSM};
font-size: 12px;
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 173c0ed91d4..2ca6f504ddb 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -705,6 +705,10 @@ export class ConversationLifecycleActionImpl {
message,
metadata: requestMetadata,
parentOperationId: operationId,
+ // Pass temp message IDs so the UI doesn't show a blank loading
+ // state while waiting for the first step_start event to replace
+ // messages with the server's real IDs.
+ tempMessageIds: [tempAssistantId],
});
return {
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index 945055f261e..eab87724db5 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -315,6 +315,13 @@ export class GatewayActionImpl {
* a fresh user prompt.
*/
resumeApproval?: ResumeApprovalParam;
+ /**
+ * Temporary message IDs created during the initial sendMessage phase.
+ * These are associated with the new gateway operation so the UI doesn't
+ * show a blank loading state while waiting for the first `step_start`
+ * event to call `replaceMessages` with the server's real message IDs.
+ */
+ tempMessageIds?: string[];
}): Promise<ExecAgentResult> => {
const {
context,
@@ -325,6 +332,7 @@ export class GatewayActionImpl {
parentMessageId,
parentOperationId,
resumeApproval,
+ tempMessageIds,
} = params;
const agentGatewayUrl =
@@ -450,6 +458,15 @@ export class GatewayActionImpl {
// Associate the server-created assistant message with the gateway operation
this.#get().associateMessageWithOperation(result.assistantMessageId, gatewayOpId);
+ // Also associate temp message IDs so the UI doesn't show a blank loading
+ // state while waiting for the first `step_start` event to call
+ // `replaceMessages` with the server's real message IDs.
+ if (tempMessageIds?.length) {
+ for (const tempId of tempMessageIds) {
+ this.#get().associateMessageWithOperation(tempId, gatewayOpId);
+ }
+ }
+
// Phase-1 init done: child op is running. Hand off loading state from
// the caller's op (e.g. `sendMessage`) to the child without a gap.
if (parentOperationId) this.#get().completeOperation(parentOperationId);