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.

⚑️ perf(agent): stop re-asking the device and the Market for answers that do not change per send (#20465)

Arvin Xud97ed1501179
diff --git a/AGENTS.md b/AGENTS.md
index b543bd54416..d066a2c2b59 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -25,6 +25,7 @@ The `acceptance` skill is generated from the default branch of [lobehub/acceptan
For the full repository map or help locating a code layer, read the `project-overview` skill.
- `apps/server/src`: backend runtime, routers, and services, imported through `@/server/*`. `src/app/(backend)` contains Next.js route shells only; do not put backend business logic there.
+- Server business code reaches Redis through domain methods in `apps/server/src/services/redis` (`redisService.deviceSystemInfo`, `skillTools`, `workspaceRescan`). The service aggregates domains and owns connections, keys, TTL and consistency policy. `apps/server/src/modules/Redis` is only the client/provider layer, not the business service. Add missing business methods to the service and missing transport primitives to the client. Generic cache/claim helpers stay internal to the service boundary. ESLint prevents new direct client access; its explicit legacy migration list only shrinks.
- `src/app`: Next.js HTML/auth shells. Web shell helpers belong under `src/libs` or the relevant app segment, not `src/server`.
- `src/spa`: SPA entry points and React Router configuration. `src/routes` holds thin page segments that compose `src/features`; business UI and logic belong in features by domain.
- `src/services` and `src/store`: client API services and Zustand state. Keep fetch/cache guidance in `data-fetching-architecture` and store conventions in `zustand`.
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/deployment.test.ts b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/deployment.test.ts
index 1b49d5652d6..a3c9a8bc793 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/deployment.test.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/__tests__/deployment.test.ts
@@ -5,39 +5,25 @@ import { isLlmRelayDeploymentReady } from '../deployment';
const env = vi.hoisted(() => ({
app: {} as Record<string, string | undefined>,
- redis: {} as Record<string, string | undefined>,
}));
vi.mock('@/envs/app', () => ({ appEnv: env.app }));
-vi.mock('@/envs/redis', () => ({ redisEnv: env.redis }));
// The browser only stands by for a one-shot relay where the server can relay:
-// a gateway it can push to and the Redis the relayed call runs through.
-// Anything less and the server calls the provider itself, which cannot reach
-// a model on the user's device β€” the browser must keep its own fallback then.
+// a gateway it can push to. Anything less and the server calls the provider
+// itself, which cannot reach a model on the user's device β€” the browser must
+// keep its own fallback then.
describe('isLlmRelayDeploymentReady', () => {
beforeEach(() => {
- vi.unstubAllEnvs();
env.app.AGENT_GATEWAY_URL = 'https://gw';
env.app.AGENT_GATEWAY_INTERNAL_URL = undefined;
env.app.AGENT_GATEWAY_SERVICE_TOKEN = 'token';
- env.redis.REDIS_URL = 'redis://localhost:6379';
});
- it('is ready with a gateway, its service token and Redis', () => {
+ it('is ready with a gateway and its service token', () => {
expect(isLlmRelayDeploymentReady()).toBe(true);
});
- it('is not ready without Redis', () => {
- env.redis.REDIS_URL = undefined;
- expect(isLlmRelayDeploymentReady()).toBe(false);
- });
-
- it('is not ready with Redis disabled', () => {
- vi.stubEnv('DISABLE_REDIS', '1');
- expect(isLlmRelayDeploymentReady()).toBe(false);
- });
-
it('is not ready without a gateway service token', () => {
env.app.AGENT_GATEWAY_SERVICE_TOKEN = undefined;
expect(isLlmRelayDeploymentReady()).toBe(false);
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/deployment.ts b/apps/server/src/modules/AgentRuntime/llmRelay/deployment.ts
index e091e44d344..8e04566dfaf 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/deployment.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/deployment.ts
@@ -1,15 +1,12 @@
import { appEnv } from '@/envs/app';
-import { redisEnv } from '@/envs/redis';
-import { isRedisDisabledByEnv } from '@/libs/redis';
/**
* Whether this deployment can relay an LLM call to a browser tab: it pushes to
- * an Agent Gateway (URL + service token) and has the Redis relayed calls run
- * through. Exposed to the browser (`llmRelayAvailable`) so a tab only gives up
- * its own provider fallback where the server can actually relay.
+ * an Agent Gateway (URL + service token). Redis, which relayed calls run
+ * through, is a hard requirement of the app, so it is not checked here.
+ * Exposed to the browser (`llmRelayAvailable`) so a tab only gives up its own
+ * provider fallback where the server can actually relay.
*/
export const isLlmRelayDeploymentReady = (): boolean =>
!!(appEnv.AGENT_GATEWAY_INTERNAL_URL || appEnv.AGENT_GATEWAY_URL) &&
- !!appEnv.AGENT_GATEWAY_SERVICE_TOKEN &&
- !!redisEnv.REDIS_URL &&
- !isRedisDisabledByEnv();
+ !!appEnv.AGENT_GATEWAY_SERVICE_TOKEN;
diff --git a/apps/server/src/modules/AgentRuntime/redis.ts b/apps/server/src/modules/AgentRuntime/redis.ts
index 1a91adf2eab..2f663a839ec 100644
--- a/apps/server/src/modules/AgentRuntime/redis.ts
+++ b/apps/server/src/modules/AgentRuntime/redis.ts
@@ -2,7 +2,7 @@ import debug from 'debug';
import Redis from 'ioredis';
import { redisEnv } from '@/envs/redis';
-import { isRedisDisabledByEnv } from '@/libs/redis';
+import { isRedisDisabledByEnv } from '@/server/modules/Redis';
const log = debug('lobe-server:agent-runtime:redis');
const timing = debug('lobe-server:agent-runtime:timing');
diff --git a/src/libs/redis/index.ts b/apps/server/src/modules/Redis/index.ts
similarity index 100%
rename from src/libs/redis/index.ts
rename to apps/server/src/modules/Redis/index.ts
diff --git a/src/libs/redis/keys.ts b/apps/server/src/modules/Redis/keys.ts
similarity index 55%
rename from src/libs/redis/keys.ts
rename to apps/server/src/modules/Redis/keys.ts
index 8074000d67f..3b5e83841e3 100644
--- a/src/libs/redis/keys.ts
+++ b/apps/server/src/modules/Redis/keys.ts
@@ -23,6 +23,12 @@ export const RedisKeyNamespace = {
* Core LOBEHUB application keys (sessions, cache, etc.)
*/
LOBEHUB: 'lobechat',
+ /**
+ * Short-lived derived answers the send path would otherwise re-fetch per
+ * turn (device system info, a skill's live tool list) and the one-shot
+ * claims that keep their background refreshes from piling up.
+ */
+ SEND_PATH_CACHE: 'sendPathCache',
} as const;
/**
@@ -61,4 +67,29 @@ export const RedisKeys = {
lobechat: {
// Add lobechat scope keys here as needed
},
+ /**
+ * Send-path cache scope β€” see {@link RedisKeyNamespace.SEND_PATH_CACHE}.
+ * Every key carries the identity the answer depends on (user, pool, device,
+ * connection), never a shared one.
+ */
+ sendPathCache: {
+ /**
+ * A routed device's system info, per principal pool.
+ * Full key: sendPathCache:device_system_info:v1:{userId}:{pool}:{deviceId}
+ */
+ deviceSystemInfo: (userId: string, pool: string, deviceId: string): string =>
+ `device_system_info:v1:${userId}:${pool}:${deviceId}`,
+ /**
+ * One connected LobeHub skill's live tool list, per connection identity.
+ * Full key: sendPathCache:lobehub_skill_tools:v1:{userId}:{providerId}:{identity}
+ */
+ lobehubSkillTools: (userId: string, providerId: string, identity: string): string =>
+ `lobehub_skill_tools:v1:${userId}:${providerId}:${identity}`,
+ /**
+ * Claim held by the one background rescan of a bound directory.
+ * Full key: sendPathCache:workspace_rescan_claim:v1:{userId}:{pool}:{deviceId}:{cwd}
+ */
+ workspaceRescanClaim: (userId: string, pool: string, deviceId: string, cwd: string): string =>
+ `workspace_rescan_claim:v1:${userId}:${pool}:${deviceId}:${cwd}`,
+ },
} as const;
diff --git a/src/libs/redis/manager.test.ts b/apps/server/src/modules/Redis/manager.test.ts
similarity index 61%
rename from src/libs/redis/manager.test.ts
rename to apps/server/src/modules/Redis/manager.test.ts
index 503388e884e..46f0631caa2 100644
--- a/src/libs/redis/manager.test.ts
+++ b/apps/server/src/modules/Redis/manager.test.ts
@@ -1,6 +1,12 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { initializeRedis, RedisManager, resetRedisClient } from './manager';
+import {
+ initializeRedis,
+ RedisManager,
+ resetPrefixedRedisClient,
+ resetRedisClient,
+ tryInitializeRedisWithPrefix,
+} from './manager';
import { type RedisConfig } from './types';
const { mockIoRedisInitialize, mockIoRedisDisconnect } = vi.hoisted(() => ({
@@ -71,3 +77,34 @@ describe('RedisManager', () => {
expect(mockIoRedisDisconnect).toHaveBeenCalledTimes(1);
});
});
+
+describe('tryInitializeRedisWithPrefix', () => {
+ const config = {
+ enabled: true,
+ prefix: 'test',
+ tls: false,
+ url: 'redis://localhost:6379',
+ } satisfies RedisConfig;
+
+ afterEach(async () => {
+ await resetPrefixedRedisClient();
+ });
+
+ it('returns null instead of throwing when the connection fails, then retries', async () => {
+ mockIoRedisInitialize.mockRejectedValueOnce(new Error('ECONNREFUSED'));
+
+ await expect(tryInitializeRedisWithPrefix(config, 'cache')).resolves.toBeNull();
+
+ // The failed setup is dropped, so the next caller gets a live provider.
+ const provider = await tryInitializeRedisWithPrefix(config, 'cache');
+ expect(provider).not.toBeNull();
+ expect(mockIoRedisInitialize).toHaveBeenCalledTimes(2);
+ });
+
+ it('returns null when redis is disabled', async () => {
+ await expect(
+ tryInitializeRedisWithPrefix({ ...config, enabled: false, url: '' }, 'cache'),
+ ).resolves.toBeNull();
+ expect(mockIoRedisInitialize).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/libs/redis/manager.ts b/apps/server/src/modules/Redis/manager.ts
similarity index 84%
rename from src/libs/redis/manager.ts
rename to apps/server/src/modules/Redis/manager.ts
index 8723aeb69d5..12de8c503df 100644
--- a/src/libs/redis/manager.ts
+++ b/apps/server/src/modules/Redis/manager.ts
@@ -1,6 +1,10 @@
+import debug from 'debug';
+
import { IoRedisRedisProvider } from './redis';
import { type BaseRedisProvider, type RedisConfig } from './types';
+const log = debug('lobe:redis');
+
export const isRedisDisabledByEnv = () => !!process.env.DISABLE_REDIS;
export const isRedisEnabled = (config: RedisConfig) => !isRedisDisabledByEnv() && config.enabled;
@@ -139,3 +143,24 @@ export const initializeRedisWithPrefix = (config: RedisConfig, prefix: string) =
PrefixedRedisManager.initialize(config, prefix);
export const resetPrefixedRedisClient = (prefix?: string) => PrefixedRedisManager.reset(prefix);
+
+/**
+ * `initializeRedisWithPrefix` for callers that can live without Redis.
+ *
+ * The manager rejects when the connection cannot be established and retries
+ * on the next call (it drops the failed in-flight setup). A cache or a claim
+ * on a hot path must not turn that into a failed request: here the failure
+ * becomes `null`, the same answer the caller already handles for a disabled
+ * Redis, and the request proceeds without the cache.
+ */
+export const tryInitializeRedisWithPrefix = async (
+ config: RedisConfig,
+ prefix: string,
+): Promise<BaseRedisProvider | null> => {
+ try {
+ return await PrefixedRedisManager.initialize(config, prefix);
+ } catch (error) {
+ log('redis "%s" unavailable, continuing without it: %O', prefix, error);
+ return null;
+ }
+};
diff --git a/src/libs/redis/redis.test.ts b/apps/server/src/modules/Redis/redis.test.ts
similarity index 94%
rename from src/libs/redis/redis.test.ts
rename to apps/server/src/modules/Redis/redis.test.ts
index 95e846ee9f8..3a8ccb2ab98 100644
--- a/src/libs/redis/redis.test.ts
+++ b/apps/server/src/modules/Redis/redis.test.ts
@@ -22,7 +22,7 @@ const buildRedisConfig = (): RedisConfig | null => {
const loadRedisProvider = async () => (await import('./redis')).IoRedisRedisProvider;
-const createMockedProvider = async () => {
+const createMockedProvider = async (config: Partial<RedisConfig> = {}) => {
const instances: Array<{ options: Record<PropertyKey, unknown>; url: string }> = [];
const createPipelineMock = () => {
@@ -116,6 +116,7 @@ const createMockedProvider = async () => {
prefix: 'mock',
tls: false,
url: 'redis://localhost:6379',
+ ...config,
});
await provider.initialize();
@@ -185,6 +186,22 @@ describe('mocked', () => {
await provider.disconnect();
});
+ it('honors per-config connect and command timeouts', async () => {
+ const { instances, provider } = await createMockedProvider({
+ commandTimeoutMs: 1000,
+ connectTimeoutMs: 1000,
+ });
+
+ expect(instances[0]).toMatchObject({
+ options: {
+ commandTimeout: 1000,
+ connectTimeout: 1000,
+ },
+ });
+
+ await provider.disconnect();
+ });
+
it('normalizes set options into ioredis arguments', async () => {
const { mocks, provider } = await createMockedProvider();
await provider.set('key', 'value', { ex: 10, nx: true, get: true });
diff --git a/src/libs/redis/redis.ts b/apps/server/src/modules/Redis/redis.ts
similarity index 95%
rename from src/libs/redis/redis.ts
rename to apps/server/src/modules/Redis/redis.ts
index eaa21eeb01d..6ac22747bff 100644
--- a/src/libs/redis/redis.ts
+++ b/apps/server/src/modules/Redis/redis.ts
@@ -1,5 +1,5 @@
import debug from 'debug';
-import { type Redis } from 'ioredis';
+import IORedis, { type Redis } from 'ioredis';
import {
type BaseRedisProvider,
@@ -26,11 +26,9 @@ export class IoRedisRedisProvider implements BaseRedisProvider {
constructor(private config: RedisConfig) {}
async initialize() {
- const IORedis = await import('ioredis');
-
- this.client = new IORedis.default(this.config.url, {
- commandTimeout: REDIS_COMMAND_TIMEOUT_MS,
- connectTimeout: REDIS_CONNECT_TIMEOUT_MS,
+ this.client = new IORedis(this.config.url, {
+ commandTimeout: this.config.commandTimeoutMs ?? REDIS_COMMAND_TIMEOUT_MS,
+ connectTimeout: this.config.connectTimeoutMs ?? REDIS_CONNECT_TIMEOUT_MS,
db: this.config.database,
keyPrefix: this.config.prefix ? `${this.config.prefix}:` : undefined,
lazyConnect: true,
diff --git a/src/libs/redis/types.ts b/apps/server/src/modules/Redis/types.ts
similarity index 100%
rename from src/libs/redis/types.ts
rename to apps/server/src/modules/Redis/types.ts
diff --git a/src/libs/redis/utils.test.ts b/apps/server/src/modules/Redis/utils.test.ts
similarity index 100%
rename from src/libs/redis/utils.test.ts
rename to apps/server/src/modules/Redis/utils.test.ts
diff --git a/src/libs/redis/utils.ts b/apps/server/src/modules/Redis/utils.ts
similarity index 89%
rename from src/libs/redis/utils.ts
rename to apps/server/src/modules/Redis/utils.ts
index df15828be8a..7e289c1fac9 100644
--- a/src/libs/redis/utils.ts
+++ b/apps/server/src/modules/Redis/utils.ts
@@ -64,3 +64,7 @@ export const buildIORedisSetArgs = (options?: SetOptions): Array<string | number
return args;
};
+
+// Cache/claim policy (read-through, atomic claim) lives in the service
+// boundary β€” see `services/redis/cache.ts`. This module keeps only transport
+// primitives (key/Buffer normalization, ioredis argument building, JSON reads).
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/runGuard.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/runGuard.test.ts
index 9d83054836b..79b674bbffc 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/runGuard.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/runGuard.test.ts
@@ -8,7 +8,7 @@ const mocks = vi.hoisted(() => ({
isRedisEnabled: vi.fn(),
}));
-vi.mock('@/libs/redis', () => ({
+vi.mock('@/server/modules/Redis', () => ({
initializeRedis: mocks.initializeRedis,
isRedisEnabled: mocks.isRedisEnabled,
}));
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/runGuard.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/runGuard.ts
index e2a62804b8f..e1c48aae89d 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/runGuard.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/runGuard.ts
@@ -1,8 +1,8 @@
import { type WorkflowContext } from '@upstash/workflow';
import { getRedisConfig } from '@/envs/redis';
-import { initializeRedis, isRedisEnabled } from '@/libs/redis';
-import { type BaseRedisProvider } from '@/libs/redis/types';
+import { initializeRedis, isRedisEnabled } from '@/server/modules/Redis';
+import { type BaseRedisProvider } from '@/server/modules/Redis/types';
import { assertWorkflowRunAllowed, WorkflowRunGuardError } from '@/server/workflows/runGuard';
import { runStep } from '@/server/workflows/step';
diff --git a/apps/server/src/runtimeConfig/providers/RedisRuntimeConfigProvider.test.ts b/apps/server/src/runtimeConfig/providers/RedisRuntimeConfigProvider.test.ts
index 2a271cd95e6..8f04adfb1b2 100644
--- a/apps/server/src/runtimeConfig/providers/RedisRuntimeConfigProvider.test.ts
+++ b/apps/server/src/runtimeConfig/providers/RedisRuntimeConfigProvider.test.ts
@@ -13,7 +13,7 @@ vi.mock('@/envs/redis', () => ({
getRedisConfig: getRedisConfigMock,
}));
-vi.mock('@/libs/redis', () => ({
+vi.mock('@/server/modules/Redis', () => ({
initializeRedis: initializeRedisMock,
}));
diff --git a/apps/server/src/runtimeConfig/providers/RedisRuntimeConfigProvider.ts b/apps/server/src/runtimeConfig/providers/RedisRuntimeConfigProvider.ts
index 6d725799a0f..835ae7e4f39 100644
--- a/apps/server/src/runtimeConfig/providers/RedisRuntimeConfigProvider.ts
+++ b/apps/server/src/runtimeConfig/providers/RedisRuntimeConfigProvider.ts
@@ -1,7 +1,7 @@
import debug from 'debug';
import { getRedisConfig } from '@/envs/redis';
-import { initializeRedis } from '@/libs/redis';
+import { initializeRedis } from '@/server/modules/Redis';
import type {
RuntimeConfigDomain,
diff --git a/apps/server/src/services/agent/index.test.ts b/apps/server/src/services/agent/index.test.ts
index 9508be526cc..fae771a5f5d 100644
--- a/apps/server/src/services/agent/index.test.ts
+++ b/apps/server/src/services/agent/index.test.ts
@@ -7,9 +7,9 @@ import { AgentModel } from '@/database/models/agent';
import { AgentShareModel } from '@/database/models/agentShare';
import { SessionModel } from '@/database/models/session';
import { UserModel } from '@/database/models/user';
-import type * as RedisModule from '@/libs/redis';
-import { initializeRedisWithPrefix, isRedisEnabled, RedisKeys } from '@/libs/redis';
import { parseAgentConfig } from '@/server/globalConfig/parseDefaultAgent';
+import type * as RedisModule from '@/server/modules/Redis';
+import { initializeRedisWithPrefix, isRedisEnabled, RedisKeys } from '@/server/modules/Redis';
import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
import { AgentService } from './index';
@@ -55,7 +55,7 @@ vi.mock('@/envs/redis', () => ({
getRedisConfig: vi.fn().mockReturnValue({ enabled: true }),
}));
-vi.mock('@/libs/redis', async (importOriginal) => {
+vi.mock('@/server/modules/Redis', async (importOriginal) => {
const original = await importOriginal<typeof RedisModule>();
return {
...original,
diff --git a/apps/server/src/services/agent/index.ts b/apps/server/src/services/agent/index.ts
index 81379ebc754..08d59428d7a 100644
--- a/apps/server/src/services/agent/index.ts
+++ b/apps/server/src/services/agent/index.ts
@@ -16,14 +16,14 @@ import { SessionModel } from '@/database/models/session';
import { UserModel } from '@/database/models/user';
import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '@/database/utils/inboxAgent';
import { getRedisConfig } from '@/envs/redis';
+import { getServerDefaultAgentConfig } from '@/server/globalConfig';
import {
getJSONFromRedis,
initializeRedisWithPrefix,
isRedisEnabled,
RedisKeyNamespace,
RedisKeys,
-} from '@/libs/redis';
-import { getServerDefaultAgentConfig } from '@/server/globalConfig';
+} from '@/server/modules/Redis';
import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
import { type UpdateAgentResult } from './type';
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
index 6ca1f5ee7b4..c208cabdd1a 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
@@ -693,7 +693,9 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
- expect(mockQueryDeviceSystemInfo).toHaveBeenCalledWith(userId, 'ws-dev-1', workspaceId);
+ expect(mockQueryDeviceSystemInfo).toHaveBeenCalledWith(userId, 'ws-dev-1', workspaceId, {
+ maxAgeMs: expect.any(Number),
+ });
const createOpArgs = mockCreateOperation.mock.calls[0][0];
expect(createOpArgs.activeDeviceId).toBe('ws-dev-1');
@@ -741,7 +743,9 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {
await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
// Personal principal: third arg must stay undefined (not this.workspaceId).
- expect(mockQueryDeviceSystemInfo).toHaveBeenCalledWith(userId, 'personal-dev-1', undefined);
+ expect(mockQueryDeviceSystemInfo).toHaveBeenCalledWith(userId, 'personal-dev-1', undefined, {
+ maxAgeMs: expect.any(Number),
+ });
const createOpArgs = mockCreateOperation.mock.calls[0][0];
expect(createOpArgs.activeDeviceId).toBe('personal-dev-1');
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
index a8f06fb07f9..a0349d912be 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts
@@ -1,6 +1,8 @@
import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type * as RedisLib from '@/server/modules/Redis';
+
import { AiAgentService } from '../index';
/**
@@ -170,6 +172,37 @@ vi.mock('@/server/modules/Mecha', () => {
};
});
+// The background rescan claims itself (SET NX) through the unified Redis lib
+// before scanning. A fake provider keeps the claims in a Set so the test can
+// prove that concurrent sends coalesce on one scan.
+const { claimedKeys, mockTryInitializeRedisWithPrefix } = vi.hoisted(() => {
+ const claimedKeys = new Set<string>();
+ const redis = {
+ get: vi.fn(async () => null),
+ set: vi.fn(async (key: string, _value: unknown, options?: { nx?: boolean }) => {
+ if (!options?.nx) return 'OK';
+ if (claimedKeys.has(key)) return null;
+ claimedKeys.add(key);
+ return 'OK';
+ }),
+ };
+ return { claimedKeys, mockTryInitializeRedisWithPrefix: vi.fn(async () => redis) };
+});
+vi.mock('@/server/modules/Redis', async (importOriginal) => ({
+ ...(await importOriginal<typeof RedisLib>()),
+ // The enabled config below would otherwise make every other Redis user (runtime config,
+ // latency cache, ...) open a real connection to `redis://test`, whose retry errors keep
+ // logging after the file finishes and fail the run with an EnvironmentTeardownError.
+ initializeRedis: vi.fn(async () => null),
+ tryInitializeRedisWithPrefix: mockTryInitializeRedisWithPrefix,
+}));
+// Without REDIS_URL the service never reaches the fake provider and claims fall
+// back to a process-local map that outlives `claimedKeys.clear()`, so one
+// test's claim would silently block every later stale-scan refresh.
+vi.mock('@/envs/redis', () => ({
+ getRedisConfig: () => ({ enabled: true, prefix: 'test', url: 'redis://test' }),
+}));
+
vi.mock('@/server/services/deviceGateway', () => ({
deviceGateway: {
initWorkspace: mockInitWorkspace,
@@ -235,6 +268,7 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
mockUpdateDevice.mockResolvedValue(undefined);
mockUpdateTopicMetadata.mockResolvedValue(undefined);
+ claimedKeys.clear();
service = new AiAgentService(mockDb, userId);
});
@@ -288,6 +322,169 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {
});
});
+ it('serves a stale workspace scan and refreshes it after the response', async () => {
+ // Two hours old: past the TTL, but still a usable description of the
+ // project. The send must not wait on the device's directory walk.
+ mockFindByDeviceId.mockResolvedValue({
+ defaultCwd: '/repo/default',
+ deviceId: DEVICE_ID,
+ workingDirs: [
+ {
+ path: '/repo/default',
+ workspace: { instructions: [], skills: [] },
+ workspaceScannedAt: Date.now() - 2 * 60 * 60 * 1000,
+ },
+ ],
+ });
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
+ );
+ // A scan that never completes: if the send awaited it, this test would hang.
+ mockInitWorkspace.mockReturnValue(new Promise(() => {}));
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+
+ expect(mockInitWorkspace).toHaveBeenCalledTimes(1);
+ expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ boundDeviceId: DEVICE_ID,
+ workingDirectory: '/repo/default',
+ workingDirectoryConfig: { path: '/repo/default' },
+ });
+ });
+
+ it('lets only one of several concurrent sends refresh the same stale scan', async () => {
+ mockFindByDeviceId.mockResolvedValue({
+ defaultCwd: '/repo/default',
+ deviceId: DEVICE_ID,
+ workingDirs: [
+ {
+ path: '/repo/default',
+ workspace: { instructions: [], skills: [] },
+ workspaceScannedAt: Date.now() - 2 * 60 * 60 * 1000,
+ },
+ ],
+ });
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
+ );
+ mockInitWorkspace.mockReturnValue(new Promise(() => {}));
+
+ await Promise.all([
+ service.execAgent({ agentId: 'agent-1', prompt: 'Hello' }),
+ service.execAgent({ agentId: 'agent-1', prompt: 'Hello again' }),
+ service.execAgent({ agentId: 'agent-1', prompt: 'And again' }),
+ ]);
+ // The refresh is scheduled off the send path; let it reach the claim.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(mockInitWorkspace).toHaveBeenCalledTimes(1);
+ });
+
+ it('merges a directory the user added mid-scan instead of overwriting it', async () => {
+ const staleEntry = {
+ path: '/repo/default',
+ workspace: { instructions: [], skills: [] },
+ workspaceScannedAt: Date.now() - 2 * 60 * 60 * 1000,
+ };
+
+ // The scan takes up to 30s; land a concurrent directory edit while it is
+ // in flight so the write-back has a newer list to merge into.
+ let scanStarted = false;
+ mockInitWorkspace.mockImplementation(async () => {
+ scanStarted = true;
+ return { instructions: [], skills: [] };
+ });
+ mockFindByDeviceId.mockImplementation(async () => ({
+ defaultCwd: '/repo/default',
+ deviceId: DEVICE_ID,
+ workingDirs: scanStarted
+ ? [staleEntry, { path: '/repo/new', workspaceScannedAt: 1 }]
+ : [staleEntry],
+ }));
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
+ );
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ // The refreshed entry is persisted AND the concurrent add survives the
+ // write-back β€” rebuilding from the pre-scan snapshot would drop it.
+ expect(mockUpdateDevice).toHaveBeenCalledWith(
+ DEVICE_ID,
+ expect.objectContaining({
+ workingDirs: expect.arrayContaining([
+ expect.objectContaining({ path: '/repo/default' }),
+ expect.objectContaining({ path: '/repo/new' }),
+ ]),
+ }),
+ );
+ });
+
+ it('does not resurrect a directory the user removed mid-scan', async () => {
+ const staleEntry = {
+ path: '/repo/default',
+ workspace: { instructions: [], skills: [] },
+ workspaceScannedAt: Date.now() - 2 * 60 * 60 * 1000,
+ };
+
+ let scanStarted = false;
+ mockInitWorkspace.mockImplementation(async () => {
+ scanStarted = true;
+ return { instructions: [], skills: [] };
+ });
+ mockFindByDeviceId.mockImplementation(async () => ({
+ defaultCwd: '/repo/default',
+ deviceId: DEVICE_ID,
+ workingDirs: scanStarted ? [{ path: '/repo/other', workspaceScannedAt: 1 }] : [staleEntry],
+ }));
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
+ );
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ expect(mockInitWorkspace).toHaveBeenCalledTimes(1);
+ // `workingDirs` is the file-operation allowlist: the removal must stick.
+ expect(mockUpdateDevice).not.toHaveBeenCalledWith(
+ DEVICE_ID,
+ expect.objectContaining({ workingDirs: expect.anything() }),
+ );
+ });
+
+ it('still refreshes when the Redis claim command fails', async () => {
+ mockFindByDeviceId.mockResolvedValue({
+ defaultCwd: '/repo/default',
+ deviceId: DEVICE_ID,
+ workingDirs: [
+ {
+ path: '/repo/default',
+ workspace: { instructions: [], skills: [] },
+ workspaceScannedAt: Date.now() - 2 * 60 * 60 * 1000,
+ },
+ ],
+ });
+ mockGetAgentConfig.mockResolvedValue(
+ createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),
+ );
+ mockInitWorkspace.mockResolvedValue({ instructions: [], skills: [] });
+ // A memoized client whose commands fail: coordination is best-effort, so
+ // the refresh must still happen instead of being silently skipped.
+ mockTryInitializeRedisWithPrefix.mockResolvedValueOnce({
+ get: vi.fn(async () => null),
+ set: vi.fn(async () => {
+ throw new Error('redis down');
+ }),
+ } as any);
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ expect(mockInitWorkspace).toHaveBeenCalledTimes(1);
+ expect(mockUpdateDevice).toHaveBeenCalled();
+ });
+
it('never rewrites a topic that is already pinned to a directory', async () => {
// The historical pin is the contract: an old conversation must not follow
// the agent's current default when that default changes later.
diff --git a/apps/server/src/services/aiAgent/__tests__/runFacts.test.ts b/apps/server/src/services/aiAgent/__tests__/runFacts.test.ts
index daefc1d26b0..a74774ee8f2 100644
--- a/apps/server/src/services/aiAgent/__tests__/runFacts.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/runFacts.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { createRunFacts } from '../runFacts';
+import { createRunFacts, DEVICE_SYSTEM_INFO_MAX_AGE_MS } from '../runFacts';
const { getUserSettings, queryDeviceSystemInfo } = vi.hoisted(() => ({
getUserSettings: vi.fn(),
@@ -43,7 +43,9 @@ describe('createRunFacts', () => {
expect(queryDeviceSystemInfo).toHaveBeenCalledTimes(1);
expect(a).toBe(b);
// A personal device must not receive the workspace id.
- expect(queryDeviceSystemInfo).toHaveBeenCalledWith('owner-1', 'dev-1', undefined);
+ expect(queryDeviceSystemInfo).toHaveBeenCalledWith('owner-1', 'dev-1', undefined, {
+ maxAgeMs: DEVICE_SYSTEM_INFO_MAX_AGE_MS,
+ });
});
it('keeps the workspace and personal scopes of the same device apart', async () => {
@@ -53,8 +55,12 @@ describe('createRunFacts', () => {
await runFacts.deviceSystemInfo('dev-1', 'personal');
expect(queryDeviceSystemInfo).toHaveBeenCalledTimes(2);
- expect(queryDeviceSystemInfo).toHaveBeenNthCalledWith(1, 'owner-1', 'dev-1', 'ws-1');
- expect(queryDeviceSystemInfo).toHaveBeenNthCalledWith(2, 'owner-1', 'dev-1', undefined);
+ expect(queryDeviceSystemInfo).toHaveBeenNthCalledWith(1, 'owner-1', 'dev-1', 'ws-1', {
+ maxAgeMs: DEVICE_SYSTEM_INFO_MAX_AGE_MS,
+ });
+ expect(queryDeviceSystemInfo).toHaveBeenNthCalledWith(2, 'owner-1', 'dev-1', undefined, {
+ maxAgeMs: DEVICE_SYSTEM_INFO_MAX_AGE_MS,
+ });
});
it('remembers an unreachable device rather than asking again', async () => {
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index f1a046a8b58..152bd66e3f1 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -28,6 +28,8 @@ import type { ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngin
import type { AgentDocumentsService } from '@/server/services/agentDocuments';
import { deviceGateway } from '@/server/services/deviceGateway';
import { FileService } from '@/server/services/file';
+import { redisService } from '@/server/services/redis';
+import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';
import { pruneRegeneratedBranch } from '../pruneRegeneratedBranch';
import { resolveDeviceWorkingDirectoryConfig } from '../resolveDeviceWorkingDirectory';
@@ -294,26 +296,10 @@ const resolveWorkspaceInit = async (
return { ...resolved, workspace: cached.workspace };
}
- const scanned = await deviceGateway.initWorkspace({
- deviceId: activeDeviceId,
- scope: boundCwd,
- userId: deps.userId,
- workspaceId: deviceWorkspaceId,
- });
- if (!scanned) {
- // Scan failed (offline mid-run / parse error). Fall back to a stale
- // cache rather than dropping the project's skills + instructions.
- if (cached?.workspace) {
- log('execAgent: workspace init scan failed, using stale cache for %s', boundCwd);
- return { ...resolved, workspace: cached.workspace };
- }
- return { ...resolved, workspace: empty };
- }
-
- // Persist the fresh scan back onto `workingDirs` (update in place or prepend
- // a new MRU entry), keeping the JSONB payload bounded. Workspace devices
- // are owned by the workspace, not a userId β€” use the workspace-scoped
- // update path so the writeback actually lands.
+ // Scan the directory on the device and persist the result back onto
+ // `workingDirs` (update in place or prepend a new MRU entry), keeping the
+ // JSONB payload bounded. Workspace devices are owned by the workspace, not
+ // a userId β€” use the workspace-scoped update path so the writeback lands.
//
// Update the MATCHED entry's path, not `boundCwd`: the lookup above can
// match a source entry by its effective (worktree) path, so a selected
@@ -321,15 +307,85 @@ const resolveWorkspaceInit = async (
// recorded entry is keyed by the source path. Upserting on `boundCwd`
// would prepend a bare worktree recent and lose the source/worktree
// metadata the picker relies on; upsert on the matched source path instead.
- const updated = upsertWorkspaceScan(workingDirs, cached?.path ?? boundCwd, scanned, Date.now());
- if (deviceWorkspaceId) {
- await deviceModel.updateWorkspaceDevice(activeDeviceId, { workingDirs: updated });
- } else {
- await deviceModel.update(activeDeviceId, { workingDirs: updated });
+ const scanAndPersist = async (): Promise<WorkspaceInitResult | undefined> => {
+ const scanned = await deviceGateway.initWorkspace({
+ deviceId: activeDeviceId,
+ scope: boundCwd,
+ userId: deps.userId,
+ workspaceId: deviceWorkspaceId,
+ });
+ if (!scanned) return undefined;
+
+ // Re-read the row before writing: the scan runs for up to 30s, and the
+ // user (or another refresh) may have edited `workingDirs` in the
+ // meantime. Merging the fresh scan into the CURRENT list keeps those
+ // edits instead of overwriting them with the pre-scan snapshot.
+ const latest = deviceWorkspaceId
+ ? await deviceModel.findWorkspaceDeviceById(activeDeviceId)
+ : await deviceModel.findByDeviceId(activeDeviceId);
+ const current = latest?.workingDirs ?? workingDirs;
+
+ // The entry this scan refreshes was removed mid-scan. Writing it back
+ // would resurrect it β€” and `workingDirs` is the allowlist for device
+ // file-operation roots β€” so keep the answer for this turn only.
+ if (cached && !current.some((dir) => dir.path === cached.path)) {
+ log('execAgent: %s was removed during the scan; skip the writeback', cached.path);
+ return scanned;
+ }
+
+ const updated = upsertWorkspaceScan(current, cached?.path ?? boundCwd, scanned, Date.now());
+ if (deviceWorkspaceId) {
+ await deviceModel.updateWorkspaceDevice(activeDeviceId, { workingDirs: updated });
+ } else {
+ await deviceModel.update(activeDeviceId, { workingDirs: updated });
+ }
+ log('execAgent: scanned and cached workspace init for %s', boundCwd);
+ return scanned;
+ };
+
+ // A stale scan still describes the project well enough for this turn:
+ // project skills and AGENTS.md change on the order of commits, not sends.
+ // Serve it now and refresh after the response, so the user does not wait
+ // on a directory walk over the device's WebSocket (up to 30s) just
+ // because an hour passed. A directory never scanned still scans inline β€”
+ // there is nothing to serve instead.
+ //
+ // Unscoped on purpose: a sub-agent or group-member run reaches here from
+ // inside a step's scheduled-work scope, whose step-boundary flush has a
+ // short budget β€” a rescan of this length would stall it. The refresh is
+ // not part of the step's settlement, so it goes straight to the host.
+ //
+ // Claimed before scanning: concurrent sends, sub-agents and group members
+ // that read the same stale entry would each schedule their own 30s walk
+ // and the same writeback. One of them wins the claim for the length of a
+ // scan; the others leave the refresh to it.
+ if (cached?.workspace) {
+ log('execAgent: serving stale workspace init for %s, refreshing in background', boundCwd);
+ afterUnscoped(async () => {
+ try {
+ if (
+ !(await redisService.workspaceRescan.claim({
+ userId: deps.userId,
+ workspaceId: deviceWorkspaceId,
+ deviceId: activeDeviceId,
+ cwd: boundCwd,
+ }))
+ ) {
+ log('execAgent: workspace rescan for %s already in flight, skipping', boundCwd);
+ return;
+ }
+ await scanAndPersist();
+ } catch (error) {
+ log('execAgent: background workspace rescan failed for %s: %O', boundCwd, error);
+ }
+ });
+ return { ...resolved, workspace: cached.workspace };
}
- log('execAgent: scanned and cached workspace init for %s', boundCwd);
- return { ...resolved, workspace: scanned };
+ const scanned = await scanAndPersist();
+ // Scan failed (offline mid-run / parse error) and there is no cache to
+ // fall back to: the run proceeds without project skills + instructions.
+ return { ...resolved, workspace: scanned ?? empty };
} catch (error) {
log('execAgent: resolveWorkspaceInit failed: %O', error);
return { workspace: empty };
diff --git a/apps/server/src/services/aiAgent/runFacts.ts b/apps/server/src/services/aiAgent/runFacts.ts
index cad1d52f47e..0e8176eb2e2 100644
--- a/apps/server/src/services/aiAgent/runFacts.ts
+++ b/apps/server/src/services/aiAgent/runFacts.ts
@@ -58,6 +58,15 @@ const memoize = <T>(read: (key: string) => Promise<T>) => {
const KEY_SEPARATOR = String.fromCodePoint(0);
+/**
+ * How old a device's system-info answer may be when a send reuses it. The
+ * answer only changes when the client upgrades or the daemon moves, and the
+ * send path asked for it on every turn (240–620ms over the device's
+ * WebSocket); three minutes covers a burst of sends without hiding a client
+ * upgrade for long.
+ */
+export const DEVICE_SYSTEM_INFO_MAX_AGE_MS = 3 * 60 * 1000;
+
export const createRunFacts = ({ db, userId, workspaceId }: RunFactsSource): RunFacts => {
const readDeviceSystemInfo = memoize(async (key: string) => {
const [deviceId, scope] = key.split(KEY_SEPARATOR);
@@ -68,6 +77,7 @@ export const createRunFacts = ({ db, userId, workspaceId }: RunFactsSource): Run
userId,
deviceId,
scope === 'workspace' ? workspaceId : undefined,
+ { maxAgeMs: DEVICE_SYSTEM_INFO_MAX_AGE_MS },
);
});
diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
index c2a43832276..3a1cc308883 100644
--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts
+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
@@ -27,6 +27,16 @@ const MockGatewayHttpClient = vi.hoisted(() =>
}),
);
+// The send-path cache rides on the Redis service; hand its connection seam a
+// fake client so the test sees which key and TTL the gateway asked for,
+// independent of whether this environment has Redis configured.
+const { cacheRedis, getRedisServiceClient } = vi.hoisted(() => {
+ const cacheRedis = { get: vi.fn(async () => null), set: vi.fn(async () => 'OK') };
+ return { cacheRedis, getRedisServiceClient: vi.fn(async () => cacheRedis) };
+});
+
+vi.mock('@/server/services/redis/client', () => ({ getRedisServiceClient }));
+
vi.mock('@/envs/gateway', () => ({
gatewayEnv: mockEnv,
}));
@@ -443,6 +453,37 @@ describe('DeviceGateway', () => {
expect(result).toBeUndefined();
});
+
+ it('asks the device directly when no maxAge is given', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo: {} });
+
+ await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');
+
+ expect(getRedisServiceClient).not.toHaveBeenCalled();
+ expect(cacheRedis.get).not.toHaveBeenCalled();
+ });
+
+ it('serves a recent answer through the cache when maxAge is set', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ const systemInfo = { arch: 'arm64' };
+ mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo });
+
+ const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1', 'ws-1', {
+ maxAgeMs: 180_000,
+ });
+
+ expect(result).toEqual(systemInfo);
+ // The key carries user, pool and device so two principals never share an answer.
+ expect(cacheRedis.get).toHaveBeenCalledWith('device_system_info:v1:user-1:ws-1:dev-1');
+ expect(cacheRedis.set).toHaveBeenCalledWith(
+ 'device_system_info:v1:user-1:ws-1:dev-1',
+ JSON.stringify(systemInfo),
+ { px: 180_000 },
+ );
+ });
});
describe('queryDeviceSystemInfo client preference', () => {
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index f83e7fd82bf..d53579a7fea 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -75,6 +75,7 @@ import debug from 'debug';
import { isAbsolute, relative, resolve } from 'pathe';
import { gatewayEnv } from '@/envs/gateway';
+import { redisService } from '@/server/services/redis';
import { resolveDeviceClientKinds } from './clientKinds';
@@ -279,19 +280,39 @@ export class DeviceGateway {
* `DEVICE_OFFLINE`) may still sit beside a live `lh connect`, which is the
* answer canary got. A gateway that predates `clientKinds` answers the first
* read as before.
+ *
+ * `maxAgeMs` lets a caller accept an answer this device gave within that
+ * window instead of a fresh round trip over its WebSocket. The send path
+ * asks every turn and the answer changes only when the client upgrades or
+ * the user moves the daemon, so a few minutes of staleness there is a
+ * round trip saved per send; callers that need the live answer (an
+ * explicit device inspection) leave it unset. Only successful answers are
+ * remembered β€” an offline device is asked again next time.
*/
async queryDeviceSystemInfo(
userId: string,
deviceId: string,
workspaceId?: string,
+ options?: { maxAgeMs?: number },
): Promise<DeviceSystemInfo | undefined> {
- const desktop = await this.readDeviceSystemInfo(userId, deviceId, workspaceId, {
- clientKinds: ['desktop'],
- });
- if (desktop.ok) return desktop.systemInfo;
+ const query = async () => {
+ const desktop = await this.readDeviceSystemInfo(userId, deviceId, workspaceId, {
+ clientKinds: ['desktop'],
+ });
+ if (desktop.ok) return desktop.systemInfo;
+
+ const any = await this.readDeviceSystemInfo(userId, deviceId, workspaceId);
+ return any.ok ? any.systemInfo : undefined;
+ };
- const any = await this.readDeviceSystemInfo(userId, deviceId, workspaceId);
- return any.ok ? any.systemInfo : undefined;
+ const maxAgeMs = options?.maxAgeMs;
+ if (!maxAgeMs || maxAgeMs <= 0) return query();
+
+ return redisService.deviceSystemInfo.remember(
+ { userId, deviceId, workspaceId },
+ query,
+ maxAgeMs,
+ );
}
/**
diff --git a/apps/server/src/services/file/impls/s3.test.ts b/apps/server/src/services/file/impls/s3.test.ts
index 49f3c937a71..15a719031d1 100644
--- a/apps/server/src/services/file/impls/s3.test.ts
+++ b/apps/server/src/services/file/impls/s3.test.ts
@@ -37,7 +37,7 @@ vi.mock('@/envs/redis', () => ({
getRedisConfig: redisMocks.getRedisConfig,
}));
-vi.mock('@/libs/redis', () => ({
+vi.mock('@/server/modules/Redis', () => ({
initializeRedis: redisMocks.initializeRedis,
isRedisEnabled: redisMocks.isRedisEnabled,
}));
diff --git a/apps/server/src/services/file/impls/s3.ts b/apps/server/src/services/file/impls/s3.ts
index c69c75908a1..fa1ca7fb56e 100644
--- a/apps/server/src/services/file/impls/s3.ts
+++ b/apps/server/src/services/file/impls/s3.ts
@@ -5,7 +5,7 @@ import urlJoin from 'url-join';
import { FileModel } from '@/database/models/file';
import { fileEnv } from '@/envs/file';
import { getRedisConfig } from '@/envs/redis';
-import { initializeRedis, isRedisEnabled } from '@/libs/redis';
+import { initializeRedis, isRedisEnabled } from '@/server/modules/Redis';
import { FileS3 } from '@/server/modules/S3';
import type { FileServiceImpl, PreSignedUpload } from './type';
diff --git a/apps/server/src/services/generation/latency.test.ts b/apps/server/src/services/generation/latency.test.ts
index d567bf18a08..29721eb4b62 100644
--- a/apps/server/src/services/generation/latency.test.ts
+++ b/apps/server/src/services/generation/latency.test.ts
@@ -8,7 +8,7 @@ vi.mock('@/envs/redis', () => ({
getRedisConfig: vi.fn().mockReturnValue({}),
}));
-vi.mock('@/libs/redis', () => ({
+vi.mock('@/server/modules/Redis', () => ({
isRedisEnabled: vi.fn().mockReturnValue(false),
initializeRedis: vi.fn(),
}));
@@ -16,7 +16,7 @@ vi.mock('@/libs/redis', () => ({
// Must import after vi.mock declarations
const { getVideoAvgLatencies, getVideoLatencyKey } = await import('./latency');
const { getServerDB } = await import('@/database/server');
-const { isRedisEnabled, initializeRedis } = await import('@/libs/redis');
+const { isRedisEnabled, initializeRedis } = await import('@/server/modules/Redis');
interface LatencyRow {
latency: number | null;
diff --git a/apps/server/src/services/generation/latency.ts b/apps/server/src/services/generation/latency.ts
index 795f0ab0289..2ddcfb115a9 100644
--- a/apps/server/src/services/generation/latency.ts
+++ b/apps/server/src/services/generation/latency.ts
@@ -4,7 +4,7 @@ import { and, eq, gte, isNotNull, or, sql } from 'drizzle-orm';
import { asyncTasks, generationBatches, generations } from '@/database/schemas';
import { getServerDB } from '@/database/server';
import { getRedisConfig } from '@/envs/redis';
-import { initializeRedis, isRedisEnabled, type RedisClient } from '@/libs/redis';
+import { initializeRedis, isRedisEnabled, type RedisClient } from '@/server/modules/Redis';
const CACHE_KEY_PREFIX = 'video:avg_latency';
const CACHE_TTL_SECONDS = 300; // 5 minutes
diff --git a/apps/server/src/services/home/index.ts b/apps/server/src/services/home/index.ts
index 6c7ee04e53f..e6434570cf4 100644
--- a/apps/server/src/services/home/index.ts
+++ b/apps/server/src/services/home/index.ts
@@ -7,7 +7,7 @@ import {
isRedisEnabled,
RedisKeyNamespace,
RedisKeys,
-} from '@/libs/redis';
+} from '@/server/modules/Redis';
const log = debug('lobe-server:home-service');
diff --git a/apps/server/src/services/market/index.test.ts b/apps/server/src/services/market/index.test.ts
index 62775a5b205..8273e9f3cac 100644
--- a/apps/server/src/services/market/index.test.ts
+++ b/apps/server/src/services/market/index.test.ts
@@ -524,7 +524,10 @@ describe('MarketService', () => {
(service as any).market.skills.listLiveTools = vi.fn().mockResolvedValue(liveResponse);
(service as any).market.skills.listTools = vi.fn().mockResolvedValue({ tools: [] });
- await expect(service.listSkillTools('posthog')).resolves.toBe(liveResponse);
+ await expect(service.listSkillTools('posthog')).resolves.toEqual({
+ ...liveResponse,
+ source: 'live',
+ });
expect((service as any).market.skills.listLiveTools).toHaveBeenCalledWith('posthog');
expect((service as any).market.skills.listTools).not.toHaveBeenCalled();
@@ -538,7 +541,10 @@ describe('MarketService', () => {
(service as any).market.skills.listLiveTools = vi.fn().mockRejectedValue(new Error('boom'));
(service as any).market.skills.listTools = vi.fn().mockResolvedValue(staticResponse);
- await expect(service.listSkillTools('posthog')).resolves.toBe(staticResponse);
+ await expect(service.listSkillTools('posthog')).resolves.toEqual({
+ ...staticResponse,
+ source: 'static',
+ });
expect((service as any).market.skills.listLiveTools).toHaveBeenCalledWith('posthog');
expect((service as any).market.skills.listTools).toHaveBeenCalledWith('posthog');
@@ -552,7 +558,10 @@ describe('MarketService', () => {
(service as any).market.skills.listLiveTools = vi.fn().mockResolvedValue({ tools: [] });
(service as any).market.skills.listTools = vi.fn().mockResolvedValue(staticResponse);
- await expect(service.listSkillTools('posthog')).resolves.toBe(staticResponse);
+ await expect(service.listSkillTools('posthog')).resolves.toEqual({
+ ...staticResponse,
+ source: 'static',
+ });
expect((service as any).market.skills.listTools).toHaveBeenCalledWith('posthog');
});
@@ -565,7 +574,10 @@ describe('MarketService', () => {
(service as any).market.skills.listLiveTools = vi.fn().mockResolvedValue(null);
(service as any).market.skills.listTools = vi.fn().mockResolvedValue(staticResponse);
- await expect(service.listSkillTools('posthog')).resolves.toBe(staticResponse);
+ await expect(service.listSkillTools('posthog')).resolves.toEqual({
+ ...staticResponse,
+ source: 'static',
+ });
expect((service as any).market.skills.listTools).toHaveBeenCalledWith('posthog');
});
diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.ts
index 3680087fdc5..e0b598fd19e 100644
--- a/apps/server/src/services/market/index.ts
+++ b/apps/server/src/services/market/index.ts
@@ -7,6 +7,7 @@ import pMap from 'p-map';
import { type TrustedClientUserInfo } from '@/libs/trusted-client';
import { generateTrustedClientToken, getTrustedClientTokenForSession } from '@/libs/trusted-client';
+import { redisService } from '@/server/services/redis';
import {
createSandboxStorageClient,
type SandboxStorageClient,
@@ -157,9 +158,16 @@ export class MarketService {
private readonly oauthProxyHeaders: Record<string, string>;
+ /**
+ * Who the cached skill tool lists belong to. A service built without a user
+ * (M2M credentials, a bare trusted token) has no scope and skips the cache.
+ */
+ private readonly skillCacheScope?: string;
+
constructor(options: MarketServiceOptions = {}) {
const { accessToken, userInfo, clientCredentials, trustedClientToken, ownerAccountId } =
options;
+ this.skillCacheScope = userInfo?.userId;
// Use provided trustedClientToken or generate from userInfo
const resolvedTrustedClientToken =
@@ -417,6 +425,32 @@ export class MarketService {
);
}
+ /**
+ * The live tool list of one connected skill, remembered per connection for
+ * ten minutes.
+ *
+ * Discovery runs on every send and `tools/live` is a round trip to the
+ * provider's MCP server (150ms for GitHub, up to a second for Notion) for
+ * an answer that changes when the provider ships tools, not per turn. The
+ * key carries the connection's identity (`createdAt`, provider user), so a
+ * re-connected skill starts from a fresh read; an empty or failed list is
+ * never remembered. The connection list itself stays live so a newly
+ * connected skill shows up on the next send.
+ */
+ private async listSkillToolsForConnection(
+ connection: { createdAt?: string; providerUserId?: string },
+ providerId: string,
+ ) {
+ const read = () =>
+ this.listSkillTools(providerId, { timeoutMs: LOBEHUB_SKILL_DISCOVERY_TIMEOUT_MS });
+ if (!this.skillCacheScope) return read();
+
+ return redisService.skillTools.remember(
+ { connection, providerId, userId: this.skillCacheScope },
+ read,
+ );
+ }
+
/**
* Call a skill tool
*/
@@ -825,9 +859,10 @@ export class MarketService {
const icon = (connection as any).icon;
const providerLabel = LOBEHUB_SKILL_PROVIDER_LABELS[providerId] || providerId;
- const { tools, instruction } = await this.listSkillTools(providerId, {
- timeoutMs: LOBEHUB_SKILL_DISCOVERY_TIMEOUT_MS,
- });
+ const { tools, instruction } = await this.listSkillToolsForConnection(
+ connection,
+ providerId,
+ );
if (!tools || tools.length === 0) return;
const manifest: LobeToolManifest = {
diff --git a/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.ts b/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.ts
index d2b917a12e2..517f272a453 100644
--- a/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.ts
+++ b/apps/server/src/services/market/listSkillToolsWithLiveFallback.test.ts
@@ -14,7 +14,10 @@ describe('listSkillToolsWithLiveFallback', () => {
listTools: vi.fn().mockResolvedValue({ tools: [] }),
};
- await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toBe(liveResponse);
+ await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toEqual({
+ ...liveResponse,
+ source: 'live',
+ });
expect(skills.listLiveTools).toHaveBeenCalledWith('posthog');
expect(skills.listTools).not.toHaveBeenCalled();
@@ -33,7 +36,7 @@ describe('listSkillToolsWithLiveFallback', () => {
await expect(
listSkillToolsWithLiveFallback(skills, 'posthog', onLiveDiscoveryError),
- ).resolves.toBe(staticResponse);
+ ).resolves.toEqual({ ...staticResponse, source: 'static' });
expect(onLiveDiscoveryError).toHaveBeenCalledWith(error);
expect(skills.listTools).toHaveBeenCalledWith('posthog');
@@ -48,7 +51,10 @@ describe('listSkillToolsWithLiveFallback', () => {
listTools: vi.fn().mockResolvedValue(staticResponse),
};
- await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toBe(staticResponse);
+ await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toEqual({
+ ...staticResponse,
+ source: 'static',
+ });
expect(skills.listTools).toHaveBeenCalledWith('posthog');
});
@@ -62,7 +68,10 @@ describe('listSkillToolsWithLiveFallback', () => {
listTools: vi.fn().mockResolvedValue(staticResponse),
};
- await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toBe(staticResponse);
+ await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toEqual({
+ ...staticResponse,
+ source: 'static',
+ });
expect(skills.listTools).toHaveBeenCalledWith('posthog');
});
@@ -75,7 +84,10 @@ describe('listSkillToolsWithLiveFallback', () => {
listTools: vi.fn().mockResolvedValue(staticResponse),
};
- await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toBe(staticResponse);
+ await expect(listSkillToolsWithLiveFallback(skills, 'posthog')).resolves.toEqual({
+ ...staticResponse,
+ source: 'static',
+ });
expect(skills.listTools).toHaveBeenCalledWith('posthog');
});
@@ -89,9 +101,9 @@ describe('listSkillToolsWithLiveFallback', () => {
listTools: vi.fn().mockResolvedValue(staticResponse),
};
- await expect(listSkillToolsWithLiveFallback(skills, 'posthog', undefined, 3000)).resolves.toBe(
- staticResponse,
- );
+ await expect(
+ listSkillToolsWithLiveFallback(skills, 'posthog', undefined, 3000),
+ ).resolves.toEqual({ ...staticResponse, source: 'static' });
const liveSignal = skills.listLiveTools.mock.calls[0][1]?.signal;
const staticSignal = skills.listTools.mock.calls[0][1]?.signal;
diff --git a/apps/server/src/services/market/listSkillToolsWithLiveFallback.ts b/apps/server/src/services/market/listSkillToolsWithLiveFallback.ts
index 37ad639a26b..e2718946cc2 100644
--- a/apps/server/src/services/market/listSkillToolsWithLiveFallback.ts
+++ b/apps/server/src/services/market/listSkillToolsWithLiveFallback.ts
@@ -3,6 +3,22 @@ export interface SkillToolsClient {
listTools: (providerId: string, options?: RequestInit) => Promise<any>;
}
+/** Which path produced a tool list: the provider's live probe, or the static catalog fallback. */
+export type SkillToolsDiscoverySource = 'live' | 'static';
+
+/**
+ * A provider's tool list plus the {@link SkillToolsDiscoverySource} it came from.
+ * The source rides along because a `static` answer is a substitute, not a real
+ * observation β€” a caller that caches the result must remember only a `live`
+ * answer and retry the fallback on the next call.
+ */
+export type SkillToolsDiscovery = {
+ /** Provider-authored usage notes, appended to the manifest's system role. */
+ instruction?: string;
+ source: SkillToolsDiscoverySource;
+ tools?: unknown[];
+} & Record<string, unknown>;
+
/**
* Each request gets its own timeout budget so a hanging live probe cannot
* starve the static fallback that follows it.
@@ -10,20 +26,30 @@ export interface SkillToolsClient {
const requestOptions = (timeoutMs?: number): [RequestInit] | [] =>
timeoutMs ? [{ signal: AbortSignal.timeout(timeoutMs) }] : [];
+/**
+ * Prefer the provider's live tool list, falling back to the static catalog when
+ * the live probe is unavailable, errors, times out, or returns no tools.
+ *
+ * The result always carries `source`, so a caller can tell a successful live
+ * probe from the fallback even when both return a nonempty tool list.
+ */
export const listSkillToolsWithLiveFallback = async (
skills: SkillToolsClient,
providerId: string,
onLiveDiscoveryError?: (error: unknown) => void,
timeoutMs?: number,
-) => {
+): Promise<SkillToolsDiscovery> => {
if (typeof skills.listLiveTools === 'function') {
try {
const response = await skills.listLiveTools(providerId, ...requestOptions(timeoutMs));
- if (Array.isArray(response?.tools) && response.tools.length > 0) return response;
+ if (Array.isArray(response?.tools) && response.tools.length > 0) {
+ return { ...response, source: 'live' };
+ }
} catch (error) {
onLiveDiscoveryError?.(error);
}
}
- return skills.listTools(providerId, ...requestOptions(timeoutMs));
+ const fallback = await skills.listTools(providerId, ...requestOptions(timeoutMs));
+ return { ...fallback, source: 'static' };
};
diff --git a/apps/server/src/services/onboardingProgress/index.ts b/apps/server/src/services/onboardingProgress/index.ts
index b685b5d85c0..0b68d9142b3 100644
--- a/apps/server/src/services/onboardingProgress/index.ts
+++ b/apps/server/src/services/onboardingProgress/index.ts
@@ -6,7 +6,7 @@ import type {
import { getServerDB } from '@/database/server';
import { getRedisConfig } from '@/envs/redis';
-import { isRedisEnabled } from '@/libs/redis';
+import { isRedisEnabled } from '@/server/modules/Redis';
import {
createTaskRecommendationService,
TaskRecommendationNotFoundError,
diff --git a/apps/server/src/services/redis/README.md b/apps/server/src/services/redis/README.md
new file mode 100644
index 00000000000..e0362cd5c82
--- /dev/null
+++ b/apps/server/src/services/redis/README.md
@@ -0,0 +1,24 @@
+# Redis business service
+
+Import `redisService` from `@/server/services/redis`. Domains expose business operations;
+callers do not choose a provider, prefix, key, SET options or claim lifetime.
+
+- `deviceSystemInfo.remember`: principal/device scoped answers, three minute default freshness;
+ callers may request a freshness bound through the existing gateway API.
+- `skillTools.remember`: connection scoped tool lists, ten minutes; empty/failed results are not cached.
+- `workspaceRescan.claim`: one background scan per principal/device/directory for 45 seconds.
+
+`client.ts` is the connection seam. All current domains share the existing `sendPathCache`
+connection and keyspace, preserving deployed cache/claim compatibility. A namespace is a key
+partition, not a reason to open another connection. Add a separate connection only for a
+transport requirement such as pub/sub or blocking commands. Client/provider code and its tests live in `apps/server/src/modules/Redis`.
+The service composes this infrastructure through domain methods.
+`cache.ts` holds the generic cache/claim policy (read-through caching, the atomic claim with its
+process-local fallback) internal to this directory: it is not re-exported, so callers cannot reach
+around the domain methods.
+The former `src/libs/redis` directory is removed without forwarding exports.
+Do not export transport primitives from the business service barrel.
+
+Existing raw-client and client-lib consumers remain explicit migration debt in ESLint.
+Move them domain by domain; runtime state requires a deployment/keyspace compatibility plan.
+This foundation does not migrate existing runtime, bot or OAuth stores.
diff --git a/apps/server/src/services/redis/cache.test.ts b/apps/server/src/services/redis/cache.test.ts
new file mode 100644
index 00000000000..956ee0bdb5f
--- /dev/null
+++ b/apps/server/src/services/redis/cache.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { BaseRedisProvider } from '@/server/modules/Redis/types';
+
+import { claimRedisOnce, readThroughRedis } from './cache';
+
+const fakeRedis = (overrides: Partial<BaseRedisProvider> = {}) =>
+ ({
+ get: vi.fn(async () => null),
+ set: vi.fn(async () => 'OK'),
+ ...overrides,
+ }) as unknown as BaseRedisProvider;
+
+describe('readThroughRedis', () => {
+ it('serves a remembered answer without calling read', async () => {
+ const redis = fakeRedis({ get: vi.fn(async () => JSON.stringify({ tools: ['a'] })) });
+ const read = vi.fn();
+
+ await expect(readThroughRedis(redis, 'k', read, { ttlMs: 1000 })).resolves.toEqual({
+ tools: ['a'],
+ });
+
+ expect(read).not.toHaveBeenCalled();
+ });
+
+ it('reads live on a miss and writes the answer back with the TTL', async () => {
+ const redis = fakeRedis();
+ const read = vi.fn(async () => ({ arch: 'arm64' }));
+
+ await expect(readThroughRedis(redis, 'k', read, { ttlMs: 1234 })).resolves.toEqual({
+ arch: 'arm64',
+ });
+
+ expect(read).toHaveBeenCalledTimes(1);
+ expect(redis.set).toHaveBeenCalledWith('k', JSON.stringify({ arch: 'arm64' }), { px: 1234 });
+ });
+
+ it('does not remember an undefined answer or one the caller rejects', async () => {
+ const redis = fakeRedis();
+
+ await readThroughRedis(redis, 'k', async () => undefined, { ttlMs: 1000 });
+ await readThroughRedis(redis, 'k', async () => ({ tools: [] as string[] }), {
+ shouldCache: (value) => value.tools.length > 0,
+ ttlMs: 1000,
+ });
+
+ expect(redis.set).not.toHaveBeenCalled();
+ });
+
+ it('falls through to the live read without a client or when Redis fails', async () => {
+ await expect(readThroughRedis(null, 'k', async () => 1, { ttlMs: 1000 })).resolves.toBe(1);
+
+ const failing = fakeRedis({
+ get: vi.fn(async () => {
+ throw new Error('ECONNRESET');
+ }),
+ });
+ await expect(readThroughRedis(failing, 'k', async () => 2, { ttlMs: 1000 })).resolves.toBe(2);
+ });
+
+ it('does not remember a live read that rejects', async () => {
+ const redis = fakeRedis();
+
+ await expect(
+ readThroughRedis(
+ redis,
+ 'k',
+ async () => {
+ throw new Error('upstream');
+ },
+ { ttlMs: 1000 },
+ ),
+ ).rejects.toThrow('upstream');
+
+ expect(redis.set).not.toHaveBeenCalled();
+ });
+});
+
+describe('claimRedisOnce', () => {
+ it('claims with SET NX and reports whether this caller won', async () => {
+ const redis = fakeRedis({
+ set: vi.fn().mockResolvedValueOnce('OK').mockResolvedValueOnce(null),
+ });
+
+ await expect(claimRedisOnce(redis, 'claim-win', 45_000)).resolves.toBe(true);
+ await expect(claimRedisOnce(redis, 'claim-win', 45_000)).resolves.toBe(false);
+
+ expect(redis.set).toHaveBeenCalledWith('claim-win', '1', { nx: true, px: 45_000 });
+ });
+
+ it('coalesces concurrent callers with a process-local claim when Redis is absent', async () => {
+ await expect(claimRedisOnce(null, 'claim-local', 45_000)).resolves.toBe(true);
+ await expect(claimRedisOnce(null, 'claim-local', 45_000)).resolves.toBe(false);
+ });
+
+ it('falls back to a process-local claim when the SET NX command fails', async () => {
+ // A memoized client can still reject commands (Redis went down). Rather
+ // than let every caller proceed, keep the in-process coalescing.
+ const redis = fakeRedis({ set: vi.fn().mockRejectedValue(new Error('redis down')) });
+
+ await expect(claimRedisOnce(redis, 'claim-fallback', 45_000)).resolves.toBe(true);
+ await expect(claimRedisOnce(redis, 'claim-fallback', 45_000)).resolves.toBe(false);
+ });
+});
diff --git a/apps/server/src/services/redis/cache.ts b/apps/server/src/services/redis/cache.ts
new file mode 100644
index 00000000000..d4a51405bf5
--- /dev/null
+++ b/apps/server/src/services/redis/cache.ts
@@ -0,0 +1,99 @@
+import { getJSONFromRedis, normalizeRedisKey } from '@/server/modules/Redis';
+import type { BaseRedisProvider, RedisKey } from '@/server/modules/Redis/types';
+
+// Generic cache/claim policy for the send-path domains. This lives inside the
+// service boundary (not `modules/Redis`, which is only the client/provider
+// layer) so it is not re-exported as a transport primitive callers can reach
+// around the domain methods. See AGENTS.md.
+
+export interface ReadThroughRedisOptions<T> {
+ /** Remember this answer? Defaults to remembering anything that is not `undefined`. */
+ shouldCache?: (value: T) => boolean;
+ /** How long a remembered answer stays valid. */
+ ttlMs: number;
+}
+
+/**
+ * Serve `read()` from Redis for `ttlMs`, falling back to the live read when
+ * the client is `null`, the key is missing, or Redis fails. Built for the
+ * repeated, slow-but-stable lookups of a hot path β€” answers that cost a
+ * network round trip and change on the order of minutes.
+ *
+ * Failure-tolerant on both sides: a Redis error degrades to the live read,
+ * and a live read that rejects is NOT remembered β€” the next caller retries.
+ * The write-back is fire-and-forget; the caller already has its answer.
+ * The key must already carry everything the answer depends on (see
+ * `RedisKeys`); this helper never derives it.
+ */
+export const readThroughRedis = async <T>(
+ redis: BaseRedisProvider | null,
+ key: RedisKey,
+ read: () => Promise<T>,
+ { shouldCache, ttlMs }: ReadThroughRedisOptions<T>,
+): Promise<T> => {
+ if (redis) {
+ try {
+ const hit = await getJSONFromRedis<T>(redis, key);
+ if (hit !== null) return hit;
+ } catch {
+ // Fall through to the live read.
+ }
+ }
+
+ const value = await read();
+ const cacheable = value !== undefined && (shouldCache ? shouldCache(value) : true);
+
+ if (redis && cacheable) {
+ void redis
+ .set(key, JSON.stringify(value), { px: Math.max(1, Math.round(ttlMs)) })
+ .catch(() => undefined);
+ }
+
+ return value;
+};
+
+/** Process-local claims, used when Redis cannot coordinate: key β†’ expiry (ms). */
+const localClaims = new Map<string, number>();
+
+const claimLocally = (key: RedisKey, ttlMs: number): boolean => {
+ const now = Date.now();
+ if (localClaims.size > 1000) {
+ for (const [k, expiresAt] of localClaims) if (expiresAt <= now) localClaims.delete(k);
+ }
+
+ const normalized = normalizeRedisKey(key);
+ const expiresAt = localClaims.get(normalized);
+ if (expiresAt && expiresAt > now) return false;
+
+ localClaims.set(normalized, now + ttlMs);
+ return true;
+};
+
+/**
+ * Claim the right to do one piece of work for `ttlMs`: the first caller gets
+ * `true`, every later caller with the same key gets `false` until the claim
+ * expires. Built for background refreshes that fan out from concurrent
+ * requests β€” one should do the work, the rest should not pile on.
+ *
+ * Atomic across instances through Redis `SET NX`. When Redis is unavailable β€”
+ * disabled, or a command that rejects after the client was memoized β€” the
+ * claim falls back to a process-local one: still enough to stop one instance
+ * scheduling the same 30s scan ten times, which is the common shape of a
+ * stampede. A claim is never released early: a successful refresh makes the
+ * next read fresh anyway, and a failed one is retried once the claim expires.
+ */
+export const claimRedisOnce = async (
+ redis: BaseRedisProvider | null,
+ key: RedisKey,
+ ttlMs: number,
+): Promise<boolean> => {
+ const ttl = Math.max(1, Math.round(ttlMs));
+ if (!redis) return claimLocally(key, ttl);
+
+ try {
+ const result = await redis.set(key, '1', { nx: true, px: ttl });
+ return result === 'OK';
+ } catch {
+ return claimLocally(key, ttl);
+ }
+};
diff --git a/apps/server/src/services/redis/client.test.ts b/apps/server/src/services/redis/client.test.ts
new file mode 100644
index 00000000000..dd6f500d56c
--- /dev/null
+++ b/apps/server/src/services/redis/client.test.ts
@@ -0,0 +1,121 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as RedisModule from '@/server/modules/Redis';
+
+const { mockGetRedisConfig, mockTryInitializeRedisWithPrefix } = vi.hoisted(() => ({
+ mockGetRedisConfig: vi.fn(),
+ mockTryInitializeRedisWithPrefix: vi.fn(),
+}));
+
+vi.mock('@/envs/redis', () => ({ getRedisConfig: mockGetRedisConfig }));
+
+vi.mock('@/server/modules/Redis', async (importOriginal) => ({
+ ...(await importOriginal<typeof RedisModule>()),
+ tryInitializeRedisWithPrefix: mockTryInitializeRedisWithPrefix,
+}));
+
+const enabledConfig = {
+ enabled: true,
+ prefix: 'lobe',
+ tls: false,
+ url: 'redis://localhost:6379',
+};
+
+// `cooldownUntil` lives at module scope, so each test gets a fresh module.
+const loadClient = async () => {
+ vi.resetModules();
+ return await import('./client');
+};
+
+beforeEach(() => {
+ mockGetRedisConfig.mockReset();
+ mockTryInitializeRedisWithPrefix.mockReset();
+});
+
+describe('getRedisServiceClient', () => {
+ it('skips Redis entirely when it is disabled', async () => {
+ mockGetRedisConfig.mockReturnValue({ enabled: false, prefix: 'lobe', tls: false, url: '' });
+ const { getRedisServiceClient } = await loadClient();
+
+ await expect(getRedisServiceClient()).resolves.toBeNull();
+ expect(mockTryInitializeRedisWithPrefix).not.toHaveBeenCalled();
+ });
+
+ it('returns the shared client and asks for the bounded timeouts', async () => {
+ const provider = { get: vi.fn().mockResolvedValue('value'), set: vi.fn() };
+ mockGetRedisConfig.mockReturnValue(enabledConfig);
+ mockTryInitializeRedisWithPrefix.mockResolvedValue(provider);
+ const { getRedisServiceClient } = await loadClient();
+
+ const client = await getRedisServiceClient();
+ expect(client).not.toBeNull();
+ await expect(client!.get('k')).resolves.toBe('value');
+
+ expect(mockTryInitializeRedisWithPrefix).toHaveBeenCalledWith(
+ expect.objectContaining({ commandTimeoutMs: 1000, connectTimeoutMs: 1000 }),
+ 'lobe:sendPathCache',
+ );
+ });
+
+ it('keeps REDIS_PREFIX so deployments sharing a Redis do not read each other', async () => {
+ mockTryInitializeRedisWithPrefix.mockResolvedValue({ get: vi.fn(), set: vi.fn() });
+
+ mockGetRedisConfig.mockReturnValue({ ...enabledConfig, prefix: 'staging' });
+ await (await loadClient()).getRedisServiceClient();
+ mockGetRedisConfig.mockReturnValue({ ...enabledConfig, prefix: 'production' });
+ await (await loadClient()).getRedisServiceClient();
+
+ expect(mockTryInitializeRedisWithPrefix.mock.calls.map(([, prefix]) => prefix)).toEqual([
+ 'staging:sendPathCache',
+ 'production:sendPathCache',
+ ]);
+ });
+
+ it('opens the circuit after a failed acquisition so later sends do not retry', async () => {
+ mockGetRedisConfig.mockReturnValue(enabledConfig);
+ mockTryInitializeRedisWithPrefix.mockResolvedValue(null);
+ const { getRedisServiceClient } = await loadClient();
+
+ await expect(getRedisServiceClient()).resolves.toBeNull();
+ await expect(getRedisServiceClient()).resolves.toBeNull();
+
+ expect(mockTryInitializeRedisWithPrefix).toHaveBeenCalledTimes(1);
+ });
+
+ it('bounds the wait when acquisition never settles and opens the circuit', async () => {
+ vi.useFakeTimers();
+ try {
+ mockGetRedisConfig.mockReturnValue(enabledConfig);
+ mockTryInitializeRedisWithPrefix.mockReturnValue(new Promise(() => {}));
+ const { getRedisServiceClient } = await loadClient();
+
+ const pending = getRedisServiceClient();
+ await vi.advanceTimersByTimeAsync(1500);
+ await expect(pending).resolves.toBeNull();
+
+ await expect(getRedisServiceClient()).resolves.toBeNull();
+ expect(mockTryInitializeRedisWithPrefix).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('opens the circuit when a command on the memoized client fails', async () => {
+ // Redis can go down after the provider is memoized; acquisition would keep
+ // returning it, so the command failure itself must trip the cooldown.
+ const provider = {
+ get: vi.fn().mockRejectedValue(new Error('redis down')),
+ set: vi.fn(),
+ };
+ mockGetRedisConfig.mockReturnValue(enabledConfig);
+ mockTryInitializeRedisWithPrefix.mockResolvedValue(provider);
+ const { getRedisServiceClient } = await loadClient();
+
+ const client = await getRedisServiceClient();
+ expect(client).not.toBeNull();
+ await expect(client!.get('k')).rejects.toThrow('redis down');
+
+ await expect(getRedisServiceClient()).resolves.toBeNull();
+ expect(mockTryInitializeRedisWithPrefix).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/redis/client.ts b/apps/server/src/services/redis/client.ts
new file mode 100644
index 00000000000..7a2d109f8d4
--- /dev/null
+++ b/apps/server/src/services/redis/client.ts
@@ -0,0 +1,92 @@
+import { getRedisConfig } from '@/envs/redis';
+import { RedisKeyNamespace, tryInitializeRedisWithPrefix } from '@/server/modules/Redis';
+import type { BaseRedisProvider } from '@/server/modules/Redis/types';
+
+// The send-path caches are an optimization layered on a hot path, so a send
+// must never wait long on Redis. This namespace opts into short provider
+// timeouts and bounds the wait for the shared client; after a failure it opens
+// a cooldown so an outage degrades every send straight to its live read
+// instead of re-paying the connect or a command timeout each time.
+const ACQUIRE_TIMEOUT_MS = 1500;
+const CONNECT_TIMEOUT_MS = 1000;
+const COMMAND_TIMEOUT_MS = 1000;
+const COOLDOWN_MS = 30_000;
+
+/** `Date.now()` until which the circuit stays open; 0 means closed. */
+let cooldownUntil = 0;
+
+const openCircuit = () => {
+ cooldownUntil = Date.now() + COOLDOWN_MS;
+};
+
+const withDeadline = async <T>(work: Promise<T>, ms: number): Promise<T | null> => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ work,
+ new Promise<null>((resolve) => {
+ timer = setTimeout(() => resolve(null), ms);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
+/**
+ * Report every rejected command to the circuit. A memoized client can outlive
+ * Redis: without this, acquisition keeps returning it and β€” unlike a failed
+ * connect β€” nothing would trip the cooldown, so each send would pay the
+ * command timeout before falling back to its live read.
+ */
+const observeFailures = (client: BaseRedisProvider): BaseRedisProvider =>
+ new Proxy(client, {
+ get(target, property, receiver) {
+ const value = Reflect.get(target, property, receiver);
+ if (typeof value !== 'function') return value;
+
+ return (...args: unknown[]) => {
+ const result = value.apply(target, args);
+ return result instanceof Promise
+ ? result.catch((error) => {
+ openCircuit();
+ throw error;
+ })
+ : result;
+ };
+ },
+ });
+
+/**
+ * The shared send-path-cache client, or `null` when Redis is unavailable and
+ * the caller should fall back to its live read.
+ *
+ * Never blocks for long: acquiring the client is bounded by
+ * {@link ACQUIRE_TIMEOUT_MS}, and any failure (or a disabled Redis) returns
+ * `null`. A failed acquisition, or a command that fails later on the memoized
+ * client, opens the circuit for {@link COOLDOWN_MS} so concurrent and later
+ * sends degrade straight to their live read.
+ */
+export const getRedisServiceClient = async (): Promise<BaseRedisProvider | null> => {
+ const config = getRedisConfig();
+ if (!config.enabled || Date.now() < cooldownUntil) return null;
+
+ const client = await withDeadline(
+ tryInitializeRedisWithPrefix(
+ { ...config, commandTimeoutMs: COMMAND_TIMEOUT_MS, connectTimeoutMs: CONNECT_TIMEOUT_MS },
+ // Compose with REDIS_PREFIX rather than replace it: deployments sharing
+ // one Redis isolate by prefix, and their user/device ids can collide.
+ config.prefix
+ ? `${config.prefix}:${RedisKeyNamespace.SEND_PATH_CACHE}`
+ : RedisKeyNamespace.SEND_PATH_CACHE,
+ ),
+ ACQUIRE_TIMEOUT_MS,
+ );
+
+ if (!client) {
+ openCircuit();
+ return null;
+ }
+
+ return observeFailures(client);
+};
diff --git a/apps/server/src/services/redis/deviceSystemInfo.ts b/apps/server/src/services/redis/deviceSystemInfo.ts
new file mode 100644
index 00000000000..4f94cccb0da
--- /dev/null
+++ b/apps/server/src/services/redis/deviceSystemInfo.ts
@@ -0,0 +1,25 @@
+import type { DeviceSystemInfo } from '@lobechat/device-gateway-client';
+
+import { RedisKeys } from '@/server/modules/Redis';
+
+import { readThroughRedis } from './cache';
+import { getRedisServiceClient } from './client';
+
+export const deviceSystemInfo = {
+ async remember(
+ scope: { deviceId: string; userId: string; workspaceId?: string },
+ fetch: () => Promise<DeviceSystemInfo | undefined>,
+ maxAgeMs = 3 * 60 * 1000,
+ ) {
+ return readThroughRedis(
+ await getRedisServiceClient(),
+ RedisKeys.sendPathCache.deviceSystemInfo(
+ scope.userId,
+ scope.workspaceId ?? 'personal',
+ scope.deviceId,
+ ),
+ fetch,
+ { ttlMs: maxAgeMs },
+ );
+ },
+};
diff --git a/apps/server/src/services/redis/index.test.ts b/apps/server/src/services/redis/index.test.ts
new file mode 100644
index 00000000000..6aea2019404
--- /dev/null
+++ b/apps/server/src/services/redis/index.test.ts
@@ -0,0 +1,71 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { redisService } from './index';
+
+const { get, set } = vi.hoisted(() => ({ get: vi.fn(), set: vi.fn() }));
+vi.mock('./client', () => ({ getRedisServiceClient: async () => ({ get, set }) }));
+
+describe('Redis domain service', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ get.mockResolvedValue(null);
+ set.mockResolvedValue('OK');
+ });
+
+ it('isolates device answers by principal pool and preserves the requested freshness', async () => {
+ const fetch = vi.fn().mockResolvedValue({ arch: 'arm64' });
+ await redisService.deviceSystemInfo.remember(
+ { deviceId: 'd', userId: 'u', workspaceId: 'w' },
+ fetch,
+ 1000,
+ );
+ expect(set).toHaveBeenCalledWith(
+ 'device_system_info:v1:u:w:d',
+ JSON.stringify({ arch: 'arm64' }),
+ { px: 1000 },
+ );
+ get.mockResolvedValue(JSON.stringify({ arch: 'arm64' }));
+ await redisService.deviceSystemInfo.remember(
+ { deviceId: 'd', userId: 'u', workspaceId: 'w' },
+ fetch,
+ );
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not retain empty or static skill discoveries and scopes successful reads to the connection', async () => {
+ const scope = {
+ connection: { createdAt: 'date', providerUserId: 'account' },
+ providerId: 'github',
+ userId: 'u',
+ };
+ await redisService.skillTools.remember(scope, async () => ({ source: 'live', tools: [] }));
+ expect(set).not.toHaveBeenCalled();
+ // The static fallback is served when the live probe failed; it must not be
+ // pinned for the TTL, or later sends stop retrying live discovery.
+ await redisService.skillTools.remember(scope, async () => ({
+ source: 'static',
+ tools: ['tool'],
+ }));
+ expect(set).not.toHaveBeenCalled();
+ await redisService.skillTools.remember(scope, async () => ({
+ source: 'live',
+ tools: ['tool'],
+ }));
+ expect(set).toHaveBeenCalledWith(
+ 'lobehub_skill_tools:v1:u:github:date|account',
+ JSON.stringify({ source: 'live', tools: ['tool'] }),
+ { px: 600_000 },
+ );
+ });
+
+ it('grants a rescan only to the winner of the atomic directory claim', async () => {
+ const scope = { cwd: '/project', deviceId: 'd', userId: 'u' };
+ expect(await redisService.workspaceRescan.claim(scope)).toBe(true);
+ set.mockResolvedValue(null);
+ expect(await redisService.workspaceRescan.claim(scope)).toBe(false);
+ expect(set).toHaveBeenCalledWith('workspace_rescan_claim:v1:u:personal:d:/project', '1', {
+ nx: true,
+ px: 45_000,
+ });
+ });
+});
diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.ts
new file mode 100644
index 00000000000..b94da093ac5
--- /dev/null
+++ b/apps/server/src/services/redis/index.ts
@@ -0,0 +1,6 @@
+import { deviceSystemInfo } from './deviceSystemInfo';
+import { skillTools } from './skillTools';
+import { workspaceRescan } from './workspaceRescan';
+
+/** Business Redis API. Providers, keys and expiry policy stay inside each domain. */
+export const redisService = { deviceSystemInfo, skillTools, workspaceRescan };
diff --git a/apps/server/src/services/redis/skillTools.ts b/apps/server/src/services/redis/skillTools.ts
new file mode 100644
index 00000000000..95d90c87c94
--- /dev/null
+++ b/apps/server/src/services/redis/skillTools.ts
@@ -0,0 +1,33 @@
+import { RedisKeys } from '@/server/modules/Redis';
+
+import { readThroughRedis } from './cache';
+import { getRedisServiceClient } from './client';
+
+export const skillTools = {
+ async remember<T extends { source?: string; tools?: unknown[] } | undefined>(
+ scope: {
+ connection: { createdAt?: string; providerUserId?: string };
+ providerId: string;
+ userId: string;
+ },
+ fetch: () => Promise<T>,
+ ): Promise<T> {
+ const identity = [scope.connection.createdAt ?? '', scope.connection.providerUserId ?? ''].join(
+ '|',
+ );
+ return readThroughRedis(
+ await getRedisServiceClient(),
+ RedisKeys.sendPathCache.lobehubSkillTools(scope.userId, scope.providerId, identity),
+ fetch,
+ {
+ // Only a successful live probe is worth remembering: the fallback
+ // (`source: 'static'`) is a cheap static catalog served when the live
+ // probe failed, and pinning it for the TTL would keep the next sends
+ // from retrying live discovery against the connection.
+ shouldCache: (value) =>
+ value?.source === 'live' && Array.isArray(value.tools) && value.tools.length > 0,
+ ttlMs: 10 * 60 * 1000,
+ },
+ );
+ },
+};
diff --git a/apps/server/src/services/redis/workspaceRescan.ts b/apps/server/src/services/redis/workspaceRescan.ts
new file mode 100644
index 00000000000..4a6a2ef4b86
--- /dev/null
+++ b/apps/server/src/services/redis/workspaceRescan.ts
@@ -0,0 +1,20 @@
+import { RedisKeys } from '@/server/modules/Redis';
+
+import { claimRedisOnce } from './cache';
+import { getRedisServiceClient } from './client';
+
+// Covers the 30 second scan timeout plus writeback. Claims expire rather than release early.
+export const workspaceRescan = {
+ async claim(scope: { cwd: string; deviceId: string; userId: string; workspaceId?: string }) {
+ return claimRedisOnce(
+ await getRedisServiceClient(),
+ RedisKeys.sendPathCache.workspaceRescanClaim(
+ scope.userId,
+ scope.workspaceId ?? 'personal',
+ scope.deviceId,
+ scope.cwd,
+ ),
+ 45 * 1000,
+ );
+ },
+};
diff --git a/apps/server/src/utils/scheduleAfterResponse.test.ts b/apps/server/src/utils/scheduleAfterResponse.test.ts
index f384f9769d2..d208869e90a 100644
--- a/apps/server/src/utils/scheduleAfterResponse.test.ts
+++ b/apps/server/src/utils/scheduleAfterResponse.test.ts
@@ -1,7 +1,12 @@
// @vitest-environment node
import { describe, expect, it } from 'vitest';
-import { after, flushScheduledWork, runWithScheduledWorkScope } from './scheduleAfterResponse';
+import {
+ after,
+ afterUnscoped,
+ flushScheduledWork,
+ runWithScheduledWorkScope,
+} from './scheduleAfterResponse';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -136,4 +141,24 @@ describe('scheduled work scope', () => {
it('is a no-op outside a scope', async () => {
await expect(flushScheduledWork()).resolves.toBe(true);
});
+
+ it('does not capture unscoped work, so a long refresh never holds a step-boundary flush', async () => {
+ let finished = false;
+
+ await runWithScheduledWorkScope(async () => {
+ afterUnscoped(async () => {
+ await sleep(80);
+ finished = true;
+ });
+
+ const startedAt = Date.now();
+ // Settled: the scope has nothing pending, the unscoped work is the host's.
+ await expect(flushScheduledWork({ timeoutMs: 10 })).resolves.toBe(true);
+ expect(Date.now() - startedAt).toBeLessThan(60);
+ expect(finished).toBe(false);
+ });
+
+ await sleep(100);
+ expect(finished).toBe(true);
+ });
});
diff --git a/apps/server/src/utils/scheduleAfterResponse.ts b/apps/server/src/utils/scheduleAfterResponse.ts
index 316d28ce284..2d17842b744 100644
--- a/apps/server/src/utils/scheduleAfterResponse.ts
+++ b/apps/server/src/utils/scheduleAfterResponse.ts
@@ -52,6 +52,21 @@ const drain = async (scope: ScheduledWorkScope) => {
}
};
+/**
+ * Like {@link after}, but never captured by a step's scheduled-work scope.
+ *
+ * Inside the inline step loop (`runStep`), `after()` work is collected and
+ * flushed at every step boundary with a short budget, because settlement
+ * there must land before the next step reserves again. Work that is neither
+ * part of the step's settlement nor bounded β€” a background rescan that may
+ * take tens of seconds β€” would stall that flush and push the continuation
+ * back onto the queue. Hand such work straight to the host instead: it still
+ * runs after the response, just not on the step's clock.
+ */
+export const afterUnscoped = (work: ScheduleAfterResponseWork): void => {
+ scheduleOnHost(() => runWork(work));
+};
+
export const after = (work: ScheduleAfterResponseWork): void => {
const scope = scopeStorage.getStore();
diff --git a/apps/server/src/workflows/runGuard/store.ts b/apps/server/src/workflows/runGuard/store.ts
index 37aa7338672..0e9f996996c 100644
--- a/apps/server/src/workflows/runGuard/store.ts
+++ b/apps/server/src/workflows/runGuard/store.ts
@@ -1,6 +1,6 @@
import debug from 'debug';
-import type { BaseRedisProvider } from '@/libs/redis/types';
+import type { BaseRedisProvider } from '@/server/modules/Redis/types';
import { WorkflowRunGuardError } from './errors';
import { buildWorkflowRunGuardKeys, buildWorkflowRunGuardRedisKey } from './keys';
diff --git a/eslint.config.mjs b/eslint.config.mjs
index ed48b16bfa9..f4c2e8c43e4 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -158,6 +158,96 @@ const browserRuntimeRestrictedImportPatterns = [
},
];
+// Business code uses domain methods in services/redis. The client lib is infrastructure.
+// Existing consumers are migration debt; this list only shrinks.
+const redisAccessRestrictedImportPaths = [
+ {
+ message:
+ 'Redis service connections are internal. Use domain methods from @/server/services/redis.',
+ name: '@/server/services/redis/client',
+ },
+ {
+ allowTypeImports: true,
+ message:
+ 'Redis client access belongs inside services/redis. Use a domain method or add one there.',
+ name: '@/server/modules/Redis',
+ },
+ {
+ allowTypeImports: true,
+ message:
+ 'Server code must not open its own ioredis client. Use domain methods in "@/server/services/redis"; add missing business capabilities there.',
+ name: 'ioredis',
+ },
+ {
+ message:
+ 'The raw agent-runtime Redis client is legacy. New code uses domain methods in "@/server/services/redis".',
+ name: '@/server/modules/AgentRuntime/redis',
+ },
+];
+const redisAccessRestrictedSyntax = [
+ {
+ message:
+ 'Server code must not open its own ioredis client, not even lazily. Use "@/server/services/redis".',
+ selector: "ImportExpression > Literal[value='ioredis']",
+ },
+ {
+ message: 'Redis client access belongs inside services/redis.',
+ selector: 'ImportExpression > Literal[value=/^@\\/server\\/modules\\/Redis(?:\\/|$)/]',
+ },
+];
+const legacyRawRedisClientConsumers = [
+ 'apps/server/src/services/home/index.ts',
+ 'apps/server/src/services/agent/index.ts',
+ 'apps/server/src/services/file/impls/s3.ts',
+ 'apps/server/src/services/generation/latency.ts',
+ 'apps/server/src/workflows/runGuard/store.ts',
+ 'apps/server/src/runtimeConfig/providers/RedisRuntimeConfigProvider.ts',
+ 'apps/server/src/router-hono/workflows/memory-user-memory/workflows/runGuard.ts',
+ 'apps/server/src/modules/AgentRuntime/redis.ts',
+ 'apps/server/src/modules/AgentRuntime/AgentStateManager.ts',
+ 'apps/server/src/modules/AgentRuntime/StreamEventManager.ts',
+ 'apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts',
+ 'apps/server/src/modules/AgentRuntime/dispatchClientTool.ts',
+ 'apps/server/src/modules/AgentRuntime/factory.ts',
+ 'apps/server/src/router-hono/agent/handlers/gatewayCron.ts',
+ 'apps/server/src/router-hono/agent/handlers/llmRelay.ts',
+ 'apps/server/src/router-hono/agent/handlers/toolResult.ts',
+ 'apps/server/src/router-hono/webhooks/handlers/github.ts',
+ 'apps/server/src/routers/lambda/messenger.ts',
+ 'apps/server/src/services/agentRuntime/opportunisticSweep.ts',
+ 'apps/server/src/services/agentSignal/store/adapters/redis/shared.ts',
+ 'apps/server/src/services/bot/BotCallbackService.ts',
+ 'apps/server/src/services/bot/BotMessageRouter.ts',
+ 'apps/server/src/services/bot/deferredMessages.ts',
+ 'apps/server/src/services/bot/platforms/discord/chatComposition.ts',
+ 'apps/server/src/services/bot/platforms/feishu/chatComposition.ts',
+ 'apps/server/src/services/bot/platforms/feishu/reactionTracker.ts',
+ 'apps/server/src/services/bot/platforms/telegram/guestSession.ts',
+ 'apps/server/src/services/bot/platforms/wechat/service.ts',
+ 'apps/server/src/services/bot/reactionState.ts',
+ 'apps/server/src/services/connector/stateStore.ts',
+ 'apps/server/src/services/editLock/index.ts',
+ 'apps/server/src/services/gateway/GatewayManager.ts',
+ 'apps/server/src/services/gateway/botConnectQueue.ts',
+ 'apps/server/src/services/gateway/runtimeStatus.ts',
+ 'apps/server/src/services/messenger/MessengerRouter.ts',
+ 'apps/server/src/services/messenger/installations/wechat.ts',
+ 'apps/server/src/services/messenger/linkTokenStore.ts',
+ 'apps/server/src/services/messenger/oauth/stateStore.ts',
+ 'apps/server/src/services/messenger/platforms/linq/webhook.ts',
+ 'apps/server/src/services/messenger/platforms/wechat/binder.ts',
+ 'apps/server/src/services/messenger/wechatPush.ts',
+ 'apps/server/src/services/messenger/wechatQrSessionStore.ts',
+ 'apps/server/src/services/onboardingProgress/index.ts',
+ 'apps/server/src/services/resourceEvents/index.ts',
+ 'apps/server/src/services/scm/ScmControlService.ts',
+ 'apps/server/src/services/scm/oauth/stateStore.ts',
+ 'apps/server/src/services/taskResultBridge/redisStore.ts',
+ 'apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts',
+ 'apps/server/src/services/toolExecution/serverRuntimes/message/index.ts',
+ 'apps/server/src/services/understanding/sourceStore.ts',
+];
+
const createRestrictedImportRule = ({ paths = [], patterns, serverSide = false } = {}) => [
'error',
{
@@ -613,6 +703,44 @@ export default eslint(
],
},
},
+ {
+ // Redis access boundary for server code (see `redisAccessRestrictedImportPaths`).
+ files: ['apps/server/src/**/*.{ts,tsx}'],
+ // Tests of the legacy consumers import the raw module to mock or seed it;
+ // the boundary is about production code paths.
+ ignores: [
+ ...legacyRawRedisClientConsumers,
+ 'apps/server/src/services/redis/**',
+ 'apps/server/src/modules/Redis/**',
+ '**/*.test.{ts,tsx}',
+ '**/__tests__/**',
+ ],
+ rules: {
+ 'no-restricted-imports': [
+ 'error',
+ {
+ ...baseRestrictedImportOptions,
+ paths: [
+ ...(baseRestrictedImportOptions.paths ?? []),
+ ...redisAccessRestrictedImportPaths,
+ ],
+ patterns: [
+ ...(baseRestrictedImportOptions.patterns ?? []),
+ {
+ group: ['@/server/modules/Redis/*'],
+ message: 'Use domain methods in services/redis.',
+ },
+ ],
+ },
+ ],
+ 'no-restricted-syntax': [
+ 'error',
+ ...useRefLazyInitRestrictedSyntax,
+ ...uppercaseRestrictedSyntax,
+ ...redisAccessRestrictedSyntax,
+ ],
+ },
+ },
{
files: [
'apps/desktop/src/overlay/**/*.{ts,tsx}',
diff --git a/package.json b/package.json
index 953444ce067..b4f2076c5ad 100644
--- a/package.json
+++ b/package.json
@@ -108,7 +108,7 @@
"lint:md": "remark . --silent --output",
"lint:mdx": "npm run workflow:mdx && remark \"docs/**/*.mdx\" -r ./.remarkrc.mdx.mjs --silent --output && eslint \"docs/**/*.mdx\" --quiet --fix",
"lint:style": "stylelint \"{src,tests}/**/*.{js,jsx,ts,tsx}\" --fix",
- "lint:ts": "eslint src/ tests/ --concurrency=auto",
+ "lint:ts": "eslint src/ tests/ apps/server/src/ --concurrency=auto",
"lint:unused": "knip --include files,exports,types,enumMembers,duplicates",
"prepare": "git rev-parse --git-dir > /dev/null 2>&1 && git config core.hooksPath .githooks || true",
"prettier": "prettier -c --write \"**/**\"",
diff --git a/packages/types/src/redis.ts b/packages/types/src/redis.ts
index b3d0dd5af8b..93e26293671 100644
--- a/packages/types/src/redis.ts
+++ b/packages/types/src/redis.ts
@@ -6,4 +6,12 @@ export type RedisConfig = {
tls: boolean;
url: string;
username?: string;
+ /**
+ * Per-command timeout in milliseconds. Defaults to the provider's own bound
+ * (10s) when unset. Best-effort callers on a hot path may set it shorter so a
+ * stalled client degrades to their fallback promptly instead of blocking.
+ */
+ commandTimeoutMs?: number;
+ /** Connection timeout in milliseconds. Defaults to the provider's own bound (10s) when unset. */
+ connectTimeoutMs?: number;
};
diff --git a/src/libs/better-auth/utils/config.test.ts b/src/libs/better-auth/utils/config.test.ts
index 54ff67097c2..0b733e8107b 100644
--- a/src/libs/better-auth/utils/config.test.ts
+++ b/src/libs/better-auth/utils/config.test.ts
@@ -11,7 +11,7 @@ const mocks = vi.hoisted(() => ({
vi.mock('@/envs/app', () => ({ appEnv: mocks.appEnv }));
vi.mock('@/envs/auth', () => ({ authEnv: mocks.authEnv }));
vi.mock('@/envs/redis', () => ({ getRedisConfig: vi.fn() }));
-vi.mock('@/libs/redis', () => ({
+vi.mock('@/server/modules/Redis', () => ({
initializeRedis: vi.fn(),
isRedisEnabled: vi.fn(() => false),
}));
diff --git a/src/libs/better-auth/utils/config.ts b/src/libs/better-auth/utils/config.ts
index 71c1b18f957..7ccf7cb4950 100644
--- a/src/libs/better-auth/utils/config.ts
+++ b/src/libs/better-auth/utils/config.ts
@@ -2,7 +2,7 @@ import assetLinks from '@/../public/.well-known/assetlinks.json';
import { appEnv } from '@/envs/app';
import { authEnv } from '@/envs/auth';
import { getRedisConfig } from '@/envs/redis';
-import { initializeRedis, isRedisEnabled } from '@/libs/redis';
+import { initializeRedis, isRedisEnabled } from '@/server/modules/Redis';
import { isDev } from '@/utils/env';
const APPLE_TRUSTED_ORIGIN = 'https://appleid.apple.com';