Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(hetero): show Claude Code project memory in the workspace panel (#21234)

Lobehub Coder2b7fd72abf43
diff --git a/apps/desktop/src/main/controllers/WorkspaceCtr.ts b/apps/desktop/src/main/controllers/WorkspaceCtr.ts
index fc1307ae579..0e8ec4ea70c 100644
--- a/apps/desktop/src/main/controllers/WorkspaceCtr.ts
+++ b/apps/desktop/src/main/controllers/WorkspaceCtr.ts
@@ -1,4 +1,8 @@
-import type { WorkspaceScanDeps } from '@lobechat/device-control';
+import type {
+ ListClaudeCodeMemoryParams,
+ ListClaudeCodeMemoryResult,
+ WorkspaceScanDeps,
+} from '@lobechat/device-control';
import {
type InitWorkspaceParams,
type InitWorkspaceResult,
@@ -35,6 +39,16 @@ export default class WorkspaceCtr extends ControllerModule {
return runListProjectSkills(params, this.scanDeps);
}
+ /** Claude Code's auto-memory files for a project (`~/.claude/projects/<key>/memory`). */
+ @IpcMethod()
+ async listClaudeCodeMemory(
+ params: ListClaudeCodeMemoryParams,
+ ): Promise<ListClaudeCodeMemoryResult> {
+ const { listClaudeCodeMemory: runListClaudeCodeMemory } =
+ await import('@lobechat/device-control/claude-code-memory');
+ return runListClaudeCodeMemory(params, this.scanDeps);
+ }
+
@IpcMethod()
async initWorkspace(params: InitWorkspaceParams): Promise<InitWorkspaceResult> {
const { initWorkspace: runInitWorkspace } = await import('@lobechat/device-control/workspace');
diff --git a/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.ts
index 3db29b25adc..7abf09e5f57 100644
--- a/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.ts
@@ -4,8 +4,9 @@ import { type App } from '@/core/App';
import WorkspaceCtr from '../WorkspaceCtr';
-const { ipcMainHandleMock } = vi.hoisted(() => ({
+const { ipcMainHandleMock, listClaudeCodeMemoryMock } = vi.hoisted(() => ({
ipcMainHandleMock: vi.fn(),
+ listClaudeCodeMemoryMock: vi.fn(),
}));
vi.mock('electron', () => ({
@@ -19,6 +20,10 @@ vi.mock('node:fs/promises', () => ({
readdir: vi.fn(),
}));
+vi.mock('@lobechat/device-control/claude-code-memory', () => ({
+ listClaudeCodeMemory: listClaudeCodeMemoryMock,
+}));
+
vi.mock('@lobechat/local-file-shell', () => ({
detectRepoType: vi.fn(async () => undefined),
}));
@@ -222,4 +227,22 @@ describe('WorkspaceCtr', () => {
expect(result).toEqual({ root: '/proj', skills: [], source: null });
});
});
+
+ describe('listClaudeCodeMemory', () => {
+ it('approves the memory directory for the preview protocol', async () => {
+ const memoryDir = '/device-home/.claude/projects/-proj/memory';
+ listClaudeCodeMemoryMock.mockImplementation(async (_params, deps) => {
+ await deps.approveProjectRoot(memoryDir);
+ return { files: [], memoryDir };
+ });
+
+ const result = await workspaceCtr.listClaudeCodeMemory({ scope: '/proj' });
+
+ expect(result).toEqual({ files: [], memoryDir });
+ expect(listClaudeCodeMemoryMock).toHaveBeenCalledWith({ scope: '/proj' }, expect.anything());
+ expect(mockLocalFileProtocolManager.approveIndexedProjectRoot).toHaveBeenCalledWith(
+ memoryDir,
+ );
+ });
+ });
});
diff --git a/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.ts b/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.ts
index 274e08c16fd..d8dbe33e53b 100644
--- a/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/deviceProjectFiles.test.ts
@@ -9,6 +9,8 @@ const mocks = vi.hoisted(() => ({
createProjectDirectory: vi.fn(),
createProjectFile: vi.fn(),
findByDeviceId: vi.fn(),
+ getAgentAgencyConfig: vi.fn(),
+ listClaudeCodeMemory: vi.fn(),
moveProjectFiles: vi.fn(),
renameProjectFile: vi.fn(),
trashProjectFiles: vi.fn(),
@@ -32,6 +34,11 @@ vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOrigina
});
vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: class {
+ getAgentAgencyConfig = mocks.getAgentAgencyConfig;
+ },
+}));
vi.mock('@/database/models/device', () => ({
DeviceModel: class {
findByDeviceId = mocks.findByDeviceId;
@@ -43,6 +50,7 @@ vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({
copyProjectFiles: mocks.copyProjectFiles,
createProjectDirectory: mocks.createProjectDirectory,
createProjectFile: mocks.createProjectFile,
+ listClaudeCodeMemory: mocks.listClaudeCodeMemory,
moveProjectFiles: mocks.moveProjectFiles,
renameProjectFile: mocks.renameProjectFile,
trashProjectFiles: mocks.trashProjectFiles,
@@ -117,3 +125,133 @@ describe('device project file mutations', () => {
expect(mocks[route]).not.toHaveBeenCalled();
});
});
+
+describe('device listClaudeCodeMemory', () => {
+ const memoryDir = '/Users/me/.claude/projects/-Users-me-proj/memory';
+ const memoryFile = `${memoryDir}/MEMORY.md`;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findByDeviceId.mockResolvedValue({ workingDirs: [{ path: '/Users/me/proj' }] });
+ mocks.writeProjectFile.mockResolvedValue({ success: true });
+ });
+
+ it('refuses a project root the device never approved', async () => {
+ await expect(
+ caller().listClaudeCodeMemory({ deviceId: 'dev-mem-1', workingDirectory: '/' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mocks.listClaudeCodeMemory).not.toHaveBeenCalled();
+ });
+
+ it('approves the listed memory directory so its files can be saved', async () => {
+ const write = () =>
+ caller().writeProjectFile({
+ content: 'x',
+ deviceId: 'dev-mem-2',
+ path: memoryFile,
+ workingDirectory: memoryDir,
+ });
+ await expect(write()).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ mocks.listClaudeCodeMemory.mockResolvedValue({
+ files: [{ isIndex: true, name: 'MEMORY', path: memoryFile, relativePath: 'MEMORY.md' }],
+ memoryDir,
+ });
+ await caller().listClaudeCodeMemory({ ...base, deviceId: 'dev-mem-2' });
+
+ expect(mocks.listClaudeCodeMemory).toHaveBeenCalledWith({
+ deviceId: 'dev-mem-2',
+ scope: '/Users/me/proj',
+ userId: 'user-1',
+ workspaceId: undefined,
+ });
+ await expect(write()).resolves.toEqual({ success: true });
+ });
+
+ it('leaves an empty memory directory unapproved', async () => {
+ mocks.listClaudeCodeMemory.mockResolvedValue({ files: [], memoryDir });
+ await caller().listClaudeCodeMemory({ ...base, deviceId: 'dev-mem-3' });
+
+ await expect(
+ caller().writeProjectFile({
+ content: 'x',
+ deviceId: 'dev-mem-3',
+ path: memoryFile,
+ workingDirectory: memoryDir,
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('revokes the memory directory once its project is no longer approved', async () => {
+ mocks.listClaudeCodeMemory.mockResolvedValue({
+ files: [{ isIndex: true, name: 'MEMORY', path: memoryFile, relativePath: 'MEMORY.md' }],
+ memoryDir,
+ });
+ await caller().listClaudeCodeMemory({ ...base, deviceId: 'dev-mem-5' });
+ const write = () =>
+ caller().writeProjectFile({
+ content: 'x',
+ deviceId: 'dev-mem-5',
+ path: memoryFile,
+ workingDirectory: memoryDir,
+ });
+ await expect(write()).resolves.toEqual({ success: true });
+
+ mocks.findByDeviceId.mockResolvedValue({ workingDirs: [{ path: '/Users/me/other' }] });
+
+ await expect(write()).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('never approves a memory directory that contains the project', async () => {
+ mocks.listClaudeCodeMemory.mockResolvedValue({
+ files: [
+ { isIndex: false, name: 'notes', path: '/Users/me/notes.md', relativePath: 'notes.md' },
+ ],
+ memoryDir: '/Users/me',
+ });
+ await caller().listClaudeCodeMemory({ ...base, deviceId: 'dev-mem-6' });
+
+ await expect(
+ caller().writeProjectFile({
+ content: 'x',
+ deviceId: 'dev-mem-6',
+ path: '/Users/me/.ssh/config',
+ workingDirectory: '/Users/me',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mocks.writeProjectFile).not.toHaveBeenCalled();
+ });
+
+ it("forwards the agent's stored Claude Code config dir, not one from the request", async () => {
+ mocks.getAgentAgencyConfig.mockResolvedValue({
+ heterogeneousProvider: {
+ env: { CLAUDE_CONFIG_DIR: '/Users/me/.claude-work', OTHER: 'x' },
+ type: 'claude-code',
+ },
+ });
+ mocks.listClaudeCodeMemory.mockResolvedValue({ files: [], memoryDir });
+
+ await caller().listClaudeCodeMemory({
+ ...base,
+ agentId: 'agent-1',
+ deviceId: 'dev-mem-7',
+ env: { CLAUDE_CONFIG_DIR: '/' },
+ } as never);
+
+ expect(mocks.getAgentAgencyConfig).toHaveBeenCalledWith('agent-1');
+ expect(mocks.listClaudeCodeMemory).toHaveBeenCalledWith({
+ deviceId: 'dev-mem-7',
+ env: { CLAUDE_CODE_PROJECT_DIR_NAME: undefined, CLAUDE_CONFIG_DIR: '/Users/me/.claude-work' },
+ scope: '/Users/me/proj',
+ userId: 'user-1',
+ workspaceId: undefined,
+ });
+ });
+
+ it('returns null when the device is offline', async () => {
+ mocks.listClaudeCodeMemory.mockResolvedValue(undefined);
+ await expect(
+ caller().listClaudeCodeMemory({ ...base, deviceId: 'dev-mem-4' }),
+ ).resolves.toBeNull();
+ });
+});
diff --git a/apps/server/src/routers/lambda/device/index.procedures.test.ts b/apps/server/src/routers/lambda/device/index.procedures.test.ts
index 87f92ddd317..40ccfdcf571 100644
--- a/apps/server/src/routers/lambda/device/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/device/index.procedures.test.ts
@@ -62,6 +62,7 @@ function expected(): Array<
['gitPullRequestMergeContext', 'query', 12],
['gitWorkingTreeStatus', 'query', 12],
['installAppUpdate', 'mutation', 12],
+ ['listClaudeCodeMemory', 'query', 14],
['listDevices', 'query', 11],
['listGitBranches', 'query', 12],
['listGitRemoteBranches', 'query', 12],
diff --git a/apps/server/src/routers/lambda/device/projectFiles.ts b/apps/server/src/routers/lambda/device/projectFiles.ts
index e7e4bf93a4d..d4f5a00db8c 100644
--- a/apps/server/src/routers/lambda/device/projectFiles.ts
+++ b/apps/server/src/routers/lambda/device/projectFiles.ts
@@ -2,10 +2,16 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { requireWorkspaceRoleWhenScoped } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AgentModel } from '@/database/models/agent';
+import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { deviceGateway, isValidDirectoryName } from '@/server/services/deviceGateway';
-import { assertWorkspaceRootApproved, registerDeviceSkillRoots } from '../deviceWorkspaceGuard';
+import {
+ assertWorkspaceRootApproved,
+ registerDeviceMemoryRoot,
+ registerDeviceSkillRoots,
+} from '../deviceWorkspaceGuard';
import { assertDeviceOperable } from './guards';
import { deviceProcedure } from './procedures';
@@ -51,6 +57,28 @@ const workspacePublishProcedure = workspaceFileProcedure.use(
requireWorkspaceRoleWhenScoped('member'),
);
+/**
+ * The agent's own `CLAUDE_CONFIG_DIR` / `CLAUDE_CODE_PROJECT_DIR_NAME`, which its
+ * runs spread over the device env. Read from the stored agent config, never the
+ * request: the memory directory they point at becomes an approved root.
+ */
+const resolveAgentClaudeMemoryEnv = async (
+ ctx: { serverDB: LobeChatDatabase; userId: string; workspaceId?: string },
+ agentId: string,
+) => {
+ const agencyConfig = await new AgentModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).getAgentAgencyConfig(agentId);
+ const env = agencyConfig?.heterogeneousProvider?.env;
+ if (!env) return undefined;
+ return {
+ CLAUDE_CODE_PROJECT_DIR_NAME: env.CLAUDE_CODE_PROJECT_DIR_NAME,
+ CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR,
+ };
+};
+
export const projectFilesRouter = router({
/**
* Project file index (tree) for a directory on a remote device, via the
@@ -261,6 +289,34 @@ export const projectFilesRouter = router({
return result ?? null;
}),
/**
+ * Claude Code's auto memory for a project on a remote device, via the
+ * device's `listClaudeCodeMemory` RPC. Powers the workspace panel's Memory
+ * tab in device mode; `agentId` applies that agent's own Claude Code config
+ * dir. The project must be an approved root; the memory directory it maps to
+ * is then approved for preview and save while the project stays approved.
+ * Returns `null` when offline.
+ */
+ listClaudeCodeMemory: workspaceFileProcedure
+ .input(z.object({ agentId: z.string().optional() }))
+ .query(async ({ ctx, input }) => {
+ const result = await deviceGateway.listClaudeCodeMemory({
+ deviceId: input.deviceId,
+ env: input.agentId ? await resolveAgentClaudeMemoryEnv(ctx, input.agentId) : undefined,
+ scope: input.workingDirectory,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ if (result?.memoryDir && result.files.length > 0) {
+ registerDeviceMemoryRoot(input.deviceId, {
+ memoryDir: result.memoryDir,
+ projectRoot: input.workingDirectory,
+ });
+ }
+
+ return result ?? null;
+ }),
+ /**
* Move files/folders within a directory on a remote device, via the device's
* `moveLocalFiles` RPC. Powers the Files tree's drag-to-move in device mode.
*/
diff --git a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
index e748676b84d..40fa6e121c7 100644
--- a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
+++ b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
@@ -48,12 +48,55 @@ export const registerDeviceSkillRoots = (deviceId: string, roots: string[]) => {
deviceSkillRoots.set(deviceId, new Set(roots));
};
-const isWithinSkillRoots = (deviceId: string, workingDirectory: string): boolean => {
- const roots = deviceSkillRoots.get(deviceId);
- if (!roots) return false;
- return [...roots].some((root) => isPathWithinRoot(root, workingDirectory));
+/**
+ * Claude Code auto-memory directories (`~/.claude/projects/<key>/memory`),
+ * registered by `listClaudeCodeMemory` once the caller proved the project
+ * itself is an approved root, so the Memory tab can preview and save them.
+ * Each grant keeps the project it was derived from and holds only while that
+ * project is still approved: removing the project from the device's working
+ * directories revokes its memory too. Accumulates per device (one per project
+ * and memory directory), oldest evicted past the cap.
+ */
+const MAX_MEMORY_ROOTS_PER_DEVICE = 50;
+
+interface DeviceMemoryRootGrant {
+ memoryDir: string;
+ /** The approved working directory the memory was listed for. */
+ projectRoot: string;
+}
+
+const deviceMemoryRoots = new Map<string, Map<string, DeviceMemoryRootGrant>>();
+
+export const registerDeviceMemoryRoot = (deviceId: string, grant: DeviceMemoryRootGrant) => {
+ const { memoryDir, projectRoot } = grant;
+ // A memory directory that covers its own project (a repository setting
+ // pointing `autoMemoryDirectory` at `~` or `/`) would widen the project's
+ // grant to the whole tree.
+ if (!memoryDir || !projectRoot || isPathWithinRoot(memoryDir, projectRoot)) return;
+
+ const grants = deviceMemoryRoots.get(deviceId) ?? new Map<string, DeviceMemoryRootGrant>();
+ const key = JSON.stringify([projectRoot, memoryDir]);
+ grants.delete(key);
+ grants.set(key, { memoryDir, projectRoot });
+ if (grants.size > MAX_MEMORY_ROOTS_PER_DEVICE) grants.delete(grants.keys().next().value!);
+ deviceMemoryRoots.set(deviceId, grants);
};
+const isWithinSkillRoots = (deviceId: string, workingDirectory: string): boolean =>
+ [...(deviceSkillRoots.get(deviceId) ?? [])].some((root) =>
+ isPathWithinRoot(root, workingDirectory),
+ );
+
+const isWithinMemoryGrant = (
+ deviceId: string,
+ workingDirectory: string,
+ isProjectApproved: (projectRoot: string) => boolean,
+): boolean =>
+ [...(deviceMemoryRoots.get(deviceId)?.values() ?? [])].some(
+ ({ memoryDir, projectRoot }) =>
+ isPathWithinRoot(memoryDir, workingDirectory) && isProjectApproved(projectRoot),
+ );
+
/**
* Validate that a client-supplied workspace root is actually one the user has
* bound to this device.
@@ -99,9 +142,12 @@ export const assertWorkspaceRootApproved = async (
.concat(device?.defaultCwd ? [device.defaultCwd] : [])
.filter((root): root is string => Boolean(root));
+ const isApprovedRoot = (target: string) =>
+ approvedRoots.some((root) => isPathWithinRoot(root, target));
const approved =
- approvedRoots.some((root) => isPathWithinRoot(root, workingDirectory)) ||
- isWithinSkillRoots(deviceId, workingDirectory);
+ isApprovedRoot(workingDirectory) ||
+ isWithinSkillRoots(deviceId, workingDirectory) ||
+ isWithinMemoryGrant(deviceId, workingDirectory, isApprovedRoot);
if (!approved) {
throw new TRPCError({
diff --git a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts b/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts
index 0e82469dc92..931b27a6588 100644
--- a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts
+++ b/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts
@@ -377,6 +377,13 @@ const cases: RpcCase[] = [
name: 'listProjectSkills',
payload: { method: 'listProjectSkills', params: { scope: '/p' } },
},
+ {
+ address: address(30_000),
+ call: (g) => g.listClaudeCodeMemory({ ...base, scope: '/p' }),
+ failure: UNDEFINED,
+ name: 'listClaudeCodeMemory',
+ payload: { method: 'listClaudeCodeMemory', params: { scope: '/p' } },
+ },
{
address: address(30_000),
call: (g) =>
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 847044d5d25..fab31fda2d6 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -401,6 +401,10 @@ export class DeviceGateway {
return projectFiles.listProjectSkills(this.clientGetter, ...args);
}
+ listClaudeCodeMemory(...args: DeviceRpcArgs<typeof projectFiles.listClaudeCodeMemory>) {
+ return projectFiles.listClaudeCodeMemory(this.clientGetter, ...args);
+ }
+
listGitRemoteBranches(...args: DeviceRpcArgs<typeof gitRead.listGitRemoteBranches>) {
return gitRead.listGitRemoteBranches(this.clientGetter, ...args);
}
diff --git a/apps/server/src/services/deviceGateway/projectFiles.ts b/apps/server/src/services/deviceGateway/projectFiles.ts
index 6df0a3118e0..0ba028dea1e 100644
--- a/apps/server/src/services/deviceGateway/projectFiles.ts
+++ b/apps/server/src/services/deviceGateway/projectFiles.ts
@@ -3,9 +3,11 @@
* skills) and publish-asset copies.
*/
import type {
+ DeviceClaudeCodeMemoryRunEnv,
DeviceCopyAssetForPublishResult,
DeviceDirectoryBrowseResult,
DeviceExternalAssetForPublishResult,
+ DeviceListClaudeCodeMemoryResult,
DeviceListProjectSkillsResult,
DeviceLocalFilePreviewResult,
DeviceProjectDirectoryListResult,
@@ -344,3 +346,44 @@ export async function listProjectSkills(
return undefined;
}
}
+
+/**
+ * Claude Code's auto memory (`~/.claude/projects/<key>/memory`) for a project
+ * on a remote device via the `listClaudeCodeMemory` device RPC — the workspace
+ * panel's Memory tab in device mode. Returns `undefined` when the gateway is
+ * unconfigured, the device is offline, or the call fails (including a client
+ * too old to know the method).
+ */
+export async function listClaudeCodeMemory(
+ getClient: DeviceClientGetter,
+ params: {
+ deviceId: string;
+ /** The agent's own `CLAUDE_CONFIG_DIR` / `CLAUDE_CODE_PROJECT_DIR_NAME`. */
+ env?: DeviceClaudeCodeMemoryRunEnv;
+ scope: string;
+ timeout?: number;
+ userId: string;
+ workspaceId?: string;
+ },
+): Promise<DeviceListClaudeCodeMemoryResult | undefined> {
+ const { userId, deviceId, env, scope, timeout = 30_000, workspaceId } = params;
+ const client = getClient();
+ if (!client) return undefined;
+
+ try {
+ const result = await client.invokeRpc<DeviceListClaudeCodeMemoryResult>(
+ { deviceId, timeout, userId, workspaceId },
+ { method: 'listClaudeCodeMemory', params: { env, scope } },
+ );
+
+ if (!result.success || !result.data) {
+ log('listClaudeCodeMemory: failed for deviceId=%s — %s', deviceId, result.error);
+ return undefined;
+ }
+
+ return result.data;
+ } catch (error) {
+ log('listClaudeCodeMemory: error for deviceId=%s — %O', deviceId, error);
+ return undefined;
+ }
+}
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 680dc731052..99a69a9712d 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -3135,6 +3135,18 @@
"workingPanel.browser.tool.screenshot": "Captured screenshot",
"workingPanel.browser.tool.scroll": "Scrolled page",
"workingPanel.browser.tool.snapshot": "Read page elements",
+ "workingPanel.claudeMemory.empty.description": "Claude Code saves what is worth remembering here as it works in this project.",
+ "workingPanel.claudeMemory.empty.title": "Claude hasn't saved anything for this project yet",
+ "workingPanel.claudeMemory.group.feedback": "Feedback",
+ "workingPanel.claudeMemory.group.index": "Index",
+ "workingPanel.claudeMemory.group.other": "Other",
+ "workingPanel.claudeMemory.group.project": "Project",
+ "workingPanel.claudeMemory.group.reference": "References",
+ "workingPanel.claudeMemory.group.user": "About you",
+ "workingPanel.claudeMemory.indexHint": "Loaded at the start of every session",
+ "workingPanel.claudeMemory.location": "Saved in {{path}}",
+ "workingPanel.claudeMemory.refresh": "Refresh",
+ "workingPanel.claudeMemory.title": "Claude Memory",
"workingPanel.deployments.buildFailedFallback": "Last build failed; the previous release is still serving.",
"workingPanel.deployments.buildLog.open": "View build logs",
"workingPanel.deployments.buildStatus.canceled": "Canceled",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 2e0f926522f..772185576ca 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -3135,6 +3135,18 @@
"workingPanel.browser.tool.screenshot": "截取了页面截图",
"workingPanel.browser.tool.scroll": "滚动了页面",
"workingPanel.browser.tool.snapshot": "读取了页面元素",
+ "workingPanel.claudeMemory.empty.description": "Claude Code 在这个项目里工作时,会把值得记住的内容保存在这里。",
+ "workingPanel.claudeMemory.empty.title": "Claude 还没有为这个项目记下内容",
+ "workingPanel.claudeMemory.group.feedback": "反馈",
+ "workingPanel.claudeMemory.group.index": "索引",
+ "workingPanel.claudeMemory.group.other": "其他",
+ "workingPanel.claudeMemory.group.project": "项目",
+ "workingPanel.claudeMemory.group.reference": "参考",
+ "workingPanel.claudeMemory.group.user": "关于你",
+ "workingPanel.claudeMemory.indexHint": "每次会话开始时载入",
+ "workingPanel.claudeMemory.location": "保存在 {{path}}",
+ "workingPanel.claudeMemory.refresh": "刷新",
+ "workingPanel.claudeMemory.title": "Claude 记忆",
"workingPanel.deployments.buildFailedFallback": "上次构建失败,上一版本仍在线",
"workingPanel.deployments.buildLog.open": "查看构建日志",
"workingPanel.deployments.buildStatus.canceled": "已取消",
diff --git a/packages/device-control/package.json b/packages/device-control/package.json
index d817492f6d6..d57ffc3f4eb 100644
--- a/packages/device-control/package.json
+++ b/packages/device-control/package.json
@@ -7,6 +7,7 @@
".": "./src/index.ts",
"./agent-browser": "./src/agentBrowser.ts",
"./claude-code-account-routing": "./src/claudeCodeAccountRouting.ts",
+ "./claude-code-memory": "./src/claudeCodeMemory.ts",
"./computer-use": "./src/computerUse.ts",
"./file-preview": "./src/filePreview.ts",
"./metrics": "./src/metrics/index.ts",
diff --git a/packages/device-control/src/__tests__/claudeCodeMemory.test.ts b/packages/device-control/src/__tests__/claudeCodeMemory.test.ts
new file mode 100644
index 00000000000..3e1339b53ae
--- /dev/null
+++ b/packages/device-control/src/__tests__/claudeCodeMemory.test.ts
@@ -0,0 +1,286 @@
+import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ listClaudeCodeMemory,
+ resolveClaudeCodeMemoryDir,
+ resolveClaudeCodeProjectRoot,
+ toClaudeCodeProjectKey,
+} from '../claudeCodeMemory';
+
+let sandbox: string;
+let home: string;
+let managedSettingsDir: string;
+
+const memoryEnv = (env: NodeJS.ProcessEnv = {}) => ({ env, homedir: home, managedSettingsDir });
+
+const write = async (filePath: string, content: string) => {
+ await mkdir(path.dirname(filePath), { recursive: true });
+ await writeFile(filePath, content);
+};
+
+beforeEach(async () => {
+ sandbox = await realpath(await mkdtemp(path.join(tmpdir(), 'cc-memory-')));
+ home = path.join(sandbox, 'home');
+ managedSettingsDir = path.join(sandbox, 'managed');
+ await mkdir(home, { recursive: true });
+});
+
+afterEach(async () => {
+ await rm(sandbox, { force: true, recursive: true });
+});
+
+describe('toClaudeCodeProjectKey', () => {
+ it('replaces every non-alphanumeric character with a dash', () => {
+ expect(toClaudeCodeProjectKey('/home/ubuntu/develop/amazing/lobehub')).toBe(
+ '-home-ubuntu-develop-amazing-lobehub',
+ );
+ expect(toClaudeCodeProjectKey('C:\\Users\\me\\my_app.v2')).toBe('C--Users-me-my-app-v2');
+ });
+
+ it('caps long keys at 200 characters and appends a hash of the full path', () => {
+ const longPath = `/${'a'.repeat(250)}`;
+ const key = toClaudeCodeProjectKey(longPath);
+
+ expect(key.startsWith(`-${'a'.repeat(199)}-`)).toBe(true);
+ expect(key).toMatch(/^-a{199}-[\da-z]+$/);
+ expect(toClaudeCodeProjectKey(`/${'a'.repeat(251)}`)).not.toBe(key);
+ });
+
+ it('keys the NFC form, so a decomposed macOS path maps to the same directory', () => {
+ const composed = '/Users/me/caf\u00E9';
+ const decomposed = '/Users/me/cafe\u0301';
+
+ expect(toClaudeCodeProjectKey(decomposed)).toBe(toClaudeCodeProjectKey(composed));
+ expect(toClaudeCodeProjectKey(`/${'\u00E9'.repeat(250)}`)).toBe(
+ toClaudeCodeProjectKey(`/${'e\u0301'.repeat(250)}`),
+ );
+ });
+});
+
+describe('resolveClaudeCodeProjectRoot', () => {
+ it('uses the git root for a subdirectory of a repository', async () => {
+ const repo = path.join(sandbox, 'repo');
+ await mkdir(path.join(repo, '.git'), { recursive: true });
+ await mkdir(path.join(repo, 'packages', 'app'), { recursive: true });
+
+ expect(await resolveClaudeCodeProjectRoot(path.join(repo, 'packages', 'app'))).toBe(repo);
+ });
+
+ it('maps a linked worktree back to the main checkout', async () => {
+ const repo = path.join(sandbox, 'repo');
+ const worktree = path.join(sandbox, 'repo-wt');
+ const worktreeGitDir = path.join(repo, '.git', 'worktrees', 'repo-wt');
+ await write(path.join(worktreeGitDir, 'commondir'), '../..\n');
+ await write(path.join(worktree, '.git'), `gitdir: ${worktreeGitDir}\n`);
+
+ expect(await resolveClaudeCodeProjectRoot(worktree)).toBe(repo);
+ });
+
+ it('keeps a submodule checkout as its own root', async () => {
+ const submodule = path.join(sandbox, 'repo', 'vendor', 'lib');
+ await mkdir(path.join(sandbox, 'repo', '.git', 'modules', 'lib'), { recursive: true });
+ await write(path.join(submodule, '.git'), 'gitdir: ../../.git/modules/lib\n');
+
+ expect(await resolveClaudeCodeProjectRoot(submodule)).toBe(submodule);
+ });
+
+ it('falls back to the directory itself outside git', async () => {
+ const dir = path.join(sandbox, 'plain');
+ await mkdir(dir, { recursive: true });
+
+ expect(await resolveClaudeCodeProjectRoot(dir)).toBe(dir);
+ });
+});
+
+describe('resolveClaudeCodeMemoryDir', () => {
+ let dir: string;
+
+ beforeEach(async () => {
+ dir = path.join(sandbox, 'plain');
+ await mkdir(dir, { recursive: true });
+ });
+
+ it('defaults to ~/.claude/projects/<key>/memory', async () => {
+ expect(await resolveClaudeCodeMemoryDir(dir, memoryEnv())).toBe(
+ path.join(home, '.claude', 'projects', toClaudeCodeProjectKey(dir), 'memory'),
+ );
+ });
+
+ it('honors CLAUDE_CONFIG_DIR', async () => {
+ const configDir = path.join(sandbox, 'cc-config');
+
+ expect(await resolveClaudeCodeMemoryDir(dir, memoryEnv({ CLAUDE_CONFIG_DIR: configDir }))).toBe(
+ path.join(configDir, 'projects', toClaudeCodeProjectKey(dir), 'memory'),
+ );
+ });
+
+ it('uses CLAUDE_CODE_PROJECT_DIR_NAME as the key only beside CLAUDE_CONFIG_DIR', async () => {
+ const configDir = path.join(sandbox, 'cc-config');
+ const derived = toClaudeCodeProjectKey(dir);
+
+ expect(
+ await resolveClaudeCodeMemoryDir(
+ dir,
+ memoryEnv({ CLAUDE_CODE_PROJECT_DIR_NAME: 'work', CLAUDE_CONFIG_DIR: configDir }),
+ ),
+ ).toBe(path.join(configDir, 'projects', 'work', 'memory'));
+ expect(
+ await resolveClaudeCodeMemoryDir(dir, memoryEnv({ CLAUDE_CODE_PROJECT_DIR_NAME: 'work' })),
+ ).toBe(path.join(home, '.claude', 'projects', derived, 'memory'));
+
+ for (const invalid of ['con', 'a/b', 'x'.repeat(65)]) {
+ expect(
+ await resolveClaudeCodeMemoryDir(
+ dir,
+ memoryEnv({ CLAUDE_CODE_PROJECT_DIR_NAME: invalid, CLAUDE_CONFIG_DIR: configDir }),
+ ),
+ ).toBe(path.join(configDir, 'projects', derived, 'memory'));
+ }
+ });
+
+ it('honors autoMemoryDirectory from user settings', async () => {
+ await write(
+ path.join(home, '.claude', 'settings.json'),
+ JSON.stringify({ autoMemoryDirectory: '~/notes/cc-memory' }),
+ );
+
+ expect(await resolveClaudeCodeMemoryDir(dir, memoryEnv())).toBe(
+ path.join(home, 'notes', 'cc-memory'),
+ );
+ });
+
+ it('takes autoMemoryDirectory from the winning scope: managed, local, project, then user', async () => {
+ const repo = path.join(sandbox, 'repo');
+ const cwd = path.join(repo, 'packages', 'app');
+ await mkdir(path.join(repo, '.git'), { recursive: true });
+ const setMemoryDir = (file: string, value: string) =>
+ write(file, JSON.stringify({ autoMemoryDirectory: value }));
+ const resolve = () => resolveClaudeCodeMemoryDir(cwd, memoryEnv());
+
+ await setMemoryDir(path.join(home, '.claude', 'settings.json'), '/scopes/user');
+ expect(await resolve()).toBe(path.resolve('/scopes/user'));
+
+ await setMemoryDir(path.join(cwd, '.claude', 'settings.json'), '/scopes/project');
+ expect(await resolve()).toBe(path.resolve('/scopes/project'));
+
+ await setMemoryDir(path.join(cwd, '.claude', 'settings.local.json'), '/scopes/legacy-local');
+ expect(await resolve()).toBe(path.resolve('/scopes/legacy-local'));
+
+ await setMemoryDir(path.join(repo, '.claude', 'settings.local.json'), '/scopes/local');
+ expect(await resolve()).toBe(path.resolve('/scopes/local'));
+
+ await setMemoryDir(path.join(managedSettingsDir, 'managed-settings.json'), '/scopes/managed');
+ await setMemoryDir(
+ path.join(managedSettingsDir, 'managed-settings.d', '10-memory.json'),
+ '/scopes/drop-in',
+ );
+ await write(path.join(managedSettingsDir, 'managed-settings.d', '20-other.json'), '{}');
+ expect(await resolve()).toBe(path.resolve('/scopes/drop-in'));
+ });
+
+ it('ignores an autoMemoryDirectory that is neither absolute nor under ~/', async () => {
+ await write(
+ path.join(dir, '.claude', 'settings.json'),
+ JSON.stringify({ autoMemoryDirectory: 'relative/memory' }),
+ );
+
+ expect(await resolveClaudeCodeMemoryDir(dir, memoryEnv())).toBe(
+ path.join(home, '.claude', 'projects', toClaudeCodeProjectKey(dir), 'memory'),
+ );
+ });
+});
+
+describe('listClaudeCodeMemory', () => {
+ const memoryDirFor = (dir: string) =>
+ path.join(home, '.claude', 'projects', toClaudeCodeProjectKey(dir), 'memory');
+
+ it('returns an empty list without approving anything when no memory exists', async () => {
+ const dir = path.join(sandbox, 'plain');
+ await mkdir(dir, { recursive: true });
+ const approveProjectRoot = vi.fn(async () => {});
+
+ const result = await listClaudeCodeMemory({ scope: dir }, { approveProjectRoot }, memoryEnv());
+
+ expect(result).toEqual({ files: [], memoryDir: memoryDirFor(dir) });
+ expect(approveProjectRoot).not.toHaveBeenCalled();
+ });
+
+ it('lists the index first, parses frontmatter and approves the memory directory', async () => {
+ const dir = path.join(sandbox, 'plain');
+ await mkdir(dir, { recursive: true });
+ const memoryDir = memoryDirFor(dir);
+ await write(path.join(memoryDir, 'MEMORY.md'), '- [Testing](testing.md) — hook\n');
+ await write(
+ path.join(memoryDir, 'testing.md'),
+ [
+ '---',
+ 'name: testing-rules',
+ 'description: Run focused vitest only',
+ 'metadata:',
+ ' type: feedback',
+ '---',
+ 'Never run the full suite.',
+ ].join('\n'),
+ );
+ await write(path.join(memoryDir, 'about.md'), '---\ntype: user\n---\nA backend engineer.');
+ await write(path.join(memoryDir, 'notes.txt'), 'ignored');
+ await write(path.join(memoryDir, '.draft.md'), 'ignored');
+ const approveProjectRoot = vi.fn(async () => {});
+
+ const result = await listClaudeCodeMemory({ scope: dir }, { approveProjectRoot }, memoryEnv());
+
+ expect(result.memoryDir).toBe(memoryDir);
+ expect(result.files.map((file) => file.relativePath)).toEqual([
+ 'MEMORY.md',
+ 'about.md',
+ 'testing.md',
+ ]);
+ expect(result.files[0]).toMatchObject({ isIndex: true, name: 'MEMORY' });
+ expect(result.files[1]).toMatchObject({ isIndex: false, name: 'about', type: 'user' });
+ expect(result.files[2]).toMatchObject({
+ description: 'Run focused vitest only',
+ name: 'testing-rules',
+ path: path.join(memoryDir, 'testing.md'),
+ type: 'feedback',
+ });
+ expect(approveProjectRoot).toHaveBeenCalledWith(memoryDir);
+ });
+
+ it("reads the agent's own CLAUDE_CONFIG_DIR over the device's", async () => {
+ const dir = path.join(sandbox, 'plain');
+ const agentConfigDir = path.join(sandbox, 'agent-config');
+ await mkdir(dir, { recursive: true });
+ const memoryDir = path.join(agentConfigDir, 'projects', toClaudeCodeProjectKey(dir), 'memory');
+ await write(path.join(memoryDir, 'MEMORY.md'), '- index\n');
+
+ const result = await listClaudeCodeMemory(
+ { env: { CLAUDE_CONFIG_DIR: agentConfigDir }, scope: dir },
+ {},
+ memoryEnv({ CLAUDE_CONFIG_DIR: path.join(sandbox, 'device-config') }),
+ );
+
+ expect(result.memoryDir).toBe(memoryDir);
+ expect(result.files.map((file) => file.relativePath)).toEqual(['MEMORY.md']);
+ });
+
+ it('never approves a memory directory that contains the project', async () => {
+ const dir = path.join(home, 'projects', 'repo');
+ await mkdir(dir, { recursive: true });
+ await write(
+ path.join(dir, '.claude', 'settings.json'),
+ JSON.stringify({ autoMemoryDirectory: '~/' }),
+ );
+ await write(path.join(home, 'notes.md'), 'personal notes');
+ const approveProjectRoot = vi.fn(async () => {});
+
+ const result = await listClaudeCodeMemory({ scope: dir }, { approveProjectRoot }, memoryEnv());
+
+ expect(result.memoryDir).toBe(home);
+ expect(result.files.length).toBeGreaterThan(0);
+ expect(approveProjectRoot).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/device-control/src/claudeCodeMemory.ts b/packages/device-control/src/claudeCodeMemory.ts
new file mode 100644
index 00000000000..e947b83868c
--- /dev/null
+++ b/packages/device-control/src/claudeCodeMemory.ts
@@ -0,0 +1,336 @@
+import { readdir, readFile, realpath, stat } from 'node:fs/promises';
+import * as os from 'node:os';
+import path from 'node:path';
+
+import matter from 'gray-matter';
+
+import type {
+ ClaudeCodeMemoryFile,
+ ClaudeCodeMemoryRunEnv,
+ ListClaudeCodeMemoryParams,
+ ListClaudeCodeMemoryResult,
+ WorkspaceScanDeps,
+} from './types';
+
+const MEMORY_INDEX_FILE = 'MEMORY.md';
+const MAX_MEMORY_FILES = 500;
+// Claude Code caps the sanitized project key and appends a hash beyond this.
+const MAX_PROJECT_KEY_LENGTH = 200;
+// The `CLAUDE_CODE_PROJECT_DIR_NAME` values Claude Code accepts; it derives the key for any other.
+const PROJECT_DIR_NAME = /^[\w-]{1,64}$/;
+const WINDOWS_DEVICE_NAME = /^(?:aux|con|nul|prn|com[1-9]|lpt[1-9])$/i;
+const RUN_ENV_KEYS = ['CLAUDE_CONFIG_DIR', 'CLAUDE_CODE_PROJECT_DIR_NAME'] as const;
+
+interface ClaudeCodeMemoryEnv {
+ env?: NodeJS.ProcessEnv;
+ homedir?: string;
+ /** System directory of the file-based managed settings; the platform's own by default. */
+ managedSettingsDir?: string;
+}
+
+const defaultManagedSettingsDir = () => {
+ if (process.platform === 'darwin') return '/Library/Application Support/ClaudeCode';
+ if (process.platform === 'win32') return 'C:\\Program Files\\ClaudeCode';
+ return '/etc/claude-code';
+};
+
+/** Java-style 32-bit string hash, the one Claude Code suffixes long keys with. */
+const hashString = (value: string): string => {
+ let hash = 0;
+ for (let i = 0; i < value.length; i++) hash = ((hash << 5) - hash + value.charCodeAt(i)) | 0;
+ return Math.abs(hash).toString(36);
+};
+
+/**
+ * Claude Code's project key: the NFC-normalized root with every non-alphanumeric
+ * character replaced by `-`. macOS can hand back decomposed accents; the CLI
+ * keys the composed form. Mirrors heterogeneous-agents' `encodeClaudeProjectDir`,
+ * kept here so the device RPC does not load the transcript parsers.
+ */
+export const toClaudeCodeProjectKey = (projectRoot: string): string => {
+ const normalized = projectRoot.normalize('NFC');
+ const key = normalized.replaceAll(/[^a-z0-9]/gi, '-');
+ if (key.length <= MAX_PROJECT_KEY_LENGTH) return key;
+ return `${key.slice(0, MAX_PROJECT_KEY_LENGTH)}-${hashString(normalized)}`;
+};
+
+const isFile = async (target: string) => {
+ try {
+ return (await stat(target)).isFile();
+ } catch {
+ return false;
+ }
+};
+
+const isDirectory = async (target: string) => {
+ try {
+ return (await stat(target)).isDirectory();
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * The root Claude Code keys memory by: the main checkout of the enclosing git
+ * repository, so every worktree and subdirectory of one repo shares a single
+ * memory directory. Outside git it is the directory itself.
+ */
+export const resolveClaudeCodeProjectRoot = async (cwd: string): Promise<string> => {
+ const start = await realpath(cwd).catch(() => path.resolve(cwd));
+
+ for (let dir = start; ; dir = path.dirname(dir)) {
+ const dotGit = path.join(dir, '.git');
+ if (await isDirectory(dotGit)) return dir;
+
+ if (await isFile(dotGit)) {
+ // A linked worktree: `.git` points at `<main>/.git/worktrees/<name>`,
+ // whose `commondir` leads back to the main repository's `.git`.
+ try {
+ const pointer = (await readFile(dotGit, 'utf8'))
+ .split('\n')
+ .find((line) => line.startsWith('gitdir:'))
+ ?.slice('gitdir:'.length)
+ .trim();
+ if (!pointer) return dir;
+ const gitDir = path.resolve(dir, pointer);
+ const commonDir = (await readFile(path.join(gitDir, 'commondir'), 'utf8')).trim();
+ const mainGitDir = await realpath(path.resolve(gitDir, commonDir));
+ return path.basename(mainGitDir) === '.git' ? path.dirname(mainGitDir) : dir;
+ } catch {
+ // No `commondir` (a submodule) or an unreadable pointer: the checkout is its own root.
+ return dir;
+ }
+ }
+
+ if (path.dirname(dir) === dir) return start;
+ }
+};
+
+const readJsonObject = async (file: string): Promise<Record<string, unknown> | undefined> => {
+ try {
+ const value = JSON.parse(await readFile(file, 'utf8'));
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+/** An `autoMemoryDirectory` value counts only as an absolute path or one under `~/`. */
+const toMemoryDirectory = (value: unknown, homedir: string): string | undefined => {
+ if (typeof value !== 'string') return undefined;
+ const trimmed = value.trim();
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
+ return path.join(homedir, trimmed.slice(2));
+ }
+ return path.isAbsolute(trimmed) ? path.resolve(trimmed) : undefined;
+};
+
+/** `managed-settings.json`, then the `managed-settings.d/*.json` drop-ins alphabetically. */
+const listManagedSettingsFiles = async (dir: string): Promise<string[]> => {
+ const dropInDir = path.join(dir, 'managed-settings.d');
+ const dropIns = await readdir(dropInDir).catch((): string[] => []);
+ return [
+ path.join(dir, 'managed-settings.json'),
+ ...dropIns
+ .filter((name) => !name.startsWith('.') && name.endsWith('.json'))
+ .sort()
+ .map((name) => path.join(dropInDir, name)),
+ ];
+};
+
+/**
+ * `autoMemoryDirectory` from the settings scope Claude Code lets win: the
+ * file-based managed settings (a later drop-in over an earlier one), then
+ * project local, shared project and user settings. Local settings sit at the
+ * repository root (the main checkout for a worktree), with a file an older CLI
+ * left in the working directory as the fallback; shared project settings sit in
+ * the working directory. MDM and server-managed policy and `--settings` are not
+ * on disk here.
+ */
+const readMemoryDirectoryOverride = async ({
+ configDir,
+ cwd,
+ homedir,
+ managedSettingsDir,
+ projectRoot,
+}: {
+ configDir: string;
+ cwd: string;
+ homedir: string;
+ managedSettingsDir: string;
+ projectRoot: string;
+}): Promise<string | undefined> => {
+ const files = [
+ ...(await listManagedSettingsFiles(managedSettingsDir)).reverse(),
+ path.join(projectRoot, '.claude', 'settings.local.json'),
+ path.join(cwd, '.claude', 'settings.local.json'),
+ path.join(cwd, '.claude', 'settings.json'),
+ path.join(configDir, 'settings.json'),
+ ];
+ const settings = await Promise.all(files.map(readJsonObject));
+
+ for (const scope of settings) {
+ const directory = toMemoryDirectory(scope?.autoMemoryDirectory, homedir);
+ if (directory) return directory;
+ }
+ return undefined;
+};
+
+/**
+ * Where Claude Code keeps auto memory for `cwd`:
+ * `<CLAUDE_CONFIG_DIR or ~/.claude>/projects/<project key>/memory`, where a
+ * valid `CLAUDE_CODE_PROJECT_DIR_NAME` beside a `CLAUDE_CONFIG_DIR` replaces the
+ * key, unless the settings point `autoMemoryDirectory` elsewhere.
+ */
+export const resolveClaudeCodeMemoryDir = async (
+ cwd: string,
+ {
+ env = process.env,
+ homedir = os.homedir(),
+ managedSettingsDir = defaultManagedSettingsDir(),
+ }: ClaudeCodeMemoryEnv = {},
+): Promise<string> => {
+ const workingDirectory = path.resolve(cwd);
+ const customConfigDir = env.CLAUDE_CONFIG_DIR?.trim();
+ // A relative config dir resolves the way the spawned CLI sees it: from its cwd.
+ const configDir = customConfigDir
+ ? path.resolve(workingDirectory, customConfigDir)
+ : path.join(homedir, '.claude');
+ const projectRoot = await resolveClaudeCodeProjectRoot(workingDirectory);
+
+ const override = await readMemoryDirectoryOverride({
+ configDir,
+ cwd: workingDirectory,
+ homedir,
+ managedSettingsDir,
+ projectRoot,
+ });
+ if (override) return override;
+
+ const pinnedName = env.CLAUDE_CODE_PROJECT_DIR_NAME;
+ const projectKey =
+ customConfigDir &&
+ pinnedName &&
+ PROJECT_DIR_NAME.test(pinnedName) &&
+ !WINDOWS_DEVICE_NAME.test(pinnedName)
+ ? pinnedName
+ : toClaudeCodeProjectKey(projectRoot);
+ return path.join(configDir, 'projects', projectKey, 'memory');
+};
+
+/** The agent's non-blank values for the keys that move memory; the rest stay the device's. */
+const pickRunEnv = (runEnv: ClaudeCodeMemoryRunEnv | undefined) =>
+ Object.fromEntries(
+ RUN_ENV_KEYS.flatMap((key) => {
+ const value: unknown = runEnv?.[key];
+ return typeof value === 'string' && value.trim() ? [[key, value]] : [];
+ }),
+ );
+
+const readStringField = (data: Record<string, unknown> | undefined, key: string) => {
+ const value = data?.[key];
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
+};
+
+const parseMemoryFrontmatter = (raw: string) => {
+ try {
+ const { data } = matter(raw) as { data: Record<string, unknown> };
+ const metadata =
+ data.metadata && typeof data.metadata === 'object'
+ ? (data.metadata as Record<string, unknown>)
+ : undefined;
+ return {
+ description: readStringField(data, 'description'),
+ name: readStringField(data, 'name'),
+ type: readStringField(metadata, 'type') ?? readStringField(data, 'type'),
+ };
+ } catch {
+ return {};
+ }
+};
+
+const listMarkdownFiles = async (root: string): Promise<string[]> => {
+ const results: string[] = [];
+ const stack = [root];
+
+ while (stack.length > 0 && results.length < MAX_MEMORY_FILES) {
+ const dir = stack.pop()!;
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+
+ for (const entry of entries) {
+ if (entry.name.startsWith('.')) continue;
+ const fullPath = path.join(dir, entry.name);
+ if (entry.isDirectory()) stack.push(fullPath);
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) results.push(fullPath);
+ if (results.length >= MAX_MEMORY_FILES) break;
+ }
+ }
+
+ return results;
+};
+
+const readMemoryFile = async (
+ memoryDir: string,
+ filePath: string,
+): Promise<ClaudeCodeMemoryFile | null> => {
+ try {
+ const [raw, stats] = await Promise.all([readFile(filePath, 'utf8'), stat(filePath)]);
+ const relativePath = path.relative(memoryDir, filePath).split(path.sep).join('/');
+ const fields = parseMemoryFrontmatter(raw);
+ return {
+ description: fields.description,
+ isIndex: relativePath === MEMORY_INDEX_FILE,
+ name: fields.name ?? path.basename(filePath, path.extname(filePath)),
+ path: filePath,
+ relativePath,
+ size: stats.size,
+ type: fields.type,
+ updatedAt: stats.mtimeMs,
+ };
+ } catch {
+ return null;
+ }
+};
+
+const containsPath = (root: string, target: string) => {
+ const relative = path.relative(root, target);
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
+};
+
+/**
+ * List Claude Code's auto-memory files for a project: the `MEMORY.md` index
+ * first, then each memory with its frontmatter. An absent directory yields an
+ * empty list. Approves the directory for the host preview protocol so the
+ * files open (and save) from the workspace panel, unless it contains the
+ * project itself: a repository setting pointing `autoMemoryDirectory` at `~`
+ * or `/` must not open the whole tree.
+ */
+export const listClaudeCodeMemory = async (
+ params: ListClaudeCodeMemoryParams,
+ deps: WorkspaceScanDeps = {},
+ { env = process.env, ...memoryEnv }: ClaudeCodeMemoryEnv = {},
+): Promise<ListClaudeCodeMemoryResult> => {
+ const memoryDir = await resolveClaudeCodeMemoryDir(params.scope, {
+ ...memoryEnv,
+ env: { ...env, ...pickRunEnv(params.env) },
+ });
+ if (!(await isDirectory(memoryDir))) return { files: [], memoryDir };
+
+ const paths = await listMarkdownFiles(memoryDir);
+ const files = (await Promise.all(paths.map((file) => readMemoryFile(memoryDir, file))))
+ .filter((file): file is ClaudeCodeMemoryFile => file !== null)
+ .sort((a, b) =>
+ a.isIndex === b.isIndex ? a.relativePath.localeCompare(b.relativePath) : a.isIndex ? -1 : 1,
+ );
+
+ if (files.length > 0 && !containsPath(memoryDir, path.resolve(params.scope))) {
+ await deps.approveProjectRoot?.(memoryDir);
+ }
+
+ return { files, memoryDir };
+};
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 7b76a484a3d..b41a6ade849 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -38,6 +38,7 @@ import type {
} from '@lobechat/local-file-shell/types';
import type { DeviceCliRestartParams } from '@lobechat/types';
+import { listClaudeCodeMemory } from './claudeCodeMemory';
import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';
import { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';
import { defaultCopyAssetForPublish, defaultReadExternalAssetForPublish } from './filePreview';
@@ -54,6 +55,7 @@ import type {
EnrollWorkspaceParams,
ExternalAssetForPublishParams,
InitWorkspaceParams,
+ ListClaudeCodeMemoryParams,
ListHeterogeneousAgentModelsParams,
ListProjectSkillsParams,
LocalFilePreviewUrlParams,
@@ -85,6 +87,7 @@ export const DEVICE_RPC_METHODS = [
'getCodexQuota',
'getKimiCodeQuota',
'listProjectSkills',
+ 'listClaudeCodeMemory',
'prepareSkillDirectory',
'browseDirectory',
'statPath',
@@ -240,6 +243,10 @@ export const executeDeviceRpc = async (
return listProjectSkills(params as ListProjectSkillsParams, deps);
}
+ case 'listClaudeCodeMemory': {
+ return listClaudeCodeMemory(params as ListClaudeCodeMemoryParams, deps);
+ }
+
case 'prepareSkillDirectory': {
return prepareSkillDirectory(params as PrepareSkillDirectoryParams, deps);
}
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index 0e20cccbae8..91a846f7844 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -1,3 +1,9 @@
+export {
+ listClaudeCodeMemory,
+ resolveClaudeCodeMemoryDir,
+ resolveClaudeCodeProjectRoot,
+ toClaudeCodeProjectKey,
+} from './claudeCodeMemory';
export { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';
export {
APP_UPDATE_UNSUPPORTED_MESSAGE,
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index b4f9238d066..0798696dad1 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -60,6 +60,49 @@ export interface ListProjectSkillsResult {
source: ProjectSkillSource | null;
}
+/** The run env keys that move where Claude Code keeps auto memory. */
+export interface ClaudeCodeMemoryRunEnv {
+ CLAUDE_CODE_PROJECT_DIR_NAME?: string;
+ CLAUDE_CONFIG_DIR?: string;
+}
+
+export interface ListClaudeCodeMemoryParams {
+ /**
+ * The agent's own values for these keys (`heterogeneousProvider.env`). A run
+ * spreads that env over the device's, so a set value wins here too.
+ */
+ env?: ClaudeCodeMemoryRunEnv;
+ /** Working directory of the Claude Code project. */
+ scope: string;
+}
+
+export interface ClaudeCodeMemoryFile {
+ description?: string;
+ /** The `MEMORY.md` index Claude Code loads into every session. */
+ isIndex: boolean;
+ /** Frontmatter `name`; the file name when absent. */
+ name: string;
+ /** Absolute path to the memory file. */
+ path: string;
+ /** Path within the memory directory, `/`-separated. */
+ relativePath: string;
+ size: number;
+ /** Frontmatter `metadata.type` (or top-level `type`): user / feedback / project / reference. */
+ type?: string;
+ /** Last modification time, epoch ms. */
+ updatedAt: number;
+}
+
+export interface ListClaudeCodeMemoryResult {
+ files: ClaudeCodeMemoryFile[];
+ /**
+ * Claude Code's auto-memory directory for this project
+ * (`~/.claude/projects/<sanitized project root>/memory`). Reported even when
+ * it does not exist yet, so the UI can say where memory will land.
+ */
+ memoryDir: string;
+}
+
export interface StatPathResult {
/** Device-resolved path; aliases and symlinks share one execution-directory lock. */
canonicalPath?: string;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 2338c68af44..1f584f80de6 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3539,6 +3539,19 @@ export default {
'workingPanel.browser.tool.screenshot': 'Captured screenshot',
'workingPanel.browser.tool.scroll': 'Scrolled page',
'workingPanel.browser.tool.snapshot': 'Read page elements',
+ 'workingPanel.claudeMemory.empty.description':
+ 'Claude Code saves what is worth remembering here as it works in this project.',
+ 'workingPanel.claudeMemory.empty.title': "Claude hasn't saved anything for this project yet",
+ 'workingPanel.claudeMemory.group.feedback': 'Feedback',
+ 'workingPanel.claudeMemory.group.index': 'Index',
+ 'workingPanel.claudeMemory.group.other': 'Other',
+ 'workingPanel.claudeMemory.group.project': 'Project',
+ 'workingPanel.claudeMemory.group.reference': 'References',
+ 'workingPanel.claudeMemory.group.user': 'About you',
+ 'workingPanel.claudeMemory.indexHint': 'Loaded at the start of every session',
+ 'workingPanel.claudeMemory.location': 'Saved in {{path}}',
+ 'workingPanel.claudeMemory.refresh': 'Refresh',
+ 'workingPanel.claudeMemory.title': 'Claude Memory',
'workingPanel.openMenu.configuration': 'Configuration',
'workingPanel.openMenu.terminal': 'Terminal',
'workingPanel.openMenu.title': 'Open workspace panel',
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index 32e8cd9bccc..66397bd4168 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -938,6 +938,39 @@ export interface DeviceListProjectSkillsResult {
source: ProjectSkillSource | null;
}
+/** One Claude Code auto-memory file, from the `listClaudeCodeMemory` device RPC. */
+export interface DeviceClaudeCodeMemoryFile {
+ description?: string;
+ /** The `MEMORY.md` index Claude Code loads into every session. */
+ isIndex: boolean;
+ name: string;
+ /** Absolute path on the device. */
+ path: string;
+ /** Path within the memory directory, `/`-separated. */
+ relativePath: string;
+ size: number;
+ /** Frontmatter memory type: user / feedback / project / reference. */
+ type?: string;
+ updatedAt: number;
+}
+
+/** The agent env keys that move Claude Code's auto memory, sent with `listClaudeCodeMemory`. */
+export interface DeviceClaudeCodeMemoryRunEnv {
+ CLAUDE_CODE_PROJECT_DIR_NAME?: string;
+ CLAUDE_CONFIG_DIR?: string;
+}
+
+/**
+ * Claude Code's auto memory for a project on the device, returned by the
+ * `listClaudeCodeMemory` device RPC. Mirrors device-control's
+ * `ListClaudeCodeMemoryResult`.
+ */
+export interface DeviceListClaudeCodeMemoryResult {
+ files: DeviceClaudeCodeMemoryFile[];
+ /** `~/.claude/projects/<project key>/memory` on the device, present or not. */
+ memoryDir: string;
+}
+
const gitLinkedPullRequestSchema = z.object({
ciStatus: z.enum(['failure', 'pending', 'success', 'unknown']).optional(),
isDraft: z.boolean().optional(),
diff --git a/src/features/Conversation/WorkingSidebar/Memory/MemoryPane.tsx b/src/features/Conversation/WorkingSidebar/Memory/MemoryPane.tsx
new file mode 100644
index 00000000000..c23eed62bfa
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Memory/MemoryPane.tsx
@@ -0,0 +1,190 @@
+import { EMPTY_ARRAY } from '@lobechat/const';
+import type { DeviceClaudeCodeMemoryFile } from '@lobechat/types';
+import { ActionIcon, Center, Empty, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { BrainIcon, FileTextIcon, RefreshCwIcon } from 'lucide-react';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import { SkillSection } from '@/features/SkillsList';
+import { useChatStore } from '@/store/chat';
+
+import { groupMemoryFiles, memoryFilePortalTarget } from './memoryView';
+import { useClaudeCodeMemory } from './useClaudeCodeMemory';
+
+const styles = stylex.create({
+ description: {
+ color: cssVar.colorTextTertiary,
+ fontSize: 12,
+ lineHeight: 1.5,
+ paddingInlineStart: 20,
+ },
+ item: {
+ backgroundColor: {
+ ':focus-visible': cssVar.colorFillTertiary,
+ ':hover': cssVar.colorFillTertiary,
+ 'default': 'transparent',
+ },
+ borderRadius: 6,
+ borderStyle: 'none',
+ color: {
+ ':focus-visible': cssVar.colorText,
+ ':hover': cssVar.colorText,
+ 'default': cssVar.colorTextSecondary,
+ },
+ cursor: 'pointer',
+ display: 'flex',
+ flexDirection: 'column',
+ fontSize: 13,
+ gap: 2,
+ paddingBlock: 6,
+ paddingInlineEnd: 8,
+ paddingInlineStart: 4,
+ textAlign: 'start',
+ width: '100%',
+ },
+ itemIcon: {
+ color: cssVar.colorTextTertiary,
+ flexShrink: 0,
+ },
+ location: {
+ flex: '1',
+ fontSize: 12,
+ minWidth: 0,
+ },
+});
+
+interface MemoryRowProps {
+ file: DeviceClaudeCodeMemoryFile;
+ indexHint: string;
+ onOpen: (file: DeviceClaudeCodeMemoryFile) => void;
+}
+
+const MemoryRow = memo<MemoryRowProps>(({ file, indexHint, onOpen }) => {
+ const description = file.description ?? (file.isIndex ? indexHint : undefined);
+
+ return (
+ <button
+ {...stylex.props(styles.item)}
+ title={file.relativePath}
+ type="button"
+ onClick={() => onOpen(file)}
+ >
+ <Flexbox horizontal align={'center'} gap={6} width={'100%'}>
+ <Icon {...stylex.props(styles.itemIcon)} icon={FileTextIcon} size={14} />
+ <Text ellipsis style={{ color: 'inherit', flex: 1, minWidth: 0 }}>
+ {file.isIndex ? file.relativePath : file.name}
+ </Text>
+ </Flexbox>
+ {description && (
+ <Text {...stylex.props(styles.description)} ellipsis={{ rows: 2 }}>
+ {description}
+ </Text>
+ )}
+ </button>
+ );
+});
+
+MemoryRow.displayName = 'ClaudeCodeMemoryRow';
+
+interface MemoryPaneProps {
+ /** The Claude Code agent whose own config dir, if it sets one, holds the memory. */
+ agentId?: string;
+ /** Bound device; the memory is then read and saved over RPC. */
+ deviceId?: string;
+ workingDirectory: string;
+}
+
+/**
+ * Claude Code's auto memory for the selected project
+ * (`~/.claude/projects/<project key>/memory`). Each file opens in the local-file
+ * portal, where it can be edited and saved back in place.
+ */
+export const MemoryPane = memo<MemoryPaneProps>(({ agentId, deviceId, workingDirectory }) => {
+ const { t } = useTranslation('chat');
+ const openLocalFile = useChatStore((s) => s.openLocalFile);
+ const { data, error, isLoading, isValidating, mutate } = useClaudeCodeMemory({
+ agentId,
+ deviceId,
+ workingDirectory,
+ });
+ const files = data?.files ?? EMPTY_ARRAY;
+ const groups = useMemo(() => groupMemoryFiles(files), [files]);
+ const memoryDir = data?.memoryDir;
+
+ const openMemory = useCallback(
+ (file: DeviceClaudeCodeMemoryFile) => {
+ if (memoryDir) openLocalFile(memoryFilePortalTarget(file, memoryDir, deviceId));
+ },
+ [deviceId, memoryDir, openLocalFile],
+ );
+ const refresh = useCallback(() => void mutate(), [mutate]);
+
+ return (
+ <Flexbox
+ data-testid={'workspace-memory'}
+ flex={1}
+ gap={12}
+ paddingBlock={8}
+ paddingInline={'8px 12px'}
+ style={{ minHeight: 0 }}
+ >
+ {/* Outside the boundary so an empty memory can still be re-read once Claude writes one. */}
+ {memoryDir && (
+ <Flexbox horizontal align={'center'} gap={4} paddingInline={4}>
+ <Text ellipsis {...stylex.props(styles.location)} title={memoryDir} type={'secondary'}>
+ {t('workingPanel.claudeMemory.location', { path: memoryDir })}
+ </Text>
+ <ActionIcon
+ aria-label={t('workingPanel.claudeMemory.refresh')}
+ icon={RefreshCwIcon}
+ loading={isValidating}
+ size={'small'}
+ title={t('workingPanel.claudeMemory.refresh')}
+ onClick={refresh}
+ />
+ </Flexbox>
+ )}
+ <AsyncBoundary
+ data={data}
+ error={error}
+ errorVariant={'inline'}
+ isEmpty={!error && files.length === 0}
+ isLoading={isLoading}
+ empty={
+ <Center flex={1} paddingBlock={24}>
+ <Empty
+ description={t('workingPanel.claudeMemory.empty.description')}
+ icon={BrainIcon}
+ title={t('workingPanel.claudeMemory.empty.title')}
+ />
+ </Center>
+ }
+ onRetry={refresh}
+ >
+ {groups.map((group) => (
+ <SkillSection
+ key={group.key}
+ sectionHeader={{
+ count: group.files.length,
+ title: t(`workingPanel.claudeMemory.group.${group.key}`),
+ }}
+ >
+ {group.files.map((file) => (
+ <MemoryRow
+ file={file}
+ indexHint={t('workingPanel.claudeMemory.indexHint')}
+ key={file.path}
+ onOpen={openMemory}
+ />
+ ))}
+ </SkillSection>
+ ))}
+ </AsyncBoundary>
+ </Flexbox>
+ );
+});
+
+MemoryPane.displayName = 'ClaudeCodeMemoryPane';
diff --git a/src/features/Conversation/WorkingSidebar/Memory/memoryView.test.ts b/src/features/Conversation/WorkingSidebar/Memory/memoryView.test.ts
new file mode 100644
index 00000000000..c403048067c
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Memory/memoryView.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+
+import { groupMemoryFiles, memoryFilePortalTarget } from './memoryView';
+
+const file = (relativePath: string, type?: string) => ({
+ isIndex: relativePath === 'MEMORY.md',
+ name: relativePath,
+ path: `/memory/${relativePath}`,
+ relativePath,
+ size: 1,
+ type,
+ updatedAt: 0,
+});
+
+describe('groupMemoryFiles', () => {
+ it('orders the index, the known types, then untyped files, dropping empty groups', () => {
+ const groups = groupMemoryFiles([
+ file('a.md', 'reference'),
+ file('MEMORY.md'),
+ file('b.md', 'custom'),
+ file('c.md', 'user'),
+ file('d.md'),
+ file('e.md', 'user'),
+ ]);
+
+ expect(groups.map((group) => [group.key, group.files.map((f) => f.relativePath)])).toEqual([
+ ['index', ['MEMORY.md']],
+ ['user', ['c.md', 'e.md']],
+ ['reference', ['a.md']],
+ ['other', ['b.md', 'd.md']],
+ ]);
+ });
+
+ it('returns no groups for no files', () => {
+ expect(groupMemoryFiles([])).toEqual([]);
+ });
+});
+
+describe('memoryFilePortalTarget', () => {
+ it('roots the tab at the memory directory and keeps it visible outside the project', () => {
+ expect(memoryFilePortalTarget(file('about.md', 'user'), '/memory', 'device-1')).toEqual({
+ allowExternalFilePreview: true,
+ deviceId: 'device-1',
+ filePath: '/memory/about.md',
+ workingDirectory: '/memory',
+ });
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Memory/memoryView.ts b/src/features/Conversation/WorkingSidebar/Memory/memoryView.ts
new file mode 100644
index 00000000000..6d142607059
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Memory/memoryView.ts
@@ -0,0 +1,54 @@
+import type { DeviceClaudeCodeMemoryFile } from '@lobechat/types';
+
+/** Claude Code's memory types, in the order the pane lists them. */
+const MEMORY_TYPES = ['user', 'feedback', 'project', 'reference'] as const;
+
+export type MemoryGroupKey = 'index' | 'other' | (typeof MEMORY_TYPES)[number];
+
+export interface MemoryGroup {
+ files: DeviceClaudeCodeMemoryFile[];
+ key: MemoryGroupKey;
+}
+
+const isMemoryType = (type: string | undefined): type is (typeof MEMORY_TYPES)[number] =>
+ !!type && (MEMORY_TYPES as readonly string[]).includes(type);
+
+/**
+ * Group memory files the way Claude Code organizes them: the `MEMORY.md` index,
+ * then one group per frontmatter type, then anything untyped. Empty groups are
+ * dropped; files keep their scan order within a group.
+ */
+export const groupMemoryFiles = (files: DeviceClaudeCodeMemoryFile[]): MemoryGroup[] => {
+ const buckets = new Map<MemoryGroupKey, DeviceClaudeCodeMemoryFile[]>();
+
+ for (const file of files) {
+ const key: MemoryGroupKey = file.isIndex
+ ? 'index'
+ : isMemoryType(file.type)
+ ? file.type
+ : 'other';
+ const bucket = buckets.get(key) ?? [];
+ bucket.push(file);
+ buckets.set(key, bucket);
+ }
+
+ return (['index', ...MEMORY_TYPES, 'other'] as const)
+ .filter((key) => buckets.has(key))
+ .map((key) => ({ files: buckets.get(key)!, key }));
+};
+
+/**
+ * Where a memory file opens: the local-file portal, rooted at the memory
+ * directory the scan approved (which is also what lets the portal save it), and
+ * marked external so the tab stays visible in a topic scoped to the project.
+ */
+export const memoryFilePortalTarget = (
+ file: DeviceClaudeCodeMemoryFile,
+ memoryDir: string,
+ deviceId: string | undefined,
+) => ({
+ allowExternalFilePreview: true,
+ deviceId,
+ filePath: file.path,
+ workingDirectory: memoryDir,
+});
diff --git a/src/features/Conversation/WorkingSidebar/Memory/useClaudeCodeMemory.test.ts b/src/features/Conversation/WorkingSidebar/Memory/useClaudeCodeMemory.test.ts
new file mode 100644
index 00000000000..72f35374641
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Memory/useClaudeCodeMemory.test.ts
@@ -0,0 +1,114 @@
+import { renderHook, waitFor } from '@testing-library/react';
+import { createElement, type ReactNode } from 'react';
+import { SWRConfig } from 'swr';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useClaudeCodeMemory } from './useClaudeCodeMemory';
+
+const mocks = vi.hoisted(() => ({
+ agentEnv: {} as Record<string, Record<string, string> | undefined>,
+ isDesktop: true,
+ listMemory: vi.fn(),
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ get isDesktop() {
+ return mocks.isDesktop;
+ },
+}));
+vi.mock('@/services/claudeCodeMemory', () => ({
+ claudeCodeMemoryService: { listMemory: mocks.listMemory },
+}));
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: (agentId: string) => () => ({
+ heterogeneousProvider: { env: mocks.agentEnv[agentId], type: 'claude-code' },
+ }),
+ },
+}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => undefined,
+}));
+
+const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(SWRConfig, { value: { provider: () => new Map() } }, children);
+
+const memoryDir = '/home/me/.claude/projects/-repo/memory';
+
+describe('useClaudeCodeMemory', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.agentEnv = {};
+ mocks.isDesktop = true;
+ });
+
+ it('reads the project memory over the local desktop transport', async () => {
+ mocks.listMemory.mockResolvedValue({ files: [], memoryDir });
+
+ const { result } = renderHook(() => useClaudeCodeMemory({ workingDirectory: '/repo' }), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(result.current.data).toEqual({ files: [], memoryDir }));
+ expect(mocks.listMemory).toHaveBeenCalledWith({
+ agentId: undefined,
+ deviceId: undefined,
+ env: { CLAUDE_CODE_PROJECT_DIR_NAME: undefined, CLAUDE_CONFIG_DIR: undefined },
+ workingDirectory: '/repo',
+ });
+ });
+
+ it("follows the agent's own Claude Code config dir, as its runs do", async () => {
+ mocks.agentEnv['agent-1'] = { CLAUDE_CONFIG_DIR: '/home/me/.claude-work', OTHER: 'x' };
+ mocks.listMemory.mockResolvedValue({ files: [], memoryDir });
+
+ const { result } = renderHook(
+ () => useClaudeCodeMemory({ agentId: 'agent-1', workingDirectory: '/repo' }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ expect(mocks.listMemory).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ deviceId: undefined,
+ env: { CLAUDE_CODE_PROJECT_DIR_NAME: undefined, CLAUDE_CONFIG_DIR: '/home/me/.claude-work' },
+ workingDirectory: '/repo',
+ });
+ });
+
+ it('stays inert without a project folder, or on web without a bound device', () => {
+ renderHook(() => useClaudeCodeMemory({}), { wrapper });
+ mocks.isDesktop = false;
+ renderHook(() => useClaudeCodeMemory({ workingDirectory: '/repo' }), { wrapper });
+
+ expect(mocks.listMemory).not.toHaveBeenCalled();
+ });
+
+ it('reports an offline device as an error, not as an empty memory', async () => {
+ mocks.listMemory.mockResolvedValue(null);
+
+ const { result } = renderHook(
+ () =>
+ useClaudeCodeMemory({
+ agentId: 'agent-1',
+ deviceId: 'device-1',
+ workingDirectory: '/repo',
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.error).toBeInstanceOf(Error));
+ expect(result.current.data).toBeUndefined();
+ expect(mocks.listMemory).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ deviceId: 'device-1',
+ workingDirectory: '/repo',
+ }),
+ );
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Memory/useClaudeCodeMemory.ts b/src/features/Conversation/WorkingSidebar/Memory/useClaudeCodeMemory.ts
new file mode 100644
index 00000000000..a94f59fbfb4
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Memory/useClaudeCodeMemory.ts
@@ -0,0 +1,58 @@
+import { isDesktop } from '@lobechat/const';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { localFileKeys } from '@/libs/swr/keys';
+import { claudeCodeMemoryService } from '@/services/claudeCodeMemory';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+type MemoryEnvKey = 'CLAUDE_CODE_PROJECT_DIR_NAME' | 'CLAUDE_CONFIG_DIR';
+
+/** One of the agent's own env values that move where its runs keep memory. */
+const useAgentMemoryEnv = (agentId: string | undefined, key: MemoryEnvKey) =>
+ useAgentStore((s) =>
+ agentId
+ ? agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider?.env?.[key]
+ : undefined,
+ );
+
+/**
+ * Claude Code's auto memory for `workingDirectory`, read from the execution
+ * device: Electron IPC on this desktop, the device RPC for a bound device.
+ * Follows the agent's own `CLAUDE_CONFIG_DIR` / `CLAUDE_CODE_PROJECT_DIR_NAME`,
+ * as its runs do. Inert until there is a directory and a transport. An offline
+ * device (`null` from the RPC) surfaces as an error, never as "no memory".
+ */
+export const useClaudeCodeMemory = ({
+ agentId,
+ deviceId,
+ workingDirectory,
+}: {
+ agentId?: string;
+ deviceId?: string;
+ workingDirectory?: string;
+}) => {
+ const configDir = useAgentMemoryEnv(agentId, 'CLAUDE_CONFIG_DIR');
+ const projectDirName = useAgentMemoryEnv(agentId, 'CLAUDE_CODE_PROJECT_DIR_NAME');
+ const key =
+ workingDirectory && (deviceId || isDesktop)
+ ? localFileKeys.claudeCodeMemory(deviceId, workingDirectory, configDir, projectDirName)
+ : null;
+
+ return useClientDataSWR(
+ key,
+ async () => {
+ const result = await claudeCodeMemoryService.listMemory({
+ agentId,
+ deviceId,
+ env: { CLAUDE_CODE_PROJECT_DIR_NAME: projectDirName, CLAUDE_CONFIG_DIR: configDir },
+ workingDirectory: workingDirectory!,
+ });
+ if (!result) throw new Error('The device did not return Claude Code memory');
+ return result;
+ },
+ // Claude Code writes memory between turns, and the user edits it in the
+ // portal, so a refocus re-reads the directory instead of waiting minutes.
+ { focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },
+ );
+};
diff --git a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
index b9cb60195c7..08c5c4f4e13 100644
--- a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
+++ b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
@@ -28,6 +28,7 @@ const rightPanel = vi.hoisted(() => ({
const agentStore = vi.hoisted(() => ({
activeAgentId: undefined as string | undefined,
+ heterogeneousType: undefined as string | undefined,
isHeterogeneous: false,
rawAgencyConfig: undefined as
{ boundDeviceId?: string; executionTarget?: 'device' | 'local' } | undefined,
@@ -85,6 +86,8 @@ const filesPrefetchProps = vi.hoisted(() => ({
const reviewState = vi.hoisted(() => ({
repoType: undefined as string | undefined,
setRepoType: undefined as ((repoType?: string) => void) | undefined,
+ /** The directory only comes from the desktop home fallback, not a user choice. */
+ isHomeFallback: false,
showTree: false,
workingDirectory: undefined as string | undefined,
}));
@@ -258,6 +261,7 @@ vi.mock('@/store/agent/selectors', () => ({
isWorkspaceAgentById: () => () => false,
},
agentSelectors: {
+ currentAgentHeterogeneousProviderType: () => agentStore.heterogeneousType,
isCurrentAgentHeterogeneous: () => agentStore.isHeterogeneous,
},
chatConfigByIdSelectors: {
@@ -286,6 +290,12 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => workspace.id,
}));
+vi.mock('@/features/Conversation/WorkingSidebar/Memory/MemoryPane', () => ({
+ MemoryPane: (props: { deviceId?: string; workingDirectory: string }) => (
+ <div data-testid="memory-pane">{props.workingDirectory}</div>
+ ),
+}));
+
vi.mock('@/business/client/features/WorkingSidebarTabs', () => ({
useBusinessWorkingSidebarTabs: () => businessTabs.current,
}));
@@ -302,7 +312,10 @@ vi.mock('@/features/ChatInput/ControlBar/useRepoType', async () => {
};
});
vi.mock('@/hooks/useEffectiveWorkingDirectory', () => ({
- useEffectiveWorkingDirectory: () => reviewState.workingDirectory,
+ useEffectiveWorkingDirectory: (_agentId?: string, options?: { homeFallback?: boolean }) =>
+ options?.homeFallback === false && reviewState.isHomeFallback
+ ? undefined
+ : reviewState.workingDirectory,
}));
vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
useEffectiveAgencyConfig: () => ({
@@ -455,6 +468,7 @@ beforeEach(() => {
chatStore.threadMaps = {};
chatStore.openTopicComments.mockReset();
agentStore.activeAgentId = undefined;
+ agentStore.heterogeneousType = undefined;
agentStore.isHeterogeneous = false;
agentStore.rawAgencyConfig = undefined;
effectiveConfig.agencyConfig = undefined;
@@ -474,6 +488,7 @@ beforeEach(() => {
reviewState.setRepoType = undefined;
reviewState.showTree = false;
reviewState.workingDirectory = undefined;
+ reviewState.isHomeFallback = false;
dropdownMenuState.onOpenChangeComplete = undefined;
dropdownMenuState.items = [];
globalStore.status.workingSidebarWidth = 360;
diff --git a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
index a8ba4f77c0e..561965b3b80 100644
--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
@@ -793,6 +793,45 @@ describe('AgentWorkingSidebar — tab strip', () => {
expect(tabs[0]).toHaveAttribute('aria-pressed', 'true');
});
+ it('opens Claude Code memory by default once a project folder is selected', () => {
+ agentStore.activeAgentId = 'agent';
+ agentStore.heterogeneousType = 'claude-code';
+ agentStore.isHeterogeneous = true;
+ effectiveConfig.agencyConfig = { executionTarget: 'local' };
+ reviewState.workingDirectory = '/repo';
+ localStorageState.openTabsByContext = {};
+ globalStore.status.workingSidebarTab = 'claudeMemory';
+
+ render(<AgentWorkingSidebar />);
+
+ const tabs = Array.from(document.querySelectorAll<HTMLButtonElement>('button[data-tab-key]'));
+ expect(tabs.map((tab) => tab.dataset.tabKey)).toEqual(['files', 'skills', 'claudeMemory']);
+ expect(screen.getByTestId('memory-pane')).toHaveTextContent('/repo');
+ });
+
+ it.each([
+ ['another heterogeneous agent', 'codex', '/repo', false],
+ ['a Claude Code agent without a project folder', 'claude-code', undefined, false],
+ ['a Claude Code agent on the home fallback only', 'claude-code', '/home/me', true],
+ ])(
+ 'offers no memory tab for %s',
+ (_case, heterogeneousType, workingDirectory, isHomeFallback) => {
+ agentStore.activeAgentId = 'agent';
+ agentStore.heterogeneousType = heterogeneousType;
+ agentStore.isHeterogeneous = true;
+ effectiveConfig.agencyConfig = { executionTarget: 'local' };
+ reviewState.workingDirectory = workingDirectory;
+ reviewState.isHomeFallback = isHomeFallback;
+ localStorageState.openTabsByContext = {};
+
+ render(<AgentWorkingSidebar />);
+
+ const tabs = Array.from(document.querySelectorAll<HTMLButtonElement>('button[data-tab-key]'));
+ expect(tabs.map((tab) => tab.dataset.tabKey)).not.toContain('claudeMemory');
+ expect(screen.queryByTestId('memory-pane')).toBeNull();
+ },
+ );
+
it('creates an independent browser tab every time Browser is chosen', async () => {
localStorageState.openTabsByContext = { 'draft:default:none': ['params'] };
globalStore.status.workingSidebarTab = 'params';
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index d9b3a8172e0..ecb7d27aa23 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -13,7 +13,6 @@ import {
GlobeIcon,
MessageCircleIcon,
PanelRightCloseIcon,
- PanelsTopLeftIcon,
PlusIcon,
SearchIcon,
Settings2Icon,
@@ -34,7 +33,6 @@ import {
} from 'react';
import { useTranslation } from 'react-i18next';
-import { useBusinessWorkingSidebarTabs } from '@/business/client/features/WorkingSidebarTabs';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { isDesktop } from '@/const/version';
@@ -90,6 +88,7 @@ import { useLinkedPullRequest } from './PullRequest/useLinkedPullRequest';
import ResourcesSection from './ResourcesSection';
import Review from './Review';
import { TopicSearchPane } from './Search';
+import { useExtraWorkingSidebarTabs } from './useExtraWorkingSidebarTabs';
import { useRetainAfterHide } from './useRetainAfterHide';
import { useSandboxFilesDirectory } from './useSandboxFilesDirectory';
import { useTabContextMenuItems } from './useTabContextMenuItems';
@@ -428,7 +427,12 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
{},
);
- const businessTabs = useBusinessWorkingSidebarTabs({ activeAgentId, topicId });
+ const extraTabs = useExtraWorkingSidebarTabs({
+ activeAgentId,
+ environmentWorkingDirectory,
+ remoteDeviceId,
+ topicId,
+ });
const commentsAvailable = !!workspaceId && !!topicId;
const currentCommentTopicId =
currentPortalView?.type === PortalViewType.TopicComments ||
@@ -487,15 +491,11 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
},
]
: []),
- ...businessTabs.map((tab) => ({
- icon: PanelsTopLeftIcon,
- key: tab.key,
- label: tab.label,
- })),
+ ...extraTabs,
],
[
browserAvailable,
- businessTabs,
+ extraTabs,
commentsAvailable,
filesAvailable,
isHetero,
@@ -522,8 +522,8 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
const pinnedTabsAgentKey = activeAgentId ?? 'default';
const defaultOpenedTabs = useMemo(
() =>
- [filesAvailable ? 'files' : undefined, 'skills', isHetero ? undefined : 'documents'].filter(
- (tab): tab is string => Boolean(tab) && isAvailableTab(tab!),
+ [filesAvailable && 'files', 'skills', isHetero ? 'claudeMemory' : 'documents'].filter(
+ (tab): tab is string => !!tab && isAvailableTab(tab),
),
[filesAvailable, isAvailableTab, isHetero],
);
@@ -894,7 +894,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
'skills',
'documents',
'web',
- ...businessTabs.map((tab) => tab.key),
+ ...extraTabs.map((tab) => tab.key),
]);
const toolChildren = [itemOf('browser')].filter((item): item is DropdownItem => Boolean(item));
if (terminalAvailable) {
@@ -924,7 +924,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
);
}, [
availableTabs,
- businessTabs,
+ extraTabs,
openBrowserTab,
openTab,
openedTabs,
@@ -1148,7 +1148,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
);
}}
/>
- {businessTabs.map((tab) => (
+ {extraTabs.map((tab) => (
<Flexbox
className={activeTab === tab.key ? styles.pane : styles.paneHidden}
key={tab.key}
diff --git a/src/features/Conversation/WorkingSidebar/useExtraWorkingSidebarTabs.tsx b/src/features/Conversation/WorkingSidebar/useExtraWorkingSidebarTabs.tsx
new file mode 100644
index 00000000000..92444c444e0
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/useExtraWorkingSidebarTabs.tsx
@@ -0,0 +1,79 @@
+import type { IconProps } from '@lobehub/ui';
+import { BrainIcon, PanelsTopLeftIcon } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ type BusinessWorkingSidebarTab,
+ useBusinessWorkingSidebarTabs,
+} from '@/business/client/features/WorkingSidebarTabs';
+import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+
+import { MemoryPane } from './Memory/MemoryPane';
+
+const CLAUDE_MEMORY_TAB_KEY = 'claudeMemory';
+
+export interface ExtraWorkingSidebarTab extends BusinessWorkingSidebarTab {
+ icon: IconProps['icon'];
+}
+
+interface ExtraWorkingSidebarTabsContext {
+ activeAgentId?: string;
+ /** The project directory, only while a filesystem (this desktop or a bound device) runs it. */
+ environmentWorkingDirectory?: string;
+ /** Bound device that serves the filesystem; `undefined` for this desktop. */
+ remoteDeviceId?: string;
+ topicId?: string;
+}
+
+/**
+ * Tabs that carry their own pane, mounted beside the built-in ones: Claude
+ * Code's project memory when the agent is Claude Code and a project folder is
+ * selected, then the business-provided tabs.
+ */
+export const useExtraWorkingSidebarTabs = ({
+ activeAgentId,
+ environmentWorkingDirectory,
+ remoteDeviceId,
+ topicId,
+}: ExtraWorkingSidebarTabsContext): ExtraWorkingSidebarTab[] => {
+ const { t } = useTranslation('chat');
+ const isClaudeCode = useAgentStore(
+ (s) => agentSelectors.currentAgentHeterogeneousProviderType(s) === 'claude-code',
+ );
+ // On desktop the effective directory falls back to Desktop / home when none
+ // was chosen. Memory follows a project the user picked, so the tab waits for
+ // an explicit folder instead of showing the fallback's memory.
+ const selectedDirectory = useEffectiveWorkingDirectory(activeAgentId, { homeFallback: false });
+ const memoryDirectory =
+ selectedDirectory && selectedDirectory === environmentWorkingDirectory
+ ? environmentWorkingDirectory
+ : undefined;
+ const businessTabs = useBusinessWorkingSidebarTabs({ activeAgentId, topicId });
+
+ return useMemo(
+ () => [
+ ...(isClaudeCode && memoryDirectory
+ ? [
+ {
+ icon: BrainIcon,
+ key: CLAUDE_MEMORY_TAB_KEY,
+ label: t('workingPanel.claudeMemory.title'),
+ pane: (
+ <MemoryPane
+ agentId={activeAgentId}
+ deviceId={remoteDeviceId}
+ key={`${remoteDeviceId ?? 'local'}:${memoryDirectory}`}
+ workingDirectory={memoryDirectory}
+ />
+ ),
+ },
+ ]
+ : []),
+ ...businessTabs.map((tab) => ({ icon: PanelsTopLeftIcon, ...tab })),
+ ],
+ [activeAgentId, businessTabs, isClaudeCode, memoryDirectory, remoteDeviceId, t],
+ );
+};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 9ea0de6c4b8..d39d7c1131b 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -797,6 +797,21 @@ export const forkKeys = {
// ---- local file ---------------------------------------------------------
export const localFileKeys = {
+ claudeCodeMemory: def(
+ 'localFile:claudeCodeMemory',
+ (
+ deviceId: string | undefined,
+ workingDirectory: string,
+ configDir?: string,
+ projectDirName?: string,
+ ) => [
+ 'localFile:claudeCodeMemory',
+ deviceId ?? 'local',
+ workingDirectory,
+ configDir ?? '',
+ projectDirName ?? '',
+ ],
+ ),
gitWorkingTreeFiles: def(
'localFile:gitWorkingTreeFiles',
(deviceId: string | undefined, dirPath: string) => [
diff --git a/src/services/claudeCodeMemory.ts b/src/services/claudeCodeMemory.ts
new file mode 100644
index 00000000000..725e734793b
--- /dev/null
+++ b/src/services/claudeCodeMemory.ts
@@ -0,0 +1,37 @@
+import type {
+ DeviceClaudeCodeMemoryRunEnv,
+ DeviceListClaudeCodeMemoryResult,
+} from '@lobechat/types';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import { ensureElectronIpc } from '@/utils/electron/ipc';
+
+/**
+ * Claude Code auto-memory chokepoint. A bound device answers over the
+ * `device.listClaudeCodeMemory` RPC; the local desktop scans over Electron IPC.
+ * (Parallels `projectSkillService`.)
+ */
+class ClaudeCodeMemoryService {
+ /** Memory files under `~/.claude/projects/<project key>/memory` for `workingDirectory`. */
+ async listMemory({
+ agentId,
+ deviceId,
+ env,
+ workingDirectory,
+ }: {
+ agentId?: string;
+ deviceId?: string;
+ /**
+ * The agent's own Claude Code env, for the local scan. A bound device gets
+ * it from `agentId` on the server instead, which owns the approved roots.
+ */
+ env?: DeviceClaudeCodeMemoryRunEnv;
+ workingDirectory: string;
+ }): Promise<DeviceListClaudeCodeMemoryResult | null> {
+ return deviceId
+ ? lambdaClient.device.listClaudeCodeMemory.query({ agentId, deviceId, workingDirectory })
+ : ensureElectronIpc().workspace.listClaudeCodeMemory({ env, scope: workingDirectory });
+ }
+}
+
+export const claudeCodeMemoryService = new ClaudeCodeMemoryService();