Skip to content

feat(server): report an unusable default workspace with its path and reason - #4243

Closed
wbxl2000 wants to merge 11 commits into
mainfrom
qer/default-workspace-unavailable-error
Closed

wbxl2000 wants to merge 11 commits into
mainfrom
qer/default-workspace-unavailable-error

Conversation

@wbxl2000

@wbxl2000 wbxl2000 commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

默认工作区无法使用时,返回带路径和原因的专用错误码 40930,让客户端能说清楚出了什么问题、该怎么修。

依赖 #4224,合入顺序在它之后;从 #4233 拆出,后续依次是 #4244(位置可配置)和 #4245(CLI 与 SDK)。目标分支为 main,#4224 合入前这里的 diff 包含它的提交;本层改动见 753ba6ef2、bc3dd3a4c。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

 IDefaultWorkspace.ensure()
   mkdir -p <root>
-    被文件占用 → Error2(FS_PATH_NOT_FOUND);其他错误原样抛出
+    失败 → DefaultWorkspaceUnavailableError({ path, reason })
+  在文件夹里建一个探测文件再删掉;建不了或删不掉 → 同上
 Windows 找不到文稿目录
-  Error2(FS_PATH_NOT_FOUND)
+  DefaultWorkspaceUnavailableError({ path: undefined, reason: 'documents_unavailable' })

原因由 fs 错误码和 errno 映射:已存在 / 不是目录 → blocked_by_file,权限 → permission_denied,父目录不存在 → missing_parent,ENOSPC/EDQUOT → no_space,EROFS → read_only,ENAMETOOLONG → invalid_path,其余 → unknown。

 POST /api/v1/sessions  default_workspace: true
   sendMappedError
+    先尝试 DefaultWorkspaceUnavailableError → 40930
+    { code: 40930, data: { path: string | null, reason } }

errors.ts 新增错误域 default_workspace.unavailable,导出 DefaultWorkspaceUnavailableError 和每种原因的英文说明 DEFAULT_WORKSPACE_PROBLEM_MESSAGES;invalid_path 的说明写的是「不是绝对路径或过长」,前半句在下一个 PR 引入自定义路径后才会出现。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
POST /sessions default_workspace: true 时文件夹无法创建 被占用 40409,权限 40411,其他 50001 40930,data 带 path 和 reason #4224 尚未发布,无外部依赖;desktop / web 按通用错误显示 无;两者都是失败响应
Windows 找不到文稿目录 40409 40930,reason: documents_unavailable,path: null 同上 无
文件夹存在但不可写 会话照常创建,之后写文件失败 40930(permission_denied / read_only 等),不创建会话 无 修复文件夹权限

受影响模块与测试覆盖:

  • agent-core-v2/app/defaultWorkspace:defaultWorkspace.test.ts 覆盖被文件占用(默认文件夹本身和父文件夹)、权限不足、路径上的悬空符号链接、Windows 找不到文稿目录(含重试)各自报出对应原因;已有文件夹变为不可写时 ensure() 拒绝交出且不留探测文件;探测文件删不掉时报 permission_denied。
  • kap-server:sessions.test.ts 的权限错误改为断言 40930 和 { path, reason },且不注册工作区。
  • docs/{en,zh}/reference/server-api.md:会话创建的错误码列表同步更新。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

POST /api/v1/sessions accepts default_workspace: true, exclusive with
workspace_id and metadata.cwd. The server resolves <Documents>/KimiCode/Default
on every request, creates it on first use, and reuses it afterwards. A path
blocked by a file fails with 40409 and a permission error with 40411; the
server never relocates silently.

Workspace payloads on REST and WebSocket events carry is_default.
… be resolved

A failed registry lookup used to fall back to %USERPROFILE%\Documents, which
could silently create a second default workspace when Documents is redirected
(for example by OneDrive). The lookup now fails with 40409, the failure is not
cached so the next request retries, and is_default reports false meanwhile.
Reading User Shell Folders with reg.exe misses the default when the value is
absent, cannot expand every variable, and is blocked where registry tools are
disabled by policy. Ask Windows for the Documents folder through PowerShell
instead, forcing UTF-8 output so non-ASCII paths survive. A reported folder
that does not exist is treated as unresolved, so garbled output can never
create a workspace in the wrong place.
The Documents lookup spawned the bare name powershell.exe, so Windows
resolved it through the current directory and PATH. In an untrusted
checkout that lets a repository-provided powershell.exe run before the
trust gate. Resolve it under SystemRoot (falling back to windir and
then C:\Windows) instead.
…reason

Creating a session in the default workspace used to surface folder problems
as generic codes: 40409 when a file blocked the path or the Windows
Documents folder could not be located, 40411 on permission errors, and a
plain internal error for anything else. Clients could not tell the default
workspace apart from an ordinary missing directory, nor explain what to fix.

DefaultWorkspaceService now throws DefaultWorkspaceUnavailableError
(default_workspace.unavailable) carrying the folder path and one of
blocked_by_file, permission_denied, missing_parent, no_space, read_only,
invalid_path, documents_unavailable or unknown. ensure() also verifies that
a file can be created and removed in the folder, so a read-only folder is
reported before a session is placed there. The server maps the error to
40930 with { path, reason } in data.
@changeset-bot

changeset-bot Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: e50d0d3

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@pkg-pr-new

pkg-pr-new Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@e50d0d3
npx https://pkg.pr.new/@moonshot-ai/kimi-code@e50d0d3

commit: e50d0d3

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 753ba6ef27

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T11:50:14.064523Z e50d0d3 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@wbxl2000
wbxl2000 changed the base branch from qer/default-workspace to main October 15, 2026 11:34
Copilot AI balanced review requested due to automatic review settings October 15, 2026 11:38
createExclusive resolves to false when the probe name already exists. The
write check ignored that result and went on to remove the path, which is a
recursive delete of an entry it did not create. Report the folder as
unknown instead and leave the entry alone.
…e-error' into qer/default-workspace-unavailable-error

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

错误分类、可用性检查与响应契约一致,未发现阻塞问题;未运行项目测试。

0 open findings

What changed in this PR

在 #4224 的默认工作区能力上,统一返回错误码 40930,附带路径和失败原因,便于客户端提供修复提示。当前 diff 同时包含前序 PR 的基础改动。

Changes:

  • 新增默认工作区错误分类及创建、删除探测文件的可用性检查。
  • 将错误映射为包含 { path, reason } 的服务端响应。
  • 补充相关测试并同步中英文 API 文档。
File Description
packages/​kap-server/​test/​workspaces.test.ts 验证默认工作区标记
packages/​kap-server/​test/​sessions.test.ts 覆盖默认创建、互斥校验及错误响应
packages/​kap-server/​test/​sessionEventBroadcaster.test.ts 更新工作区事件断言
packages/​kap-server/​src/​routes/​workspaces.ts 计算响应中的默认标记
packages/​kap-server/​src/​routes/​sessions.ts 接入默认工作区及错误映射
packages/​kap-server/​src/​routes/​defaultWorkspace.ts 构造专用错误响应
packages/​kap-server/​src/​protocol/​workspace.ts 增加 is_default 字段
packages/​kap-server/​src/​protocol/​session.ts 接受 default_workspace 参数
packages/​kap-server/​src/​protocol/​error-codes.ts 定义错误码 40930
packages/​kap-server/​src/​protocol/​default-workspace.ts 定义错误数据结构
packages/​agent-core-v2/​test/​app/​defaultWorkspace/​defaultWorkspace.test.ts 覆盖路径解析、可用性检查及失败分类
packages/​agent-core-v2/​src/​index.ts 导出默认工作区服务及错误
packages/​agent-core-v2/​src/​errors.ts 注册默认工作区错误域
packages/​agent-core-v2/​src/​app/​workspace/​workspaceProtocol.ts 扩展工作区协议
packages/​agent-core-v2/​src/​app/​defaultWorkspace/​errors.ts 定义错误类型及原因说明
packages/​agent-core-v2/​src/​app/​defaultWorkspace/​defaultWorkspaceService.ts 实现目录准备、探测及错误分类
packages/​agent-core-v2/​src/​app/​defaultWorkspace/​defaultWorkspacePaths.ts 解析各平台文稿目录
packages/​agent-core-v2/​src/​app/​defaultWorkspace/​defaultWorkspace.ts 定义服务接口
docs/​zh/​reference/​server-api.md 更新中文接口说明
docs/​en/​reference/​server-api.md 更新英文接口说明

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e50d0d3386

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

const proc = await this.processes.spawn(
windowsPowerShellPath(this.bootstrap.getEnv('SystemRoot') ?? this.bootstrap.getEnv('windir')),
['-NoProfile', '-NonInteractive', '-Command', WINDOWS_DOCUMENTS_COMMAND],
{ windowsHide: true, timeout: WINDOWS_DOCUMENTS_TIMEOUT_MS },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce the declared PowerShell timeout

When PowerShell hangs on Windows, this call never completes: HostProcessService.buildSpawnOptions() does not forward HostProcessOptions.timeout, and HostProcess.wait() implements no timeout itself. Because toWireWorkspace() now calls isDefault() for every workspace projection, this can indefinitely hang existing GET/POST/PATCH workspace requests as well as default-workspace session creation, rather than failing after 15 seconds. Race the process against a timer and terminate it, or implement the option in the host-process backend.

AGENTS.md reference: AGENTS.md:L102-L104

Useful? React with 👍 / 👎.

Comment on lines +98 to +99
dir = await this.queryWindowsDocumentsDir();
if (dir !== undefined && !(await this.isDirectory(dir))) dir = undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the resolved Windows path when validation fails

When Windows successfully resolves MyDocuments but stat is denied by its ACL, or the resolved path is occupied by a file, this assignment discards the known path and reports documents_unavailable with path: null. Clients therefore receive neither the actionable path nor the intended permission_denied/blocked_by_file reason. Preserve the resolved path and map the stat error or non-directory result instead of treating every validation failure as an unresolved Documents folder.

Useful? React with 👍 / 👎.

Comment on lines +137 to +138
const configHome =
this.bootstrap.getEnv('XDG_CONFIG_HOME') ?? join(this.bootstrap.osHomeDir, '.config');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Validate XDG_CONFIG_HOME before using it

On Linux, XDG_CONFIG_HOME="" is defined but means the default ~/.config, while a relative value is invalid; this nullish fallback accepts both and reads user-dirs.dirs relative to the server working directory instead. The read failure is then swallowed, so a valid ~/.config/user-dirs.dirs redirect is silently ignored and default_workspace: true creates sessions under ~/Documents rather than the user's configured Documents folder. Treat empty or non-absolute values as unset, as required by the XDG Base Directory specification.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

const match = /^\s*XDG_DOCUMENTS_DIR\s*=\s*"(.*)"\s*$/.exec(line);
if (match === null) continue;
const raw = match[1]!;
const expanded = raw.replace(/^\$HOME(?=\/|$)/, osHomeDir);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Decode shell escapes in XDG document paths

The xdg-user-dirs format is shell-formatted, and its writer escapes literal dollar signs, backticks, and backslashes. For example, the valid value XDG_DOCUMENTS_DIR="$HOME/Docs\$2026" represents /home/alice/Docs$2026, but this replacement leaves the escape character in place and creates /home/alice/Docs\$2026/KimiCode/Default instead. Decode the supported shell escapes before validating and returning the path so the configured directory is not silently replaced by a newly created lookalike.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

@wbxl2000

Copy link
Copy Markdown
Collaborator Author

已并入 #4224。

@wbxl2000 wbxl2000 closed this Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants