Skip to content

/clear 命令会把 workingDirectory 重置为默认值 —— clearSession 闭包未把 session 传给 clear() #44

Description

@c70118

问题

/clear 会把 session.workingDirectory 重置回 DEFAULT_WORKING_DIR~/Documents/ClaudeCode),完全无视 session JSON 里已持久化的值和 config.json 的配置。/clear 之后下一条消息会在错误的项目目录下新建 SDK session。

复现步骤

  1. setup 时把工作目录设为非默认值(例如 /home/user/myproject),或之后编辑 ~/.wechat-claude-code/config.json
  2. 在微信发任意消息 → session JSON 被创建并持久化,workingDirectory 为正确值。
  3. /status → 确认 工作目录: /home/user/myproject
  4. /clear
  5. 再发 /status(或任意消息)→ 工作目录 已变成 ~/Documents/ClaudeCode,且新的 sdkSessionId 属于 ~-Documents-ClaudeCode 项目,而不是配置的那个。

预期 vs 实际

  • 预期/clear 只清 sdkSessionIdchatHistory保留 workingDirectoryclear()currentSession 参数明显就是为此设计的)。
  • 实际workingDirectory 被重置为 DEFAULT_WORKING_DIR~/Documents/ClaudeCode)。

根因

Session.clear() 本来就接受当前 session 作为参数,用于把 workingDirectory 带过来:

// src/session.ts:67
function clear(accountId: string, currentSession?: Session): Session {
  const session: Session = {
    sdkSessionId: undefined,
    workingDirectory: currentSession?.workingDirectory ?? DEFAULT_WORKING_DIR,  // ← currentSession 为 undefined 时回退到默认值
    ...
  };
}

但唯一的调用点没传它:

// src/main.ts:389
clearSession: () => sessionStore.clear(account.accountId),   // ← 没传 session

所以 currentSession 永远是 undefinedworkingDirectory 永远回退到 DEFAULT_WORKING_DIR

补充:/resetsrc/commands/handlers.ts:127-128)也会调用 clearSession(),但紧接着又显式赋值 DEFAULT_WORKING_DIR,所以它的行为符合设计意图,不受此 bug 影响。只有 /clear 是坏的。

另外没有任何兜底机制能挽回目录:src/main.ts:257 的启动 backfill 只在 session.workingDirectory === process.cwd()(daemon 进程的 cwd)时触发,本场景下永远不成立,所以也救不回来。

建议修复

一行改动:

--- a/src/main.ts
+++ b/src/main.ts
@@ -386,7 +386,7 @@
       accountId: account.accountId,
       session,
       updateSession,
-      clearSession: () => sessionStore.clear(account.accountId),
+      clearSession: () => sessionStore.clear(account.accountId, session),
       getChatHistoryText: (limit?: number) => sessionStore.getChatHistoryText(session, limit),
       text: userText,
     };

改完后 /clear 就能按原设计保留 workingDirectory。我本地已验证:打上补丁后 tsc 干净编译,/clear 之后目录保持不变。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions