Răsfoiți Sursa

Merge main into fix/compaction-empty-tools and preserve vendor change records

hetaoBackend 2 luni în urmă
părinte
comite
9c01a5bd11
91 a modificat fișierele cu 3221 adăugiri și 292 ștergeri
  1. 2 1
      .github/ISSUE_TEMPLATE/01-bug-report.yml
  2. 2 1
      .github/ISSUE_TEMPLATE/02-feature-request.yml
  3. 9 7
      .github/ISSUE_TEMPLATE/03-question.yml
  4. 3 0
      .github/ISSUE_TEMPLATE/config.yml
  5. 14 0
      .github/ISSUE_TEMPLATE/docs.yml
  6. 2 1
      .github/workflows/ci.yml
  7. 2 1
      .github/workflows/compatibility.yml
  8. 71 0
      .github/workflows/label-issue-product.yml
  9. 3 2
      .github/workflows/source-candidate.yml
  10. 3 3
      CONTRIBUTING.md
  11. 56 0
      README.md
  12. 56 0
      README_ZH.md
  13. 97 1
      docs/examples.md
  14. 48 2
      docs/installation.md
  15. 23 0
      docs/maintainers.md
  16. 4 2
      docs/releasing.md
  17. 35 1
      docs/tui-capabilities.md
  18. 3 1
      packages/agent-modules/permission/src/tools/fs-permission.ts
  19. 8 17
      packages/local-runtime-v2/src/application/session/process-local-application-contract.ts
  20. 5 13
      packages/local-runtime-v2/src/application/session/process-local-application.ts
  21. 23 0
      packages/local-runtime-v2/src/service/model-system/catalog/list-models.test.ts
  22. 113 0
      packages/local-runtime-v2/src/service/model-system/catalog/provider-presets/provider-presets.service.test.ts
  23. 28 0
      packages/local-runtime-v2/src/service/model-system/catalog/provider-presets/provider-presets.service.ts
  24. 1 0
      packages/local-runtime-v2/src/service/model-system/contracts.ts
  25. 42 0
      packages/local-runtime-v2/src/service/model-system/management/service-input.test.ts
  26. 3 0
      packages/local-runtime-v2/src/service/model-system/management/service-input.ts
  27. 89 3
      packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.test.ts
  28. 39 0
      packages/local-runtime-v2/src/service/model-system/resolution/model-ref.test.ts
  29. 11 0
      packages/local-runtime-v2/src/service/turn-system/agent-host/runner/local-agent-turn-runner.ts
  30. 3 1
      packages/local-runtime-v2/test/unit/agent/storage/agent.repository.test.ts
  31. 39 20
      packages/local-runtime/src/content-safety/api-v2.ts
  32. 34 41
      packages/local-runtime/src/content-safety/api.ts
  33. 27 0
      packages/local-runtime/src/content-safety/diagnostics.ts
  34. 15 4
      packages/local-runtime/src/permissions/facade.ts
  35. 11 0
      packages/local-runtime/src/runtime/host.ts
  36. 3 1
      packages/local-runtime/test/unit/child-bash-lifecycle.test.ts
  37. 62 38
      packages/local-runtime/test/unit/content-safety-api-fail-policy.test.ts
  38. 83 1
      packages/local-runtime/test/unit/content-safety-api-v2.test.ts
  39. 109 0
      packages/local-runtime/test/unit/local-permission-facade.test.ts
  40. 88 1
      packages/local-runtime/test/unit/local-runtime-host-output-safety-concurrency.test.ts
  41. 16 3
      packages/local-runtime/test/unit/session-diff-fallback.test.ts
  42. 2 1
      packages/shared/src/asset-markup/deliver-assets.ts
  43. 50 4
      packages/shared/src/safety-check-v2.ts
  44. 3 1
      packages/tui/docs/status-line-config.md
  45. 42 19
      packages/tui/src/acp/agent.ts
  46. 36 2
      packages/tui/src/acp/commands.ts
  47. 2 1
      packages/tui/src/application/assistant-content.ts
  48. 14 0
      packages/tui/src/cli/contract.ts
  49. 7 1
      packages/tui/src/cli/environment.ts
  50. 2 0
      packages/tui/src/cli/main.ts
  51. 1 1
      packages/tui/src/cli/network-proxy.ts
  52. 3 0
      packages/tui/src/cli/program.ts
  53. 2 0
      packages/tui/src/cli/provider-command.ts
  54. 3 0
      packages/tui/src/provider/contract.ts
  55. 6 2
      packages/tui/src/runtime/adapter.ts
  56. 2 1
      packages/tui/src/runtime/adapters/product-access.ts
  57. 1 1
      packages/tui/src/runtime/port.ts
  58. 1 1
      packages/tui/src/tui/controller/product/command-flow.ts
  59. 1 1
      packages/tui/src/tui/controller/runtime/runtime-event-flow.ts
  60. 11 4
      packages/tui/src/tui/engine/LOCAL_CHANGES.json
  61. 9 0
      packages/tui/src/tui/engine/LOCAL_CHANGES.md
  62. 8 2
      packages/tui/src/tui/engine/components/scroll-view.ts
  63. 42 18
      packages/tui/src/tui/engine/tui-alt-screen.ts
  64. 14 3
      packages/tui/src/tui/engine/tui-main-screen.ts
  65. 1 0
      packages/tui/src/tui/features/settings/status-line-copy.ts
  66. 27 3
      packages/tui/src/tui/launcher.ts
  67. 2 0
      packages/tui/src/tui/shell/chat-layout.ts
  68. 20 8
      packages/tui/src/tui/shell/chrome.ts
  69. 4 1
      packages/tui/src/tui/shell/status-line-items.ts
  70. 216 2
      packages/tui/test/unit/acp-agent.test.ts
  71. 39 0
      packages/tui/test/unit/headless-model-selection.test.ts
  72. 70 0
      packages/tui/test/unit/network-proxy.test.ts
  73. 19 0
      packages/tui/test/unit/runtime-product-access.test.ts
  74. 247 5
      packages/tui/test/unit/tui-app.test.ts
  75. 83 0
      packages/tui/test/unit/tui-assistant-content.test.ts
  76. 113 1
      packages/tui/test/unit/tui-engine-local-deltas.test.ts
  77. 22 0
      packages/tui/test/unit/tui-model-picker.test.ts
  78. 305 0
      packages/tui/test/unit/tui-scrollbar-interaction.test.ts
  79. 191 0
      packages/tui/test/unit/tui-status-line-items.test.ts
  80. 2 2
      packages/tui/test/unit/tui-transcript-view.test.ts
  81. 29 0
      packages/tui/test/unit/tui-workspace-status-line.test.ts
  82. 14 1
      packages/tui/test/unit/tui/controller/product/command-flow.test.ts
  83. 17 0
      packages/tui/test/unit/tui/features/settings/status-line-picker.test.ts
  84. 5 0
      release/public-source.json
  85. 7 5
      scripts/source-candidate.mjs
  86. 72 1
      test/byok.test.mjs
  87. 36 20
      test/smoke.test.mjs
  88. 84 13
      test/source-sync.test.mjs
  89. 3 0
      test/vitest-suites.json
  90. 34 0
      third_party/pi-mono/MINIMAX_CHANGES.md
  91. 12 1
      third_party/pi-mono/packages/ai/src/providers/openai-completions.ts

+ 2 - 1
.github/ISSUE_TEMPLATE/01-bug-report.yml

@@ -1,7 +1,7 @@
 name: Bug report
 description: Report a reproducible problem with the Desktop app, CLI, or source build.
 title: "[Bug]: "
-labels: ["bug"]
+labels: ["bug", "needs-triage"]
 body:
   - type: markdown
     attributes:
@@ -10,6 +10,7 @@ body:
     id: product
     attributes:
       label: Product or interface
+      description: Desktop app and interactive TUI reports automatically receive the desktop or tui label.
       options:
         - Desktop app
         - CLI - interactive TUI

+ 2 - 1
.github/ISSUE_TEMPLATE/02-feature-request.yml

@@ -1,12 +1,13 @@
 name: Feature request
 description: Suggest an improvement to the Desktop app, CLI, or source distribution.
 title: "[Feature]: "
-labels: ["enhancement"]
+labels: ["enhancement", "needs-triage"]
 body:
   - type: dropdown
     id: product
     attributes:
       label: Product or interface
+      description: Desktop app and interactive TUI reports automatically receive the desktop or tui label.
       options:
         - Desktop app
         - CLI - interactive TUI

+ 9 - 7
.github/ISSUE_TEMPLATE/03-question.yml

@@ -1,12 +1,13 @@
-name: Usage question
-description: Ask about the Desktop app, CLI, or building from source.
+name: Usage or repository policy question
+description: Ask about the Desktop app, CLI, source builds, or contribution policy.
 title: "[Question]: "
-labels: ["question"]
+labels: ["question", "needs-triage"]
 body:
   - type: dropdown
     id: product
     attributes:
       label: Product or interface
+      description: Leave blank if unsure or asking about repository policy. Desktop app and interactive TUI reports automatically receive the desktop or tui label.
       options:
         - Desktop app
         - CLI - interactive TUI
@@ -14,7 +15,7 @@ body:
         - CLI - ACP
         - Source build or repository tooling
     validations:
-      required: true
+      required: false
   - type: textarea
     id: question
     attributes:
@@ -25,6 +26,7 @@ body:
     id: platform
     attributes:
       label: Platform
+      description: Leave blank if unknown or not applicable.
       options:
         - macOS
         - Windows
@@ -32,11 +34,11 @@ body:
         - WSL
         - Multiple platforms
     validations:
-      required: true
+      required: false
   - type: textarea
     id: context
     attributes:
-      label: Version and what you have tried
-      description: Include documentation you followed and relevant redacted output. Do not include keys or account data.
+      label: Version or policy context
+      description: For usage questions, include your version and what you tried. For policy questions, link the relevant policy. Do not include keys or account data.
     validations:
       required: true

+ 3 - 0
.github/ISSUE_TEMPLATE/config.yml

@@ -1,5 +1,8 @@
 blank_issues_enabled: false
 contact_links:
+  - name: Contribution policy
+    url: https://github.com/MiniMax-AI/minimax-code/blob/main/CONTRIBUTING.md
+    about: Everyone may report issues and suggest improvements. Pull requests are accepted only from repository collaborators; external PRs are not accepted.
   - name: CLI quick start and troubleshooting
     url: https://agent.minimax.io/docs/cli/quick-start
     about: Installation, account regions, first tasks, and links to troubleshooting.

+ 14 - 0
.github/ISSUE_TEMPLATE/docs.yml

@@ -1,7 +1,21 @@
 name: Documentation issue
 description: Report missing, incorrect, or unclear documentation.
 title: "[Docs] "
+labels: ["documentation", "needs-triage"]
 body:
+  - type: dropdown
+    id: product
+    attributes:
+      label: Product or interface
+      description: Desktop app and interactive TUI reports automatically receive the desktop or tui label.
+      options:
+        - Desktop app
+        - CLI - interactive TUI
+        - CLI - headless
+        - CLI - ACP
+        - Source build or repository tooling
+    validations:
+      required: true
   - type: input
     id: location
     attributes:

+ 2 - 1
.github/workflows/ci.yml

@@ -55,7 +55,8 @@ jobs:
     strategy:
       fail-fast: false
       matrix:
-        os: [ubuntu-latest, macos-latest, windows-latest]
+        # Windows validation is temporarily paused until its checks are reliable.
+        os: [ubuntu-latest, macos-latest]
         node: ["24"]
         include:
           - os: ubuntu-latest

+ 2 - 1
.github/workflows/compatibility.yml

@@ -16,7 +16,8 @@ jobs:
     strategy:
       fail-fast: false
       matrix:
-        os: [ubuntu-latest, macos-latest, windows-latest]
+        # Windows validation is temporarily paused until its checks are reliable.
+        os: [ubuntu-latest, macos-latest]
         node: ["22.19.0", "24.2.0", "25", "26"]
         include:
           - os: ubuntu-latest

+ 71 - 0
.github/workflows/label-issue-product.yml

@@ -0,0 +1,71 @@
+name: Label issue product
+
+on:
+  issues:
+    types: [opened, edited]
+
+permissions:
+  issues: write
+
+concurrency:
+  group: issue-product-${{ github.event.issue.number }}
+  cancel-in-progress: false
+
+jobs:
+  label-product:
+    runs-on: ubuntu-latest
+    timeout-minutes: 5
+    if: ${{ github.repository == 'MiniMax-AI/minimax-code' && github.event.repository.private == false && !github.event.issue.pull_request }}
+    steps:
+      - name: Synchronize product labels
+        env:
+          GH_TOKEN: ${{ github.token }}
+        shell: bash
+        run: |
+          node <<'EOF'
+          const fs = require('node:fs');
+
+          async function main() {
+            const event = JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8'));
+            const issuePath = `/repos/${process.env.GITHUB_REPOSITORY}/issues/${event.issue.number}`;
+            async function request(path, method = 'GET', body) {
+              const response = await fetch(`${process.env.GITHUB_API_URL}${path}`, {
+                method,
+                headers: {
+                  Authorization: `Bearer ${process.env.GH_TOKEN}`,
+                  Accept: 'application/vnd.github+json',
+                  'Content-Type': 'application/json',
+                },
+                body: body === undefined ? undefined : JSON.stringify(body),
+              });
+              if (!response.ok) throw new Error(`GitHub ${method} failed: ${response.status}`);
+              return response.status === 204 ? undefined : response.json();
+            }
+
+            // Read current state so queued edits cannot restore an outdated label.
+            const issue = await request(issuePath);
+            const body = (issue.body || '').replace(/\r\n/g, '\n');
+            const product = body.match(/^### Product or interface\n+([^\n]+)\n*(?=### |$)/m)?.[1].trim();
+            const products = new Map([
+              ['Desktop app', 'desktop'],
+              ['CLI - interactive TUI', 'tui'],
+              ['CLI - headless', null],
+              ['CLI - ACP', null],
+              ['Source build or repository tooling', null],
+            ]);
+            // Leave manually triaged issues alone when no valid form answer exists.
+            if (!products.has(product)) return;
+            const desired = products.get(product);
+            const labels = issue.labels.map(label => label.name);
+            if (desired && !labels.includes(desired)) {
+              await request(`${issuePath}/labels`, 'POST', { labels: [desired] });
+            }
+            for (const label of ['desktop', 'tui']) {
+              if (label !== desired && labels.includes(label)) {
+                await request(`${issuePath}/labels/${label}`, 'DELETE');
+              }
+            }
+          }
+
+          main();
+          EOF

+ 3 - 2
.github/workflows/source-candidate.yml

@@ -56,7 +56,8 @@ jobs:
     strategy:
       fail-fast: false
       matrix:
-        os: [ubuntu-latest, macos-latest, windows-latest]
+        # Windows validation is temporarily paused until its checks are reliable.
+        os: [ubuntu-latest, macos-latest]
     steps:
       - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
         with:
@@ -122,7 +123,7 @@ jobs:
         with:
           pattern: candidate-validation-*
           path: ${{ runner.temp }}/candidate/reports
-      - name: Require three matching validation reports
+      - name: Require matching Linux and macOS validation reports
         shell: bash
         run: node scripts/source-candidate.mjs finalize --archive "$RUNNER_TEMP/candidate/minimax-code-source.tar.gz" --revision "$REVISION" --reports "$RUNNER_TEMP/candidate/reports"
         env:

+ 3 - 3
CONTRIBUTING.md

@@ -37,15 +37,15 @@ pnpm install --frozen-lockfile
 pnpm verify
 ```
 
-`pnpm verify` runs the complete gate list in the same order as GitHub CI. Normal PR and main-branch checks use Node.js 24 on Linux, macOS and Windows. The Linux job runs this full profile; the other two platforms use `pnpm verify --profile platform`, which omits only the duplicate TypeScript compiler check. All three jobs still export source, build, and test their own platform artifacts. Gates that depend on platform behaviour are selected by platform rather than skipped silently; run `pnpm verify --list` or `pnpm verify --profile platform --list` to inspect either plan. Individual gates remain available as their own scripts, such as `pnpm typecheck` or `pnpm test:byok`, while you iterate.
+`pnpm verify` runs the complete gate list in the same order as GitHub CI. Normal PR and main-branch checks use Node.js 24 on Linux and macOS. Windows CI is temporarily paused while its checks are made reliable. The Linux job runs this full profile; the macOS job uses `pnpm verify --profile platform`, which omits only the duplicate TypeScript compiler check. Both jobs still export source, build, and test their own platform artifacts. Gates that depend on platform behaviour are selected by platform rather than skipped silently; run `pnpm verify --list` or `pnpm verify --profile platform --list` to inspect either plan. Individual gates remain available as their own scripts, such as `pnpm typecheck` or `pnpm test:byok`, while you iterate.
 
 CI writes per-gate timing and exit metadata to the Job Summary and a seven-day `verification-<os>-node-<version>-<attempt>` artifact. For a local report, set `MCODE_VERIFY_REPORT_DIR` to a directory outside the repository. Reports distinguish `PASS`, `FAIL`, intentional `SKIP`, and `NOT_RUN` after a failure. JSON is checkpointed before and after each gate; a cancelled run may leave `RUNNING`, which is not a pass. If installation fails before verification starts, no verification report is available. Reports do not collect command output, environment variables, or runtime data; read the corresponding gate's job log for failure details, including the existing bounded BYOK timeout diagnostics. CI jobs have a 15-minute verification limit and a 10-minute release-audit limit.
 
 Existing README files, `CONTRIBUTING.md`, `.github/PULL_REQUEST_TEMPLATE.md`, Markdown under `docs/`, and media directly under `docs/assets/` use the `docs` profile when they are the only changed paths. That profile checks the source inventory and generated paths, exports the committed source, and tests release tooling. History and source-snapshot secret scans still run; platform builds and distribution scans are skipped. Mixed changes, unknown paths, missing comparisons, and any `release/` inventory change get full CI. Documentation-only changes skip the platform matrix entirely. The `verification` aggregate check always runs and rejects failed, cancelled, or unexpectedly skipped jobs. Use it together with `source-history-artifact` as required checks when configuring branch protection; this repository's automation does not change administrative settings.
 
-`Node compatibility` runs weekly and on demand against macOS, Linux and Windows with Node 22.19.0, 24.2.0, 25 and 26. It does not run automatically on PRs. Dispatch it on the selected branch for changes to supported Node versions, native dependencies or compatibility-sensitive verification tooling, and before a source release. This covers the minimum versions of the two supported ranges and the additional supported majors. Deferring those versions from ordinary PR checks can delay regression discovery; a known failure in a supported version still needs resolution before release. Dependabot proposes weekly Actions and npm updates, grouping Actions and development-tool minor/patch updates. External Actions use reviewed full commit SHAs, while local actions and reusable workflows come from the same checked-out revision.
+`Node compatibility` runs weekly and on demand against macOS and Linux with Node 22.19.0, 24.2.0, 25 and 26. Windows is also temporarily excluded from this matrix. It does not run automatically on PRs. Dispatch it on the selected branch for changes to supported Node versions, native dependencies or compatibility-sensitive verification tooling, and before a source release. This covers the minimum versions of the two supported ranges and the additional supported majors. Deferring those versions from ordinary PR checks can delay regression discovery; a known failure in a supported version still needs resolution before release. Dependabot proposes weekly Actions and npm updates, grouping Actions and development-tool minor/patch updates. External Actions use reviewed full commit SHAs, while local actions and reusable workflows come from the same checked-out revision.
 
-Source candidates are requested independently through the `Source candidate` workflow; ordinary PRs and main pushes do not produce them. Its three-platform archive validation is described in [Releasing](docs/releasing.md). Product npm and installer publication remains a separate release process.
+Source candidates are requested independently through the `Source candidate` workflow; ordinary PRs and main pushes do not produce them. Its Linux/macOS archive validation is described in [Releasing](docs/releasing.md). Product npm and installer publication remains a separate release process.
 
 Source export reports separate archive creation, extraction, inventory validation, hashing, and cleanup timings in `export.json`. Windows uses native `tar` after complete archive preflight; other systems use the Node extractor. The preflight rejects traversal, links, duplicate entries and Git metadata before writing files. A machine without native `tar` falls back to Node. Set `MCODE_SOURCE_EXTRACTOR=node` or `native` when comparing extractors locally.
 

+ 56 - 0
README.md

@@ -45,6 +45,8 @@ curl -fsSL https://filecdn.minimax.chat/public/install.sh | bash
 irm https://filecdn.minimax.chat/public/install.ps1 | iex
 ```
 
+The scripts install into `~/.minimax-code` on macOS / Linux / WSL and `%USERPROFILE%\.minimax-code` on Windows. The launchers are `bin/mcode` and `bin/mcode-tools` on POSIX, or `mcode.cmd` / `mcode.ps1` and `mcode-tools.cmd` / `mcode-tools.ps1` on Windows. Set `MCODE_INSTALL_DIR` before installation to choose a different location. See [Uninstall](#uninstall) to remove the CLI.
+
 **npm** — if you already have **Node.js 22.19+ (22.x), 24.2+ (24.x), 25, or 26**:
 
 ```bash
@@ -96,6 +98,8 @@ mcode
 
 Supported API formats: `openai-completions`, `openai-responses`, and `anthropic-messages`. See the [model examples](docs/examples.md#2-choose-your-own-model) for environment variable setup, connection checks, and model overrides for a single run.
 
+Providers added this way are stored under `custom_provider` in the active profile's `config.yaml`; this is the supported path for third-party or self-hosted endpoints, while `minimax_api` stays reserved for the official MiniMax API. Relays that require `Authorization: Bearer` on an Anthropic-compatible endpoint can set custom headers in `config.yaml`; see [Third-party relays and custom auth headers](docs/examples.md#third-party-relays-and-custom-auth-headers).
+
 </details>
 
 ### 3. Run your first task
@@ -143,6 +147,58 @@ Inside the TUI, use `/sessions` to find previous sessions and `/help` to see all
 | Switch permission modes | `Alt+M` |
 | Close a panel or interrupt a running task | `Esc` |
 
+## Uninstall
+
+Close running MCode sessions, including editor integrations, before uninstalling. First locate the command with `command -v mcode` (macOS / Linux / WSL) or `Get-Command mcode -All` (PowerShell), then follow the matching installation method below. The current official install scripts do **not** provide an uninstall flag.
+
+### Installed with the script
+
+The commands below remove the default installation directory, including both launchers, downloaded releases, and any installer-managed Node.js runtime. If you used `MCODE_INSTALL_DIR`, substitute the actual installation directory. Inspect it first: earlier source builds used `~/.minimax-code` for user data, and a custom data directory can overlap the installation. Back up any configuration or sessions you want to keep before deleting it.
+
+**macOS / Linux / WSL**
+
+```bash
+rm -rf -- "$HOME/.minimax-code"
+```
+
+Remove the `# MiniMax Code CLI` comment and its following PATH line from the shell file the installer updated: `~/.zshrc` for zsh; the first existing file among `~/.bashrc`, `~/.bash_profile`, and `~/.profile` for bash (or a newly created `~/.bashrc`); `~/.config/fish/config.fish` for fish; or `~/.profile` for other shells. The line is `export PATH="/absolute/install/path/bin:$PATH"`, or `fish_add_path -g "/absolute/install/path/bin"` for fish. Remove only the MCode entry, preserving other PATH settings. The installer skips this edit when `MCODE_NO_MODIFY_PATH` is set or the path is already present.
+
+**Windows (PowerShell)**
+
+```powershell
+Remove-Item -LiteralPath "$env:USERPROFILE\.minimax-code" -Recurse -Force
+```
+
+Open **Edit environment variables for your account**, edit the user **Path**, and remove only the installation directory entry (by default `%USERPROFILE%\.minimax-code`, which may appear as an expanded absolute path). The Windows installer updates the user Path, not the PowerShell profile; `MCODE_NO_MODIFY_PATH` skips that persistent update.
+
+### Installed with npm or from source
+
+For a global npm installation, use the same npm installation/prefix you used to install MCode:
+
+```bash
+npm uninstall -g @minimax-ai/code
+```
+
+For a source build, save any work and remove only the checkout you created; see [Update or remove](docs/installation.md#update-or-remove).
+
+After uninstalling, reopen your terminal (fully restart the editor for integrated terminals) and run `command -v mcode` or `Get-Command mcode -All` again. No result means the command is no longer on PATH. If another copy appears, identify its installation method before removing it.
+
+### Optional: delete user data
+
+Removing the program leaves separately stored user data in place. To also delete local login state, provider configuration, caches, and sessions, first confirm the selected directory using [Accounts and data](docs/installation.md#accounts-and-data) and back up anything you need. Other MCode installations can share this directory. For the default `~/.minimax` directory only:
+
+```bash
+# macOS / Linux / WSL — permanently deletes the default user data
+rm -rf -- "$HOME/.minimax"
+```
+
+```powershell
+# Windows — permanently deletes the default user data
+Remove-Item -LiteralPath "$env:USERPROFILE\.minimax" -Recurse -Force
+```
+
+A profile uses `~/.minimax-<profile>`; `MINIMAX_DATA_DIR` or `MAVIS_DATA_DIR` can select a different location. Remove only the specific directories you intend to discard, without wildcard deletion. Remove any MCode-specific environment variable assignments you added to shell profiles or user environment settings if you no longer need them.
+
 ## What you can do
 
 | Task | Capabilities |

+ 56 - 0
README_ZH.md

@@ -45,6 +45,8 @@ curl -fsSL https://filecdn.minimax.chat/public/install.sh | bash
 irm https://filecdn.minimax.chat/public/install.ps1 | iex
 ```
 
+脚本在 macOS / Linux / WSL 上默认安装到 `~/.minimax-code`,在 Windows 上默认安装到 `%USERPROFILE%\.minimax-code`。POSIX 启动器为 `bin/mcode` 和 `bin/mcode-tools`;Windows 启动器为 `mcode.cmd` / `mcode.ps1` 和 `mcode-tools.cmd` / `mcode-tools.ps1`。安装前设置 `MCODE_INSTALL_DIR` 可更改安装位置。移除 CLI 的方法见[卸载](#卸载)。
+
 **npm**:适用于已安装 **Node.js 22.19+(22.x)、24.2+(24.x)、25 或 26** 的环境。
 
 ```bash
@@ -96,6 +98,8 @@ mcode
 
 支持 `openai-completions`、`openai-responses` 和 `anthropic-messages`。连接测试、单次模型切换及环境变量设置见 [模型示例](docs/examples.md#2-choose-your-own-model)。
 
+通过该命令添加的提供方保存在当前 profile `config.yaml` 的 `custom_provider` 下;第三方或自建端点一律走这条路径,`minimax_api` 保留给官方 MiniMax API。若中转端点只提供 Anthropic 兼容接口且要求 `Authorization: Bearer` 鉴权,可在 `config.yaml` 中为提供方配置自定义 headers;见[第三方中转与自定义鉴权头](docs/examples.md#third-party-relays-and-custom-auth-headers)。
+
 </details>
 
 ### 3. 完成第一个任务
@@ -143,6 +147,58 @@ mcode --session
 | 切换权限模式 | `Alt+M` |
 | 关闭面板或中断正在运行的任务 | `Esc` |
 
+## 卸载
+
+卸载前请关闭正在运行的 MCode 会话,包括编辑器中的集成。先通过 `command -v mcode`(macOS / Linux / WSL)或 `Get-Command mcode -All`(PowerShell)定位命令,再按对应的安装方式操作。当前官方安装脚本**不提供卸载参数**。
+
+### 通过脚本安装
+
+以下命令会删除默认安装目录,包括两个启动器、下载的版本,以及安装器管理的 Node.js 运行时。如果使用过 `MCODE_INSTALL_DIR`,请替换为实际安装目录。删除前请先检查:早期源码构建曾将用户数据保存在 `~/.minimax-code`,自定义数据目录也可能与安装目录重合。请先备份需要保留的配置和会话。
+
+**macOS / Linux / WSL**
+
+```bash
+rm -rf -- "$HOME/.minimax-code"
+```
+
+从安装器修改的 shell 配置文件中删除 `# MiniMax Code CLI` 注释及其下一行 PATH 配置:zsh 使用 `~/.zshrc`;bash 依次选择 `~/.bashrc`、`~/.bash_profile`、`~/.profile` 中第一个已存在的文件,均不存在时创建 `~/.bashrc`;fish 使用 `~/.config/fish/config.fish`;其他 shell 使用 `~/.profile`。对应配置为 `export PATH="/absolute/install/path/bin:$PATH"`,fish 则为 `fish_add_path -g "/absolute/install/path/bin"`。只移除 MCode 对应的条目,保留其他 PATH 设置。如果设置了 `MCODE_NO_MODIFY_PATH` 或路径已存在,安装器会跳过此修改。
+
+**Windows(PowerShell)**
+
+```powershell
+Remove-Item -LiteralPath "$env:USERPROFILE\.minimax-code" -Recurse -Force
+```
+
+打开“编辑账户的环境变量”,编辑用户 **Path**,仅删除安装目录对应的条目(默认为 `%USERPROFILE%\.minimax-code`,也可能显示为展开后的绝对路径)。Windows 安装器修改的是用户 Path,不是 PowerShell 配置文件;设置 `MCODE_NO_MODIFY_PATH` 会跳过此持久化修改。
+
+### 通过 npm 或源码安装
+
+全局 npm 安装请使用当初安装 MCode 时的同一套 npm 和安装前缀:
+
+```bash
+npm uninstall -g @minimax-ai/code
+```
+
+源码构建请先保存工作,再仅删除自己创建的源码目录,详见[更新或移除](docs/installation.md#update-or-remove)。
+
+卸载后重新打开终端(编辑器集成终端需要完全重启编辑器),再次运行 `command -v mcode` 或 `Get-Command mcode -All`。没有结果表示 PATH 中已找不到该命令。如果出现另一份安装,请先确认它的安装方式再移除。
+
+### 可选:删除用户数据
+
+移除程序会保留单独存储的用户数据。如果还要删除本地登录状态、提供方配置、缓存和会话,请先按[账号与数据](docs/installation.md#accounts-and-data)确认实际数据目录,并备份需要保留的内容。其他 MCode 安装可能共用该目录。以下命令仅适用于默认的 `~/.minimax`:
+
+```bash
+# macOS / Linux / WSL — 永久删除默认用户数据
+rm -rf -- "$HOME/.minimax"
+```
+
+```powershell
+# Windows — 永久删除默认用户数据
+Remove-Item -LiteralPath "$env:USERPROFILE\.minimax" -Recurse -Force
+```
+
+profile 使用 `~/.minimax-<profile>`;`MINIMAX_DATA_DIR` 或 `MAVIS_DATA_DIR` 可以指定其他位置。只删除确定不再需要的具体目录,不要使用通配符批量删除。如果不再需要自行添加的 MCode 环境变量,也请从 shell 配置或用户环境变量设置中移除对应赋值。
+
 ## 可以做什么
 
 | 场景 | 使用方式 |

+ 97 - 1
docs/examples.md

@@ -66,10 +66,65 @@ pnpm mcode provider list --json
 
 `--api-key-env` reads the current environment variable value and stores that value in the active profile's `config.yaml`; it does not save an environment-variable reference. The file still contains plaintext credentials. On POSIX systems, config writes and temporary copies use `0600`. When loading existing files, MCode removes group/other access while preserving the owner's permissions; already-private files such as `0400` or `0600` do not require a permission change. Loading fails if an unsafe main config cannot be restricted. Older migration backups are also checked, but inspection or repair failures produce a warning identifying the directory or backup that needs manual attention rather than preventing the main config from loading. Windows file modes do not provide equivalent ACL protection; restrict access to the profile directory using Windows permissions.
 
+### Third-party relays and custom auth headers
+
+Providers created by `mcode provider add` are stored under `custom_provider` in the active profile's `config.yaml`. That tree is the supported home for any endpoint other than the official MiniMax API; `minimax_api` is reserved for the official endpoint and keeps its fixed authentication scheme.
+
+Authentication follows the API format: `openai-completions` and `openai-responses` send `Authorization: Bearer <key>`, and `anthropic-messages` sends the key as `x-api-key`. A relay that expects Bearer authentication on an OpenAI-compatible endpoint therefore needs no extra configuration. If a relay only exposes an Anthropic-compatible endpoint (`/v1/messages`) and requires Bearer authentication, add explicit headers to the provider entry in `config.yaml`:
+
+```yaml
+custom_provider:
+  my-relay:
+    options:
+      apiKey: sk-relay-key
+      baseURL: https://relay.example.com
+      headers:
+        Authorization: Bearer sk-relay-key
+    models:
+      MiniMax-M2: {}
+```
+
+`api` can be omitted and defaults to `anthropic-messages`. Configured headers are sent on both connection tests and conversation requests, and they are part of the connection-test fingerprint, so editing them retires a cached test verdict. The default `x-api-key` header is still sent alongside; the relay must tolerate rather than reject it. Header values are stored in plaintext like `apiKey` and are reported by name only in provider views. After editing the file, verify with `mcode provider list` and `mcode provider test <provider-id>`.
+
 [Live acceptance](verification.md) separately verified MiniMax Token Plan and one configured BYOK provider. This is not a guarantee for every compatible service.
 
 ## 3. Search and image input
 
+For a custom BYOK model, declare image input support explicitly when adding the
+provider. Use this only if the selected provider endpoint and model accept images:
+
+```bash
+pnpm mcode provider add --name my-vision-provider --base-url https://example.com/v1 \
+  --api-format openai-completions --model my-vision-model \
+  --api-key-env MCODE_PROVIDER_API_KEY --support-image --use
+```
+
+`--support-image` applies to every repeated `--model` and saves
+`capabilities.support_image: true`. Without it, adding an unknown custom model
+does not infer image support from its name. `--use` and `provider test` check
+connectivity with a text request; they do not verify vision support.
+
+For an existing provider, close MCode and add the capability to the matching model
+in the active profile's `config.yaml` (normally `~/.minimax/config.yaml`; see
+[Accounts and data](installation.md#accounts-and-data) for profiles and overrides).
+Merge this fragment into the existing provider and keep its other settings:
+
+```yaml
+custom_provider:
+  my-vision-provider:
+    models:
+      my-vision-model:
+        capabilities:
+          support_image: true
+```
+
+The existing `modalities: { input: [text, image], output: [text] }` model setting
+also enables image input. Either declaration is sufficient. To make a model
+text-only again, remove `image` from `modalities.input` and remove or set
+`capabilities.support_image` to `false`. Generic `attachment: true` alone does not
+declare image input support. Restart MCode after editing configuration and select
+the configured model with `/provider`, or use `exec --model` for a single run.
+
 After signing in to MiniMax, try a task that explicitly requires search:
 
 > Use web_search to find the official Node.js test runner documentation. Summarize how to run tests and include the source URL. If the tool is unavailable, say so.
@@ -85,4 +140,45 @@ pnpm mcode exec "Describe this UI screenshot's layout and suggest three improvem
 
 The image is sent as input to the selected model service. Use content suitable for sending and a model that supports images. This is an executable usage example, not a live-service acceptance result from this review. Search, image understanding, and media generation are separate capabilities; mcode-tools generation also requires the relevant account permissions and credits.
 
-Use `/plugins` to manage extensions. See [capability coverage](tui-capabilities.md) for custom MCP, managed connectors, and media tools.
+See [capability coverage](tui-capabilities.md) for custom MCP, managed connectors, and media tools.
+
+## 4. Manage plugins
+
+Open `/plugins` inside the TUI, or run `mcode plugin` from a shell to open that panel. For a source build, use `pnpm mcode plugin` from the source root instead; the commands below use the installed `mcode` executable.
+
+The panel combines the **official** catalog and **local** plugin directories. Use `Tab` / `Shift+Tab` to switch between All Plugins, Installed, Official, and Local; type to search and use the arrow keys to select a row.
+
+| Action | Key | Scope |
+| --- | --- | --- |
+| Install an available plugin | `Enter` | Official catalog; requires MiniMax login |
+| Enable or disable an installed plugin | `Space` | Official and local |
+| Remove an installed plugin | `Delete` or `Ctrl+D` | Official and local; clear the search first with `Esc`, then reselect the plugin |
+| Refresh the catalogs | `Ctrl+R` | Official and local |
+
+With a nonempty search, `Delete` / `Ctrl+D` edit the search instead of removing a plugin. `Esc` clears the search, or closes the panel when the search is already empty. Removing a local plugin deletes its installed directory; keep a separate source copy if you need to restore it.
+
+The same operations are available from the shell:
+
+```bash
+mcode plugin --help
+mcode plugin marketplace list
+mcode plugin list --available --marketplace official
+mcode plugin add <name>@official
+mcode plugin disable <name>@official
+mcode plugin enable <name>@official
+mcode plugin remove <name>@official
+mcode plugin marketplace upgrade
+```
+
+Replace `<name>` with a plugin name returned by `list`. Use `@official` or `@local` to disambiguate names shared by both sources; `--marketplace official` / `--marketplace local` are equivalent source selectors. The list and mutation commands support `--json`. `marketplace upgrade` refreshes source snapshots; it does not register a new marketplace.
+
+For a local plugin, run `mcode plugin marketplace list` to find the active profile's local directory. Place a supported plugin package in a direct child directory there, with its manifest at the package's expected location, then refresh `/plugins`. Copy the individual plugin package, not an entire marketplace repository. Discovered local packages already count as installed:
+
+```bash
+mcode plugin list --available --marketplace local
+mcode plugin disable <name>@local
+mcode plugin enable <name>@local
+mcode plugin remove <name>@local
+```
+
+`mcode plugin add <name>@local` is not a local import command and is unsupported. Neither `plugin add` nor `/plugins` currently accepts a GitHub URL, local path, or arbitrary third-party marketplace registration. Compatible package readers and a GitHub importer exist in the runtime, but the CLI/TUI do not expose that importer. Managing arbitrary marketplaces from the panel remains a separate feature request; the current source selectors are only `official` and `local`.

+ 48 - 2
docs/installation.md

@@ -8,7 +8,7 @@ For npm, use the command in the README: it explicitly selects the public registr
 
 This guide builds the 0.4.12 source preview. Workspace/local build manifests remain `private: true` to prevent accidental publishing. A source checkout may contain additional reviewed distribution changes; matching version strings alone do not establish byte-for-byte or build-provenance equivalence with the official npm tarball. Use the committed source revision and release receipt to identify a source build.
 
-For a source build, you need Git, Node.js 22.19+ (22.x), 24.2+ (24.x), 25, or 26, and pnpm 9.12.0. Regular CI uses Node.js 24 across Linux, macOS, and Windows. The weekly and manual compatibility matrix covers Node.js 22.19.0, 24.2.0, 25, and 26 on all three platforms. Initial installation and build require access to public npm.
+For a source build, you need Git, Node.js 22.19+ (22.x), 24.2+ (24.x), 25, or 26, and pnpm 9.12.0. Regular CI uses Node.js 24 across Linux and macOS. The weekly and manual compatibility matrix covers Node.js 22.19.0, 24.2.0, 25, and 26 on both platforms. Windows CI and source-candidate validation are temporarily paused while their checks are made reliable. Initial installation and build require access to public npm.
 
 Node 24.0 and 24.1 are unsupported: their bundled libuv can return inconsistent Windows file identity metadata, causing safe configuration reads to fail. [Node 24.2.0](https://nodejs.org/en/blog/release/v24.2.0) includes libuv 1.51.0 with the [upstream fix](https://github.com/libuv/libuv/commit/82cdfb75f). Use a current patch release of a supported Node line.
 
@@ -60,8 +60,54 @@ To locate data safely:
 
 For tests, explicitly set `MINIMAX_DATA_DIR` to a temporary directory to keep normal sessions separate. Use `$env:MINIMAX_DATA_DIR = 'C:\path\to\test-profile'` in PowerShell or `export MINIMAX_DATA_DIR=/path/to/test-profile` in a POSIX shell.
 
+## macOS terminal shortcuts: Ghostty Option+M
+
+In the composer, `Alt+M` (`Option+M` on macOS) cycles permission modes through Ask, Auto, and Full access. Its binding ID is `composer.cycle-permission`. `Shift+Tab` toggles **Plan mode**, a separate setting. You can also use `/permission` to choose a permission mode and `/permission status` to inspect it without an Option shortcut.
+
+If `Option+M` inserts `µ` instead, the terminal is sending text rather than the expected Alt shortcut. MCode preserves literal `µ` as text; it cannot safely infer a permission change from that character. The terminal must forward the modifier, or you can choose another binding.
+
+### Configure Ghostty's Option key
+
+Ghostty's [`macos-option-as-alt`](https://ghostty.org/docs/config/reference#macos-option-as-alt) default is **keyboard-layout dependent** when unset, not always `false`. The current reference lists U.S. Standard and U.S. International as defaulting to `true`; other layouts default to `false`. Check the active macOS input source and the configuration loaded by your installed Ghostty version.
+
+Set this in your Ghostty configuration to send both Option keys as Alt:
+
+```ini
+macos-option-as-alt = true
+```
+
+Use `left` or `right` instead of `true` to reserve only that Option key for shortcuts and retain Unicode composition on the other side. Use the configured side when testing `Option+M`.
+
+Follow Ghostty's [configuration locations and precedence](https://ghostty.org/docs/config#file-location): macOS-specific files load after XDG files, and later settings can override earlier ones. Inspect the loaded setting from the same Ghostty installation, without `--default`:
+
+```bash
+ghostty +show-config | awk '/^macos-option-as-alt[[:space:]]*=/'
+```
+
+If `ghostty` is not on `PATH`, use the executable inside your installed app bundle, typically `/Applications/Ghostty.app/Contents/MacOS/ghostty`. An empty or omitted value is not proof of `false`; unset behavior depends on the layout. After editing, reload Ghostty's configuration from its menu (default `Cmd+Shift+,`) and open a new terminal. This is separate from MCode's `/reload` command.
+
+### Keep Option for text and customize MCode instead
+
+While idle, open `/hotkeys`, select `composer.cycle-permission`, press `Enter`, press `Ctrl+X`, then press `Enter` to save. `Ctrl+X` is unused by the current default MCode bindings; check any custom terminal or multiplexer bindings too. Do not choose `Ctrl+M`: terminals commonly encode it identically to `Enter`.
+
+Alternatively, merge this entry into `<data-dir>/tui/keybindings.json`, preserving any existing entries:
+
+```json
+{
+  "composer.cycle-permission": "ctrl+x"
+}
+```
+
+For the default profile this is `~/.minimax/tui/keybindings.json`; [profiles and data-directory overrides](#accounts-and-data) change the path. Create the `tui` directory if needed. After editing the file, run `/reload` while idle with no pending interaction or queued message, or restart MCode. This replaces `Alt+M`; use `["alt+m", "ctrl+x"]` as the value to retain both bindings. `/hotkeys` shows the effective binding.
+
+### Verify the result
+
+With an idle composer and no open picker or permission prompt, note `/permission status`, press the configured shortcut, and check the status again. The mode should advance without inserting text. Restore your intended permission mode through `/permission` afterward. Confirm that `Shift+Tab` still toggles Plan mode and that pasting `µ` still inserts text.
+
+If it still fails, record `mcode --version`, Ghostty's version, active keyboard layout, which Option key you pressed, the setting above, the effective `/hotkeys` entry, and whether tmux or SSH is involved. Compare with a direct Ghostty session. MCode supports both legacy ESC-prefixed Alt input and extended keyboard reports; a shell's raw-key display alone does not establish what Ghostty sends after the TUI negotiates its keyboard protocol.
+
 ## Update or remove
 
 Save your changes, fetch a reviewed revision with Git, then repeat the frozen install and build. A source installation does not automatically become an official npm installation.
 
-To uninstall, remove the source directory you created. User data is separate and remains in place. Delete that directory only when you no longer need its account configuration or sessions.
+To uninstall a source build, save any work and remove the source directory you created. Separately stored user data remains in place. See [Uninstall](../README.md#uninstall) for official installer and npm removal, shell PATH cleanup, and optional user-data deletion.

+ 23 - 0
docs/maintainers.md

@@ -11,6 +11,29 @@
 
 These are repository maintenance responsibilities, not an assertion that an account owns the product's copyright. Every PR that requires approval needs a reviewer other than the author, and security reports need a working private response path. Review maintainer additions and policy changes in a PR; do not silently grant repository access.
 
+## Issue triage
+
+Published source covers the standalone CLI (interactive TUI, headless and ACP). The issue tracker also collects Desktop app feedback; accepting those reports does not expand the published source scope.
+
+Everyone may report bugs, request features, ask questions, and flag documentation problems. Code and documentation PRs are accepted only from repository collaborators. Opening an issue or having a proposal accepted does not grant collaborator access or permission to submit a PR. Do not use `good first issue` or `help wanted` while external PRs are closed.
+
+Use these labels independently:
+
+| Category | Labels and meaning |
+| --- | --- |
+| Type | `bug`: reported malfunction; `enhancement`: requested improvement; `documentation`: missing or incorrect docs; `question`: usage or project-policy question |
+| Product | `desktop`: Desktop app; `cli`: standalone mcode, including TUI, headless, ACP and its source builds/tooling |
+| Triage | `needs-triage`: awaiting maintainer assessment; `needs-info`: a maintainer has asked the reporter for specific missing information |
+
+1. Start with [needs-triage](https://github.com/MiniMax-AI/minimax-code/issues?q=is%3Aissue+is%3Aopen+label%3Aneeds-triage) and [unlabelled issues](https://github.com/MiniMax-AI/minimax-code/issues?q=is%3Aissue+is%3Aopen+no%3Alabel). Templates add a type and `needs-triage`; reports created through other routes may need both added manually. A type label describes the report and does not confirm a defect or commit to implementation.
+2. Confirm one primary type and apply `desktop` or `cli` from the report. Product dropdowns stay in the body; maintainers apply product labels manually. Use both only when the report establishes that both are affected. Leave product labels unset for unclear reports or repository-policy questions. The existing `tui` label may supplement `cli` for interactive-terminal-specific issues; it does not cover headless or ACP.
+3. If information is missing, ask for the specific version, reproduction, or expected behavior, replace `needs-triage` with `needs-info`, and retain any known type/product labels. When the reporter replies, remove `needs-info` and reassess. Do not automatically close issues for inactivity.
+4. Once assessed, remove `needs-triage` and record the next step in a comment. Assign a collaborator when someone takes responsibility; classification alone does not promise a fix or release date. For duplicates, link the original issue before closing with `duplicate`. For declined requests, explain the reason before closing with `wontfix`.
+
+Route security reports through [Security](../SECURITY.md). Do not ask for secrets or unredacted logs in public issues. Label setup is a separate repository operation: ensure the labels above exist before merging template changes, since forms cannot create missing labels. The Feishu workflow sends notifications only; it does not perform triage.
+
+This small label set draws on the type and information-request handling in [VS Code's triage guide](https://github.com/microsoft/vscode/wiki/Issues-Triaging) and the `needs-triage`/`needs-info` states used by [Ruff](https://github.com/astral-sh/ruff/labels). Contribution eligibility follows this repository's policy.
+
 ## Review and merge
 
 1. Repository collaborators open an issue for substantial scope or submit a focused feature-branch PR. Other users may open issues to discuss ideas and proposals. Security details follow the private reporting process.

+ 4 - 2
docs/releasing.md

@@ -15,9 +15,11 @@ Before npm or installer distribution, separately validate the published package
 
 ## Automated source candidates
 
-The `Source candidate` workflow exports the selected commit without Git history, verifies its receipt, and scans both repository history and the extracted source. Linux, macOS, and Windows runners authenticate the same archive, install from public npm into fresh stores, and run the archive verification profile.
+The `Source candidate` workflow exports the selected commit without Git history, verifies its receipt, and scans both repository history and the extracted source. Linux and macOS runners authenticate the same archive, install from public npm into fresh stores, and run the archive verification profile.
 
-After all platform jobs pass, the workflow creates a `source-candidate-<full-SHA>` artifact containing:
+Windows validation is temporarily paused across source verification, Node compatibility, and source candidates. Candidate reports cover only Linux and macOS; a successful candidate does not establish Windows acceptance. Restore the Windows workflow matrices and the required report set in `scripts/source-candidate.mjs` together when Windows checks are reliable again.
+
+After both platform jobs pass, the workflow creates a `source-candidate-<full-SHA>` artifact containing:
 
 - `minimax-code-source.tar.gz`
 - The archive receipt and SHA-256 file

+ 35 - 1
docs/tui-capabilities.md

@@ -10,7 +10,7 @@ The evidence column summarizes the historical TUI 0.3.11 restoration record from
 | BYOK / custom models | Retained; headless model overrides no longer inherit the default Token Plan login requirement | Local protocol server drives runtime, resume, and file tools; live BYOK session passed; managed models still reject unauthenticated requests |
 | mcode-tools | Public package's unchanged 0.0.4 artifact, launcher, and short-lived token leases restored | Archive SHA-512, CLI SHA-256, real CLI startup, lease and host integration tests; production shared-broker authentication passed |
 | Search and Matrix image / audio / video tools | Matrix MCP and tool assembly restored; search is independent of mcode-tools | MCP configuration and auth-isolation tests; actual search passed; generation requests not run |
-| Official, local, and GitHub plugins | Official sources, marketplace reads, and installation control restored; local sources retained | Plugin application, source-page, and offline local CLI tests; actual official catalog read passed |
+| Official and local plugins; runtime GitHub importer | `/plugins` and `mcode plugin` manage official installations and discovered local packages; arbitrary marketplace registration and GitHub URL import are not exposed in the CLI/TUI. See [plugin management](examples.md#4-manage-plugins) | Plugin application, source-page, and offline local CLI tests; actual official catalog read passed |
 | Managed connectors | Cloud client, permissions, and invocation adapters restored | Connector runtime and cloud transport tests; actual tool discovery passed; business writes not run |
 | Updates | Update entry points, install-source detection, and signature verification restored; public packages use public npm | Update application and service tests; no real installation / upgrade on the development machine |
 | Feedback and diagnostic uploads | Reviewed feedback text and minimized diagnostic summaries | Synthetic fixtures exercise session collection and capture/decode the final ZIP upload; no live uploads or real content |
@@ -21,6 +21,21 @@ The evidence column summarizes the historical TUI 0.3.11 restoration record from
 | Files, shell, subagents, sessions, headless, ACP | Actual runtime retained | BYOK, file reads, session resume, ACP, sandbox, and status protocol tests |
 | Built-in skills, MCP, plugin tools | Original TUI assets and activation conditions retained | Asset build, plugin, and MCP tests; no claim that every skill has passed a real task |
 
+## ACP Skill commands
+
+ACP clients receive enabled Skills alongside built-in slash commands when a session
+is created, loaded, resumed, or forked. Discovery uses the session's Agent and
+workspace, including installed plugin Skills. Command names come from the runtime
+Skill roster (for example, `/review` or `/plugin:review`), not the installation
+package name. Select a command and append instructions to invoke it through the
+normal Agent turn. `/skills [filter]` lists the session's available Skills.
+
+Built-in command names take priority over conflicting Skill names. Disabled,
+duplicate, and invalid command names are omitted. If Skill discovery fails,
+built-in commands remain available. Reopen the session after installing or enabling
+Skills to refresh its command menu. Protocol tests cover command discovery and
+prompt forwarding; this does not establish live Zed or model acceptance.
+
 ## Desktop boundary
 
 Background workspace indexing is removed from this distribution. Runtime startup and conversation turns do not collect workspace snapshots, create workspace ZIP archives, or upload/retry them for cloud indexing. The semantic workspace search tool and its enablement policy are also removed; a saved indexing preference cannot reactivate them. Existing indexing records are left inert. User-directed file reading, search, and Git operations remain available.
@@ -46,3 +61,22 @@ Every collected diagnostic artifact, including prioritized session artifacts, is
 There is no raw-attachment upload option in this flow. Prompts, conversation text, tool arguments/results, command output, workspace excerpts, raw errors and unknown fields are excluded even if they contain no recognizable credential pattern. This intentionally reduces diagnostic detail: reproducing an exact response or inspecting an original stack is not possible from these uploads. Future raw attachments would require a separate, explicit review and consent surface describing their contents and scope.
 
 The regression tests use temporary synthetic files and intercepted HTTP only. They decrypt the final automatic-report request as a receiver would, and unzip the actual feedback PUT body after real session-report collection. They do not validate production ingestion of the new schemas, retention policies, live services, other telemetry paths or other platforms.
+
+
+## Interactive startup model
+
+Use `mcode -m <provider-id>/<model-id>` or
+`mcode "Fix the failing tests" --model <provider-id>/<model-id>` to select the
+model for the startup Session. References use the same syntax as `exec --model`,
+including `custom_provider:<id>/<model-id>`, model IDs containing `/`, and the
+optional `#variant` suffix. The provider must already be configured and the model
+must be available to Runtime; invalid references fail before the initial prompt runs.
+
+Without a resume option, this creates a new Session even when no prompt is given.
+With `--session <id>` or `--continue`, it updates the opened Session's model before
+submitting the prompt. The selection is saved with that Session, so later turns
+and resumes keep it. It does not change the global default, and `/new` returns to
+the configured default. Omitting `--model` preserves existing startup behavior.
+The untargeted `--session` picker cannot be combined with `--model`; provide an ID
+or use `--continue` instead. If opening or continuing a Session fails, the override
+and initial prompt are not applied.

+ 3 - 1
packages/agent-modules/permission/src/tools/fs-permission.ts

@@ -687,8 +687,10 @@ function isProtectedRuntimeRead(
     // at credentials must not turn its destination into a trusted asset root.
     const readableAsset =
       within(canonicalPath, path.join(canonicalRoot, 'skills')) ||
+      within(canonicalPath, path.join(canonicalRoot, '.builtin-skills')) ||
       (context.agentName != null &&
-        within(canonicalPath, path.join(canonicalRoot, 'agents', context.agentName, 'workspace'))) ||
+        (within(canonicalPath, path.join(canonicalRoot, 'agents', context.agentName, 'workspace')) ||
+          within(canonicalPath, path.join(canonicalRoot, 'agents', context.agentName, 'skills')))) ||
       isInternalWhitelistedPath(canonicalPath, {
         ...context,
         dataDir: canonicalRoot,

+ 8 - 17
packages/local-runtime-v2/src/application/session/process-local-application-contract.ts

@@ -26,8 +26,13 @@ import type {
   CodexOAuthStartResult,
   CodexOAuthLoginOptions,
   CodexOAuthStatus,
+  UserModelInputView,
 } from "../../service/model-system/index.js";
 
+export type ProcessLocalModelInput = Omit<UserModelInputView, "modalities"> & {
+  modalities?: { input?: readonly string[]; output?: readonly string[] };
+};
+
 export interface ProcessLocalMiniAppLaunch {
   readonly miniApp: MiniAppSurfaceSummary;
   /** Main-process-only launch coordinates. Never forward this object to a renderer. */
@@ -262,7 +267,7 @@ export interface LocalRuntimeApplication {
       baseUrl: string;
       apiKey: string;
       apiFormat?: string;
-      models?: readonly { modelId: string; displayName?: string }[];
+      models?: readonly ProcessLocalModelInput[];
       saveAndUse?: boolean;
     }): Promise<unknown>;
     discoverCandidate(input: {
@@ -278,21 +283,7 @@ export interface LocalRuntimeApplication {
         baseUrl: string;
         apiKey?: string;
         apiFormat?: string;
-        models?: readonly {
-          modelId: string;
-          displayName?: string;
-          configurationSource?: string;
-          enabled?: boolean;
-          attachment?: boolean;
-          reasoning?: boolean;
-          toolCall?: boolean;
-          temperature?: boolean;
-          modalities?: {
-            input?: readonly string[];
-            output?: readonly string[];
-          };
-          limit?: { context?: number; output?: number };
-        }[];
+        models?: readonly ProcessLocalModelInput[];
       };
       modelId?: string;
       saveAndUse?: boolean;
@@ -309,7 +300,7 @@ export interface LocalRuntimeApplication {
       apiKey?: string;
       apiFormat?: string;
       enabled?: boolean;
-      models?: readonly { modelId: string; displayName?: string }[];
+      models?: readonly ProcessLocalModelInput[];
       saveAndUse?: boolean;
     }): Promise<unknown>;
     delete(input: { providerId: string }): Promise<void>;

+ 5 - 13
packages/local-runtime-v2/src/application/session/process-local-application.ts

@@ -10,7 +10,10 @@ import type {
 } from '../../service/model-system/index.js';
 import { watchGlobalEvents, watchProcessEvents } from '../events.js';
 import type { ModelProviderApplication } from './model-provider-application.js';
-import type { LocalRuntimeApplication } from './process-local-application-contract.js';
+import type {
+  LocalRuntimeApplication,
+  ProcessLocalModelInput,
+} from './process-local-application-contract.js';
 import type { SessionReportCapability } from '../../service/session-system/index.js';
 
 export interface ProcessLocalApplicationOptions {
@@ -201,18 +204,7 @@ function toProviderRecord(provider: ModelProviderView): Record<string, unknown>
 }
 
 function toUserModelInputs(
-  models: readonly {
-    modelId: string;
-    displayName?: string;
-    configurationSource?: string;
-    enabled?: boolean;
-    attachment?: boolean;
-    reasoning?: boolean;
-    toolCall?: boolean;
-    temperature?: boolean;
-    modalities?: { input?: readonly string[]; output?: readonly string[] };
-    limit?: { context?: number; output?: number };
-  }[],
+  models: readonly ProcessLocalModelInput[],
 ): UserModelInputView[] {
   return models.map(({ modalities, ...model }) => ({
     ...model,

+ 23 - 0
packages/local-runtime-v2/src/service/model-system/catalog/list-models.test.ts

@@ -274,6 +274,29 @@ describe('model catalog entry helpers', () => {
     });
   });
 
+  it('exposes Kimi K3 low/high/max effort options in the model roster', () => {
+    const entry = buildModelEntry({
+      providerId: 'custom_provider:moonshotai',
+      modelId: 'kimi-k3',
+      model: {
+        name: 'Kimi K3',
+        reasoning: true,
+        thinking: { effortOptions: ['low', 'high', 'max'] },
+      },
+      selected: false,
+      providerSource: 'custom_provider',
+      providerKind: 'custom',
+      providerName: 'Moonshot AI',
+    });
+
+    expect(entry).toMatchObject({
+      modelId: 'kimi-k3',
+      displayName: 'Kimi K3',
+      effortOptions: ['low', 'high', 'max'],
+    });
+    expect(entry.defaultEffort).toBeUndefined();
+  });
+
   it('exposes context option hints only for managed models', () => {
     const model = {
       limit: { context: 512_000 },

+ 113 - 0
packages/local-runtime-v2/src/service/model-system/catalog/provider-presets/provider-presets.service.test.ts

@@ -7,6 +7,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
 import { providerCompletionUrl, providerModelsUrls } from '../../connectivity/provider-request.js';
 import { ProviderPresetCatalog } from './provider-presets.service.js';
 import { readProviderPresetSnapshotCandidates } from './provider-presets.repository.js';
+import { modelsFromInputs } from '../../management/service-input.js';
+import { buildModelEntry } from '../list-models.js';
 
 vi.mock('./provider-presets.repository.js', async (importOriginal) => {
   const actual = await importOriginal<typeof import('./provider-presets.repository.js')>();
@@ -371,6 +373,117 @@ describe('models.dev Provider Presets', () => {
       },
     ]);
   });
+
+  it('parses declared reasoning effort options for Kimi K3 on both Moonshot providers', async () => {
+    const k3 = {
+      name: 'Kimi K3',
+      tool_call: true,
+      attachment: true,
+      reasoning: true,
+      reasoning_options: [
+        { type: 'toggle' },
+        { type: 'effort', values: ['low', 'high', 'max'] },
+      ],
+      temperature: false,
+      modalities: { input: ['text', 'image', 'video'], output: ['text'] },
+      limit: { context: 1_048_576, output: 131_072 },
+    };
+    const presets = await parsePresetsForTest({
+      moonshotai: {
+        name: 'Moonshot AI',
+        npm: '@ai-sdk/openai-compatible',
+        api: 'https://api.moonshot.ai/v1',
+        models: {
+          'kimi-k3': k3,
+          'kimi-k2.6': {
+            name: 'Kimi K2.6',
+            tool_call: true,
+            reasoning: true,
+            reasoning_options: [{ type: 'toggle' }],
+          },
+          'kimi-k2.7-code': {
+            name: 'Kimi K2.7 Code',
+            tool_call: true,
+            reasoning: true,
+            reasoning_options: [],
+          },
+        },
+      },
+      'moonshotai-cn': {
+        name: 'Moonshot AI China',
+        npm: '@ai-sdk/openai-compatible',
+        api: 'https://api.moonshot.cn/v1',
+        models: { 'kimi-k3': k3 },
+      },
+    });
+
+    for (const providerId of ['moonshotai', 'moonshotai-cn'] as const) {
+      const preset = presets.find((candidate) => candidate.providerId === providerId);
+      expect(preset?.models.find((model) => model.modelId === 'kimi-k3')).toMatchObject({
+        reasoning: true,
+        effortOptions: ['low', 'high', 'max'],
+      });
+      if (!preset) throw new Error(`Missing preset ${providerId}`);
+      const savedModel = modelsFromInputs(preset.models)['kimi-k3'];
+      expect(savedModel?.thinking).toEqual({ effortOptions: ['low', 'high', 'max'] });
+      expect(buildModelEntry({
+        providerId: `custom_provider:${providerId}`,
+        modelId: 'kimi-k3',
+        model: savedModel,
+        selected: false,
+        providerSource: 'custom_provider',
+        providerKind: 'custom',
+        providerName: preset.name,
+      }).effortOptions).toEqual(['low', 'high', 'max']);
+    }
+    const moonshot = presets.find((candidate) => candidate.providerId === 'moonshotai');
+    // A toggle-only or bare reasoning model can think, but declares no
+    // selectable effort levels, so it must not gain effortOptions.
+    for (const modelId of ['kimi-k2.6', 'kimi-k2.7-code'] as const) {
+      const model = moonshot?.models.find((candidate) => candidate.modelId === modelId);
+      expect(model).toMatchObject({ reasoning: true });
+      expect(model).not.toHaveProperty('effortOptions');
+    }
+  });
+
+  it('normalizes effort metadata without inventing or dropping declared levels', async () => {
+    const [preset] = await parsePresetsForTest({
+      compatible: {
+        name: 'Compatible API',
+        npm: '@ai-sdk/openai-compatible',
+        api: 'https://api.example.test/v1',
+        models: {
+          custom: {
+            name: 'Custom',
+            tool_call: true,
+            reasoning: true,
+            reasoning_options: [null, {}, { type: 'effort', values: 'high' },
+              { type: 'effort', values: [' light ', 'light', '', ' ', 7, null, 'max'] }],
+          },
+          'empty-effort': {
+            name: 'Empty effort',
+            tool_call: true,
+            reasoning: true,
+            reasoning_options: [{ type: 'effort', values: [] }],
+          },
+          'budget-only': {
+            name: 'Budget only',
+            tool_call: true,
+            reasoning: true,
+            reasoning_options: [{ type: 'budget_tokens', min: 128, max: 32_768 }],
+          },
+        },
+      },
+    });
+
+    const model = (modelId: string) =>
+      preset?.models.find((candidate) => candidate.modelId === modelId);
+    // Unknown levels are preserved verbatim; blanks, duplicates and
+    // non-strings never reach the roster.
+    expect(model('custom')).toMatchObject({ effortOptions: ['light', 'max'] });
+    expect(model('empty-effort')).not.toHaveProperty('effortOptions');
+    expect(model('budget-only')).not.toHaveProperty('effortOptions');
+  });
 });
 
 describe('models.dev Provider Preset snapshots', () => {

+ 28 - 0
packages/local-runtime-v2/src/service/model-system/catalog/provider-presets/provider-presets.service.ts

@@ -169,6 +169,7 @@ function parseModel(modelId: string, value: unknown): UserModelInputView | undef
     modelId,
     displayName: stringValue(value.name) ?? modelId,
     ...parseModelCapabilities(value),
+    ...parseModelEffortOptions(value),
     ...parseModelModalities(value),
     ...parseModelLimit(value),
   };
@@ -183,6 +184,33 @@ function parseModelCapabilities(value: Record<string, unknown>): Partial<UserMod
   };
 }
 
+/**
+ * Reads the catalog's declared reasoning-effort levels. models.dev describes
+ * reasoning controls as `reasoning_options` entries; only an explicit
+ * `{ type: 'effort', values: [...] }` entry means the model accepts effort
+ * selection. A bare `reasoning: true` or a `toggle` entry only means the model
+ * can think, so neither one produces `effortOptions` here. Declared strings
+ * are preserved as-is (trimmed, de-duplicated, in catalog order) so levels the
+ * CLI does not know about still reach validation and the wire unchanged.
+ */
+function parseModelEffortOptions(value: Record<string, unknown>): Partial<UserModelInputView> {
+  if (!Array.isArray(value.reasoning_options)) return {};
+  for (const option of value.reasoning_options) {
+    if (!isRecord(option) || option.type !== 'effort' || !Array.isArray(option.values)) continue;
+    const effortOptions: string[] = [];
+    const seen = new Set<string>();
+    for (const candidate of option.values) {
+      if (typeof candidate !== 'string') continue;
+      const effort = candidate.trim();
+      if (!effort || seen.has(effort)) continue;
+      seen.add(effort);
+      effortOptions.push(effort);
+    }
+    if (effortOptions.length > 0) return { effortOptions };
+  }
+  return {};
+}
+
 function parseModelModalities(value: Record<string, unknown>): Partial<UserModelInputView> {
   const modalities = isRecord(value.modalities) ? value.modalities : undefined;
   const input = stringArray(modalities?.input);

+ 1 - 0
packages/local-runtime-v2/src/service/model-system/contracts.ts

@@ -414,6 +414,7 @@ export interface UserModelInputView {
   reasoning?: boolean;
   toolCall?: boolean;
   temperature?: boolean;
+  capabilities?: LocalModelConfig['capabilities'];
   modalities?: { input?: string[]; output?: string[] };
   limit?: { context?: number; output?: number };
   thinkingConfig?: { mode?: string; defaultValue?: string };

+ 42 - 0
packages/local-runtime-v2/src/service/model-system/management/service-input.test.ts

@@ -13,6 +13,31 @@ import {
 } from './service-input.js';
 
 describe('model provider input normalization', () => {
+  it('preserves declared capabilities on create and merges updates without losing limits', () => {
+    const created = modelsFromInputs([
+      {
+        modelId: 'vision-model',
+        capabilities: { support_image: true, max_image_bytes_inline: 1024 },
+      },
+    ]);
+    expect(created['vision-model']?.capabilities).toEqual({
+      support_image: true,
+      max_image_bytes_inline: 1024,
+    });
+    const patch = [{ modelId: 'vision-model', capabilities: { support_image: false } }];
+    for (const updated of [modelsFromInputs(patch, created), mergeModelsFromInputs(created, patch)]) {
+      expect(updated['vision-model']?.capabilities).toEqual({
+        support_image: false,
+        max_image_bytes_inline: 1024,
+      });
+      const renamed = mergeModelsFromInputs(updated, [
+        { modelId: 'vision-model', displayName: 'Renamed' },
+      ]);
+      expect(renamed['vision-model']?.capabilities).toEqual(updated['vision-model']?.capabilities);
+    }
+    expect(created['vision-model']?.capabilities?.support_image).toBe(true);
+  });
+
   it('normalizes API keys and formats', () => {
     expect(() => assertValidRawApiKey(undefined as unknown as string)).toThrow(
       LocalModelProviderError,
@@ -96,6 +121,23 @@ describe('model provider input normalization', () => {
     });
   });
 
+  it('persists declared Kimi K3 effort options as thinking metadata', () => {
+    expect(
+      modelsFromInputs([
+        {
+          modelId: 'kimi-k3',
+          displayName: 'Kimi K3',
+          reasoning: true,
+          effortOptions: ['low', 'high', 'max'],
+        },
+      ])['kimi-k3'],
+    ).toEqual({
+      name: 'Kimi K3',
+      reasoning: true,
+      thinking: { effortOptions: ['low', 'high', 'max'] },
+    });
+  });
+
   it('applies implicit thinking only to eligible new models', () => {
     expect(modelsFromInputs([{ modelId: 'implicit' }], undefined, true).implicit).toMatchObject({
       reasoning: true,

+ 3 - 0
packages/local-runtime-v2/src/service/model-system/management/service-input.ts

@@ -120,6 +120,9 @@ function modelFromInput(
   const nextModel: LocalModelConfig = {
     ...existing,
     ...modelMetadataFields(model),
+    ...(model.capabilities
+      ? { capabilities: { ...existing?.capabilities, ...model.capabilities } }
+      : {}),
     ...modelReasoningFields(model, effortOptions, defaultThinkingConfig),
     ...modelThinkingConfigFields(model, defaultThinkingConfig),
     ...modelEffortFields(effortOptions),

+ 89 - 3
packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.test.ts

@@ -1384,19 +1384,22 @@ describe('LocalModelResolver custom provider compat overrides', () => {
   });
 
   // The incident was a wire-level symptom: pi chooses the system prompt role from the
-  // resolved compat, so these two cases pin the request pi would actually send.
+  // resolved compat, so these cases pin the request pi would actually send.
   const reasoningModelConfig: LocalModelConfig = {
     reasoning: true,
     thinking: { effortOptions: ['low', 'light', 'max'] },
   };
 
-  const systemPromptRoleFor = async (compat: LocalModelConfig['compat']) => {
+  const systemPromptRoleFor = async (
+    compat: LocalModelConfig['compat'],
+    baseURL = 'https://gateway.example/v1',
+  ) => {
     const resolver = new LocalModelResolver({
       byokConfigGetter: () => ({
         custom_provider: {
           gateway: {
             api: 'openai-completions',
-            options: { apiKey: 'gateway-key', baseURL: 'https://gateway.example/v1' },
+            options: { apiKey: 'gateway-key', baseURL },
             models: { 'kimi-k2-thinking': { ...reasoningModelConfig, compat } },
           },
         },
@@ -1443,4 +1446,87 @@ describe('LocalModelResolver custom provider compat overrides', () => {
   it('still sends `developer` when the gateway declares nothing, reproducing the incident', async () => {
     expect(await systemPromptRoleFor(undefined)).toBe('developer');
   });
+
+  it('keeps the system role for a thinking model on the Mistral API', async () => {
+    expect(await systemPromptRoleFor(undefined, 'https://api.mistral.ai/v1')).toBe('system');
+  });
+
+  it.each([
+    'https://api.siliconflow.cn/v1',
+    'https://api.siliconflow.com/v1',
+    'https://dashscope.aliyuncs.com/compatible-mode/v1',
+    'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
+    'https://dashscope-us.aliyuncs.com/compatible-mode/v1',
+    'https://cn-hongkong.dashscope.aliyuncs.com/compatible-mode/v1',
+    'https://coding.dashscope.aliyuncs.com/v1',
+    'https://coding-intl.dashscope.aliyuncs.com/v1',
+    'https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',
+    'https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1',
+    'https://trial.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',
+    'https://example-workspace.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',
+    'https://example-workspace.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1',
+    'https://example-workspace.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1',
+    'https://example-workspace.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1',
+    'https://example-workspace.eu-central-1.maas.aliyuncs.com/compatible-mode/v1',
+    'https://example-workspace.us-east-1.maas.aliyuncs.com/compatible-mode/v1',
+    'https://api.kimi.com/coding/v1',
+    'https://api.kimi.ai/coding/v1',
+  ])('keeps the system role for a thinking model at %s', async (baseURL) => {
+    expect(await systemPromptRoleFor(undefined, baseURL)).toBe('system');
+  });
+
+  it.each([
+    ['https://api.openai.com/v1', 'developer'],
+    ['https://api.deepseek.com/v1', 'system'],
+    ['https://api.mistral.ai.example/v1', 'developer'],
+    ['https://gateway.example/api.mistral.ai/v1', 'developer'],
+    ['https://api.siliconflow.cn.example/v1', 'developer'],
+    ['https://gateway.example/api.siliconflow.cn/v1', 'developer'],
+    ['https://api.siliconflow.com.example/v1', 'developer'],
+    ['https://gateway.example/api.siliconflow.com/v1', 'developer'],
+    ['https://api.moonshot.cn/v1', 'system'],
+    ['https://api.moonshot.ai/v1', 'system'],
+    ['https://dashscope.aliyuncs.com.example/v1', 'developer'],
+    ['https://gateway.example/dashscope.aliyuncs.com/v1', 'developer'],
+    ['https://coding.dashscope.aliyuncs.com.example/v1', 'developer'],
+    ['https://token-plan.cn-beijing.maas.aliyuncs.com.example/v1', 'developer'],
+    ['https://gateway.example/token-plan.cn-beijing.maas.aliyuncs.com/v1', 'developer'],
+    ['https://example-workspace.unknown-region.maas.aliyuncs.com/v1', 'developer'],
+    ['https://example-workspace.cn-beijing.aliyuncs.com/v1', 'developer'],
+    ['https://api.kimi.com.example/v1', 'developer'],
+    ['https://gateway.example/api.kimi.com/coding/v1', 'developer'],
+  ])('preserves the system prompt role for %s', async (baseURL, role) => {
+    expect(await systemPromptRoleFor(undefined, baseURL)).toBe(role);
+  });
+
+  it('honors an explicit developer-role override on the Mistral API', async () => {
+    expect(
+      await systemPromptRoleFor({ supportsDeveloperRole: true }, 'https://api.mistral.ai/v1'),
+    ).toBe('developer');
+  });
+
+  it.each([
+    'https://api.siliconflow.cn/v1',
+    'https://api.siliconflow.com/v1',
+    'https://dashscope.aliyuncs.com/compatible-mode/v1',
+    'https://coding.dashscope.aliyuncs.com/v1',
+    'https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',
+    'https://example-workspace.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1',
+  ])('honors an explicit developer-role override on %s', async (baseURL) => {
+    expect(
+      await systemPromptRoleFor(
+        { supportsDeveloperRole: true },
+        baseURL,
+      ),
+    ).toBe('developer');
+  });
+
+  it('honors an explicit developer-role override on a Kimi Coding endpoint', async () => {
+    expect(
+      await systemPromptRoleFor(
+        { supportsDeveloperRole: true },
+        'https://api.kimi.com/coding/v1',
+      ),
+    ).toBe('developer');
+  });
 });

+ 39 - 0
packages/local-runtime-v2/src/service/model-system/resolution/model-ref.test.ts

@@ -403,6 +403,32 @@ describe('BYOK Think Effort selection', () => {
     });
   });
 
+  it.each(['low', 'high', 'max'] as const)(
+    'carries the Kimi K3 effort %s from catalog metadata to the OpenAI-compatible request patch',
+    (effort) => {
+      // What the models.dev preset chain persists for moonshotai/kimi-k3:
+      // reasoning_options { type: 'effort', values: ['low', 'high', 'max'] }
+      // becomes thinking.effortOptions on the stored model config.
+      const config: LocalModelConfig = {
+        name: 'Kimi K3',
+        reasoning: true,
+        thinking: { effortOptions: ['low', 'high', 'max'] },
+      };
+      const ref = modelRefForModel('custom_provider:moonshotai', 'kimi-k3', config, {
+        thinking: { effort },
+      });
+
+      const selectedEffort = readSelectedThinkingEffort(ref.capabilities);
+      expect(selectedEffort).toBe(effort);
+      expect(
+        resolveByokThinkingProtocol('openai-completions', selectedEffort, ref.model_id),
+      ).toMatchObject({
+        effort,
+        requestPatch: { reasoning_effort: effort },
+      });
+    },
+  );
+
   it.each([`${DEFAULT_THINKING_MODEL_IDS[0]}[1m]`, ...DEFAULT_THINKING_MODEL_IDS.slice(1)])(
     'omits thinking for default-thinking model %s while preserving effort',
     (modelId) => {
@@ -600,6 +626,19 @@ describe('resolveThinkingLevel', () => {
 });
 
 describe('model capability helpers', () => {
+  it('requires explicit image input metadata instead of generic attachment support', () => {
+    expect(capabilitiesFromModelConfig({ attachment: true }).support_image).toBe(false);
+    expect(
+      capabilitiesFromModelConfig({ modalities: { input: ['text'], output: ['image'] } }).support_image,
+    ).toBe(false);
+    expect(
+      capabilitiesFromModelConfig({ modalities: { input: ['text', 'image'] } }).support_image,
+    ).toBe(true);
+    expect(
+      capabilitiesFromModelConfig({ capabilities: { support_image: false } }).support_image,
+    ).toBe(false);
+  });
+
   it('uses explicit capability flags and forced thinking modes', () => {
     expect(
       capabilitiesFromModelConfig({

+ 11 - 0
packages/local-runtime-v2/src/service/turn-system/agent-host/runner/local-agent-turn-runner.ts

@@ -1,3 +1,4 @@
+import { logger } from '../../../../infra/logging/index.js';
 import {
   PiTurnRunner,
   type LLMModelConfig,
@@ -633,6 +634,16 @@ async function settleNetworkStop(
   safetyWriter: LocalOutputSafetyEventWriter,
 ): Promise<void> {
   if (safetyWriter.terminalFailed) return;
+  logger.warn(
+    {
+      sessionId: input.sessionId,
+      turnId: input.turnId,
+      reviewOutcome: safetyWriter.reviewStopVariant === 'auth' ? 'auth_error' : 'unavailable',
+      outputSuppressed: true,
+      terminalStatus: 'completed',
+    },
+    '[content-safety] output review stopped turn',
+  );
   state.networkStopped = true;
   state.retractionVariant = safetyWriter.reviewStopVariant;
   state.approvedPartial = safetyWriter.getApprovedPartial();

+ 3 - 1
packages/local-runtime-v2/test/unit/agent/storage/agent.repository.test.ts

@@ -169,6 +169,8 @@ async function seed(repository: DrizzleAgentRepository): Promise<void> {
 }
 
 describe("Frozen Session deletion continuity", () => {
+  // This real-database create/delete/recreate sequence exceeded 5s on Windows CI.
+  // Keep the larger I/O budget local to this integration case.
   it("reads the persisted definition and renders after deleting and recreating its Agent", async () => {
     const { repository, database, dataDir } = await createRepository();
     const agentService = createTestAgentService({
@@ -275,7 +277,7 @@ describe("Frozen Session deletion continuity", () => {
     const afterRecreate = await read();
     expect(afterRecreate).toEqual(afterDelete);
     expect(afterRecreate.corePrompt).not.toContain("NEW_AGENT_PROMPT");
-  });
+  }, process.platform === "win32" ? 15_000 : 5_000);
 });
 
 describe("Local Agent reference resolver integration", () => {

+ 39 - 20
packages/local-runtime/src/content-safety/api-v2.ts

@@ -16,6 +16,7 @@ import {
   managedBackendRoutingHeaders,
   type LocalRuntimeRoutingContext,
 } from '../runtime/routing-headers.js';
+import { createSafetyFailureReporter } from './diagnostics.js';
 import { resolveSafetyApiBase } from './api-base.js';
 
 /** biz-gateway uses V2 numeric scenes with its desktop HTTP envelope. */
@@ -50,26 +51,44 @@ export async function callLocalSafetyCheckV2(input: {
   const buildEnv = (input.buildEnv ?? getRuntimeBuildEnv)();
   const region = (input.region ?? getRuntimeRegion)();
   const token = input.authContext?.accessToken?.trim() || process.env.MAVIS_ACCESS_TOKEN?.trim();
-  const result = await postSafetyCheckV2({
-    url: `${resolveSafetyApiBase(region, buildEnv, input.testBaseURL)}/mavis/api/v2/content?require_auth=true`,
-    headers: {
-      'User-Agent': 'MiniMaxAgent',
-      ...(token ? { Authorization: `Bearer ${token}` } : {}),
-      ...managedBackendRoutingHeaders(input.routingContext, input.buildEnv ? buildEnv : undefined),
-    },
-    body: {
-      scene: input.request.scene,
-      ...(input.request.content_text !== undefined
-        ? { content_text: input.request.content_text }
-        : {}),
-      ...(input.request.sessionId !== undefined ? { sessionId: input.request.sessionId } : {}),
-      ...(input.request.image_url !== undefined ? { image_url: input.request.image_url } : {}),
-      ...(input.request.files !== undefined ? { files: input.request.files } : {}),
-    },
-    fetchImpl: input.fetchImpl,
-    signal: input.signal,
-  });
-  return parseLocalSafetyCheckV2Result(result);
+  const url = `${resolveSafetyApiBase(region, buildEnv, input.testBaseURL)}/mavis/api/v2/content?require_auth=true`;
+  const reportFailure = createSafetyFailureReporter(url, 'v2', input.request.scene);
+  try {
+    const result = await postSafetyCheckV2({
+      url,
+      headers: {
+        'User-Agent': 'MiniMaxAgent',
+        ...(token ? { Authorization: `Bearer ${token}` } : {}),
+        ...managedBackendRoutingHeaders(
+          input.routingContext,
+          input.buildEnv ? buildEnv : undefined,
+        ),
+      },
+      body: {
+        scene: input.request.scene,
+        ...(input.request.content_text !== undefined
+          ? { content_text: input.request.content_text }
+          : {}),
+        ...(input.request.sessionId !== undefined ? { sessionId: input.request.sessionId } : {}),
+        ...(input.request.image_url !== undefined ? { image_url: input.request.image_url } : {}),
+        ...(input.request.files !== undefined ? { files: input.request.files } : {}),
+      },
+      fetchImpl: input.fetchImpl,
+      signal: input.signal,
+    });
+    return parseLocalSafetyCheckV2Result(result);
+  } catch (error) {
+    reportFailure(
+      error instanceof SafetyCheckV2Error
+        ? {
+            failureKind: error.kind,
+            statusCode: error.statusCode,
+            transportKind: error.transportKind,
+          }
+        : { failureKind: 'internal' },
+    );
+    throw error;
+  }
 }
 
 function parseLocalSafetyCheckV2Result(body: Record<string, unknown>): LocalSafetyCheckV2Result {

+ 34 - 41
packages/local-runtime/src/content-safety/api.ts

@@ -1,3 +1,8 @@
+import {
+  classifySafetyTransportError,
+  isSafetyCheckV2Record,
+} from "@mavis/shared/safety-check-v2";
+import { createSafetyFailureReporter } from "./diagnostics.js";
 import {
   getRuntimeBuildEnv,
   getRuntimeRegion,
@@ -8,7 +13,6 @@ import {
 import { callTurnSafetyApi } from "./turn-api.js";
 import { resolveSafetyApiBase } from "./api-base.js";
 
-import { logger } from "../common/logger.js";
 import type { LocalRuntimeAuthContext } from "../runtime/model-resolver.js";
 import {
   managedBackendRoutingHeaders,
@@ -126,12 +130,7 @@ export async function callSafetyApi(input: {
   const accessToken =
     input.authContext?.accessToken?.trim() ||
     process.env.MAVIS_ACCESS_TOKEN?.trim();
-  // TODO(shared-oauth): Remove this local-only diagnostic after the content-safety
-  // resource server accepts mcode-public Bearer tokens in the joint test environment.
-  // Never add the token, request body/content, or response body to these fields.
-  const logLocalUpstream =
-    resolvedBuildEnv === "dev" || resolvedBuildEnv === "test";
-  const startedAt = Date.now();
+  const reportFailure = createSafetyFailureReporter(url, "v1", input.scene);
   let response: Response;
   try {
     response = await input.fetchImpl(url, {
@@ -162,20 +161,10 @@ export async function callSafetyApi(input: {
       signal: AbortSignal.timeout(CONTENT_REVIEW_TIMEOUT_MS),
     });
   } catch (error) {
-    if (logLocalUpstream) {
-      logger.info(
-        {
-          url,
-          method: "POST",
-          status: null,
-          scene: input.scene,
-          hasBearer: Boolean(accessToken),
-          durationMs: Date.now() - startedAt,
-          errorType: error instanceof Error ? error.name : typeof error,
-        },
-        "[content-safety] upstream transport failure",
-      );
-    }
+    reportFailure({
+      failureKind: "transport",
+      transportKind: classifySafetyTransportError(error),
+    });
     // fetch threw (offline / DNS / connection refused / TLS) or the 10s timeout
     // fired: we never reached a verdict. No gateway confirmation → fail closed.
     return {
@@ -185,26 +174,21 @@ export async function callSafetyApi(input: {
     };
   }
 
-  if (logLocalUpstream) {
-    logger.info(
-      {
-        url,
-        method: "POST",
-        status: response.status,
-        scene: input.scene,
-        hasBearer: Boolean(accessToken),
-        durationMs: Date.now() - startedAt,
-        upstreamTraceId:
-          response.headers.get("trace-id") ??
-          response.headers.get("x-trace-id") ??
-          response.headers.get("x-request-id") ??
-          null,
-      },
-      "[content-safety] upstream response",
-    );
+  let text: string;
+  try {
+    text = await response.text();
+  } catch (error) {
+    reportFailure({
+      failureKind: "transport",
+      transportKind: classifySafetyTransportError(error),
+      statusCode: response.status,
+    });
+    return {
+      pass: false,
+      reason: "Service response could not be read",
+      errorKind: "local_error",
+    };
   }
-
-  const text = await response.text();
   if (!response.ok) {
     // Non-2xx from the gateway, split by class so an auth failure can never be a
     // bypass:
@@ -215,6 +199,10 @@ export async function callSafetyApi(input: {
     //          acceptable, so there is NO valid verdict on our side → `local_error`
     //          (fail closed). Treating 401/403 as `api_error` would let an
     //          unauthenticated user bypass every content gate.
+    reportFailure({
+      failureKind: response.status === 401 || response.status === 403 ? "auth" : "http",
+      statusCode: response.status,
+    });
     const error = readErrorText(text);
     return {
       pass: false,
@@ -240,6 +228,7 @@ export async function callSafetyApi(input: {
   try {
     data = JSON.parse(text) as typeof data;
   } catch {
+    reportFailure({ failureKind: "response", statusCode: response.status });
     // 2xx but the body is not JSON — we cannot read a verdict. Treat as no
     // gateway confirmation → fail closed on the input path.
     return {
@@ -249,8 +238,9 @@ export async function callSafetyApi(input: {
     };
   }
 
-  const pass = data.pass ?? data.safe;
+  const pass = isSafetyCheckV2Record(data) ? data.pass ?? data.safe : undefined;
   if (typeof pass !== "boolean") {
+    reportFailure({ failureKind: "response", statusCode: response.status });
     // 2xx JSON but no boolean pass/safe field — again no usable verdict → fail
     // closed on the input path.
     return {
@@ -262,6 +252,9 @@ export async function callSafetyApi(input: {
   const activeRegion = region();
   const upstreamCode =
     typeof data.errorCode === "number" ? data.errorCode : undefined;
+  if (!pass && upstreamCode === UPSTREAM_CODE.SERVICE_UNAVAILABLE) {
+    reportFailure({ failureKind: "upstream", statusCode: upstreamCode });
+  }
   return {
     pass,
     reason:

+ 27 - 0
packages/local-runtime/src/content-safety/diagnostics.ts

@@ -0,0 +1,27 @@
+import { randomUUID } from 'node:crypto';
+import type { SafetyTransportKind } from '@mavis/shared/safety-check-v2';
+import { logger } from '../common/logger.js';
+
+/** One bounded record per failed check, in every build. Never log raw upstream data. */
+export function createSafetyFailureReporter(url: string, apiVersion: 'v1' | 'v2', scene: number) {
+  const startedAt = Date.now();
+  const reviewId = randomUUID();
+  const endpointHost = new URL(url).hostname;
+  return (failure: {
+    failureKind: 'transport' | 'auth' | 'http' | 'response' | 'upstream' | 'internal';
+    transportKind?: SafetyTransportKind;
+    statusCode?: number;
+  }): void => {
+    logger.warn(
+      {
+        reviewId,
+        endpointHost,
+        apiVersion,
+        scene,
+        durationMs: Date.now() - startedAt,
+        ...failure,
+      },
+      '[content-safety] review failed',
+    );
+  };
+}

+ 15 - 4
packages/local-runtime/src/permissions/facade.ts

@@ -608,7 +608,11 @@ export class LocalPermissionFacade {
       rules,
       workingDirectory,
       allowedWorkingPaths: [...pluginContext.directories],
-      sandboxAllowPaths: this.resolveSandboxAllowPaths(params.toolName, workingDirectory),
+      sandboxAllowPaths: this.resolveSandboxAllowPaths(
+        params.toolName,
+        workingDirectory,
+        params.agentName,
+      ),
       trustedExactWritePaths: params.trustedExactWritePaths,
       dataDir: this.deps.configGetter().dataDir,
       homeDir: homedir(),
@@ -978,7 +982,11 @@ export class LocalPermissionFacade {
   // -------------------------------------------------------------------------
 
   /** Built-in skill assets may be read without granting access to private runtime state. */
-  private resolveSandboxAllowPaths(toolName: string, workingDirectory: string): string[] {
+  private resolveSandboxAllowPaths(
+    toolName: string,
+    workingDirectory: string,
+    agentName?: string,
+  ): string[] {
     // Read-only tool set parity with `READ_ONLY_TOOLS`
     // (`packages/local-runtime/src/permission/tools/fs-permission.ts`).
     // We don't import it directly to avoid coupling facade construction
@@ -989,8 +997,11 @@ export class LocalPermissionFacade {
 
     const candidates: string[] = [];
     const dataDir = this.deps.configGetter().dataDir;
-    if (dataDir) candidates.push(path.resolve(dataDir, 'skills'));
-    candidates.push(path.resolve(homedir(), '.minimax', 'skills'));
+    for (const root of [dataDir, path.join(homedir(), '.minimax')]) {
+      if (!root) continue;
+      candidates.push(path.resolve(root, 'skills'), path.resolve(root, '.builtin-skills'));
+      if (agentName) candidates.push(path.resolve(root, 'agents', agentName, 'skills'));
+    }
     // De-duplicate (dataDir may already equal <dataDir> on a default install).
     const unique = Array.from(new Set(candidates));
     if (!workingDirectory) return unique;

+ 11 - 0
packages/local-runtime/src/runtime/host.ts

@@ -1,3 +1,4 @@
+import { logger } from "../common/logger.js";
 import type { LocalEventWriter } from "../events/sink.js";
 import { PiTurnRunner } from "@mavis/agent-core/pi-turn-runner";
 import { RuntimeEventStatus, RuntimeEventType } from "@mavis/protocol";
@@ -437,6 +438,16 @@ export class LocalRuntimeHost {
         // writer, so keep it authoritative and do not append a synthetic
         // COMPLETED/network-notice outcome.
         if (safetyWriter.terminalFailed) break;
+        logger.warn(
+          {
+            sessionId: input.sessionId,
+            turnId: input.turnId,
+            reviewOutcome: "unavailable",
+            outputSuppressed: true,
+            terminalStatus: "completed",
+          },
+          "[content-safety] output review stopped turn",
+        );
         networkStopped = true;
         retractionVariant = "network";
         // Capture the approved prefix so the orchestration can rewrite pi history

+ 3 - 1
packages/local-runtime/test/unit/child-bash-lifecycle.test.ts

@@ -36,6 +36,8 @@ function nodeCommand(script: string): string {
 
 const directories: string[] = [];
 const shutdowns: Array<() => Promise<void>> = [];
+// Windows CI has exceeded the 10s teardown budget for these SQLite/output fixtures.
+// Keep the execution deadlines below separate from this bounded teardown budget.
 afterEach(async () => {
   // A terminal task can still be finalizing output or scheduling delivery.
   // Drain that work before closing SQLite, otherwise it can reopen the file
@@ -45,7 +47,7 @@ afterEach(async () => {
     closeLocalRuntimeDb(path);
     await rm(path, { recursive: true, force: true });
   }
-});
+}, process.platform === 'win32' ? 30_000 : 10_000);
 async function fixture() {
   const dataDir = await mkdtemp(join(tmpdir(), 'child-bash-lifecycle-'));
   directories.push(dataDir);

+ 62 - 38
packages/local-runtime/test/unit/content-safety-api-fail-policy.test.ts

@@ -276,46 +276,70 @@ describe('callSafetyApi fail-policy classification', () => {
     expect(headers.get('Token')).toBeNull();
   });
 
-  it('logs a sanitized upstream response in local test environments', async () => {
-    const log = vi.spyOn(logger, 'info').mockImplementation(() => {});
-    const fetchImpl = vi.fn(async () =>
-      new Response(JSON.stringify({ code: 401, message: 'auth failed' }), {
-        status: 401,
-        headers: {
-          'Content-Type': 'application/json',
-          'Trace-Id': 'trace-content-safety-test',
-        },
-      }),
-    ) as unknown as typeof fetch;
-
-    await callSafetyApi({
-      content: 'must-not-appear-in-log',
-      scene: SAFETY_SCENE.UserInput,
-      authContext: { accessToken: 'must-not-appear-token' },
-      fetchImpl,
-      region,
-      buildEnv,
-    });
-
-    expect(log).toHaveBeenCalledWith(
-      expect.objectContaining({
-        url: 'https://matrix-test.example.invalid/mavis/api/v1/content',
-        method: 'POST',
-        status: 401,
+  it.each([
+    ['auth', () => jsonResponse({ error: 'private-response' }, 401), 401],
+    ['http', () => jsonResponse({ error: 'private-response' }, 503), 503],
+    ['response', () => new Response('private-response'), 200],
+    ['response', () => jsonResponse(null), 200],
+    ['response', () => jsonResponse({ secret: 'private-response' }), 200],
+    [
+      'transport',
+      () => {
+        throw new TypeError('private-error https://secret.invalid/?token=private-token', {
+          cause: { code: 'ENOTFOUND' },
+        });
+      },
+      undefined,
+    ],
+    [
+      'transport',
+      () =>
+        new Response(
+          new ReadableStream({
+            start(controller) {
+              controller.error(new DOMException('private-error', 'TimeoutError'));
+            },
+          }),
+        ),
+      200,
+    ],
+  ] as const)(
+    'logs redacted %s failures in production',
+    async (failureKind, response, statusCode) => {
+      const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
+      const result = await callSafetyApi({
+        content: 'private-content',
         scene: SAFETY_SCENE.UserInput,
-        hasBearer: true,
-        durationMs: expect.any(Number),
-        upstreamTraceId: 'trace-content-safety-test',
-      }),
-      '[content-safety] upstream response',
-    );
-    const serialized = JSON.stringify(log.mock.calls);
-    expect(serialized).not.toContain('must-not-appear-token');
-    expect(serialized).not.toContain('must-not-appear-in-log');
-  });
+        authContext: { accessToken: 'private-token' },
+        attachments: [{ fileUrl: 'https://secret.invalid/private-file', fileName: 'private-name' }],
+        fetchImpl: async () => response(),
+        region,
+        buildEnv: () => 'prod',
+      });
+      expect(result.pass).toBe(false);
+      expect(reviewBlocks(result)).toBe(failureKind !== 'http');
+      expect(log).toHaveBeenCalledOnce();
+      expect(log).toHaveBeenCalledWith(
+        expect.objectContaining({
+          reviewId: expect.any(String),
+          endpointHost: 'agent.minimax.cn',
+          apiVersion: 'v1',
+          scene: SAFETY_SCENE.UserInput,
+          durationMs: expect.any(Number),
+          failureKind,
+          ...(statusCode === undefined ? { transportKind: 'dns' } : { statusCode }),
+        }),
+        '[content-safety] review failed',
+      );
+      const serialized = JSON.stringify(log.mock.calls);
+      expect(serialized).not.toContain('private-');
+      expect(serialized).not.toContain('secret.invalid');
+      expect(serialized).not.toContain('https://');
+    },
+  );
 
-  it('does not emit the temporary upstream diagnostic in production', async () => {
-    const log = vi.spyOn(logger, 'info').mockImplementation(() => {});
+  it('does not log successful reviews in production', async () => {
+    const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
 
     await callSafetyApi({
       content: 'hello',

+ 83 - 1
packages/local-runtime/test/unit/content-safety-api-v2.test.ts

@@ -1,3 +1,4 @@
+import { logger } from '../../src/common/logger.js';
 import { afterEach, describe, expect, it, vi } from 'vitest';
 import { SAFETY_CHECK_V2_SCENE } from '@mavis/shared/safety-check-v2';
 import { callLocalSafetyCheckV2 } from '../../src/content-safety/api-v2.js';
@@ -14,7 +15,10 @@ const defaults = {
 };
 const fetchResponse = (body: unknown) =>
   vi.fn<typeof fetch>().mockImplementation(async () => Response.json(body));
-afterEach(() => vi.unstubAllEnvs());
+afterEach(() => {
+  vi.unstubAllEnvs();
+  vi.restoreAllMocks();
+});
 
 describe('local biz-gateway SafetyCheckV2 client', () => {
   it('uses the V2 endpoint and scene with the current Bearer/routing headers', async () => {
@@ -248,3 +252,81 @@ describe('local biz-gateway SafetyCheckV2 client', () => {
     });
   });
 });
+
+describe('V2 production failure diagnostics', () => {
+  it.each([
+    [{ cause: { code: 'ENOTFOUND' } }, 'dns'],
+    [{ cause: { code: 'ECONNREFUSED' } }, 'connect'],
+    [{ cause: { code: 'ERR_TLS_CERT_ALTNAME_INVALID' } }, 'tls'],
+    [{ name: 'TimeoutError' }, 'timeout'],
+    [{ cause: { code: 'UND_ERR_BODY_TIMEOUT' } }, 'timeout'],
+    [{ name: 'AbortError' }, 'aborted'],
+    [{ cause: { code: 'private-code' } }, 'unknown'],
+  ] as const)('retains only the transport category %j', async (details, transportKind) => {
+    const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
+    const error = Object.assign(
+      new Error('private-error https://secret.invalid/?token=private-token'),
+      details,
+    );
+    await expect(
+      callLocalSafetyCheckV2({
+        ...defaults,
+        buildEnv: () => 'prod',
+        authContext: { accessToken: 'private-token' },
+        request: { scene: 100, content_text: 'private-content', sessionId: 'private-session' },
+        fetchImpl: async () => {
+          throw error;
+        },
+      }),
+    ).rejects.toMatchObject({ kind: 'transport', transportKind });
+    expect(log).toHaveBeenCalledOnce();
+    expect(log).toHaveBeenCalledWith(
+      expect.objectContaining({
+        reviewId: expect.any(String),
+        endpointHost: 'agent.minimax.cn',
+        apiVersion: 'v2',
+        scene: 100,
+        durationMs: expect.any(Number),
+        failureKind: 'transport',
+        transportKind,
+      }),
+      '[content-safety] review failed',
+    );
+    expect(JSON.stringify(log.mock.calls)).not.toContain('private-');
+    expect(JSON.stringify(log.mock.calls)).not.toContain('secret.invalid');
+  });
+
+  it.each([
+    ['auth', () => new Response('private-body', { status: 401 })],
+    ['http', () => new Response('private-body', { status: 503 })],
+    ['response', () => new Response('private-body')],
+    ['response', () => Response.json({ unexpected: 'private-body' })],
+    ['upstream', () => Response.json({ errorCode: 50200, error: 'private-body' })],
+    [
+      'transport',
+      () =>
+        new Response(
+          new ReadableStream({
+            start(controller) {
+              controller.error(new DOMException('private-body', 'TimeoutError'));
+            },
+          }),
+        ),
+    ],
+  ] as const)('logs failed %s reviews without response data', async (kind, response) => {
+    const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
+    await expect(
+      callLocalSafetyCheckV2({
+        ...defaults,
+        buildEnv: () => 'prod',
+        fetchImpl: async () => response(),
+      }),
+    ).rejects.toMatchObject({ kind });
+    expect(log).toHaveBeenCalledOnce();
+    expect(log).toHaveBeenCalledWith(
+      expect.objectContaining({ failureKind: kind }),
+      '[content-safety] review failed',
+    );
+    expect(JSON.stringify(log.mock.calls)).not.toContain('private-body');
+  });
+});

+ 109 - 0
packages/local-runtime/test/unit/local-permission-facade.test.ts

@@ -1709,6 +1709,111 @@ describe('LocalPermissionFacade', () => {
   });
 
   describe('sandbox self-paths (dataDir auto-allow)', () => {
+    describe.each(['default', 'auto', 'bypassPermissions'] as const)(
+      'skill resources in %s mode',
+      (permissionMode) => {
+        it.each(['read', 'grep', 'glob', 'list'])(
+          'allows %s for global, builtin and active-agent skill resources',
+          async (toolName) => {
+            const classify = vi.fn(async (): Promise<CloudClassifyVerdict> => ({
+              kind: 'allow',
+              reasonLocalized: 'ok',
+            }));
+            const { facade, dataDir } = freshFacade({
+              permissionMode,
+              cloudGateway: { classify },
+              dataDirParent: homedir(),
+            });
+            try {
+              for (const root of [
+                path.join(dataDir, 'skills'),
+                path.join(dataDir, '.builtin-skills'),
+                path.join(dataDir, 'agents', 'fixture-agent', 'skills'),
+              ]) {
+                const resourceDir = path.join(root, 'fixture-skill', 'references');
+                mkdirSync(resourceDir, { recursive: true });
+                const resource = path.join(resourceDir, 'guide.txt');
+                writeFileSync(resource, 'synthetic skill reference');
+                const result = await facade.checkPermission({
+                  toolName,
+                  agentName: 'fixture-agent',
+                  input: { path: toolName === 'read' ? resource : resourceDir, pattern: '*' },
+                });
+                expect(result.behavior).toBe('allow');
+              }
+              expect(classify).not.toHaveBeenCalled();
+            } finally {
+              cleanup(dataDir);
+            }
+          },
+        );
+      },
+    );
+
+    it.each(['default', 'auto'] as const)(
+      '%s mode keeps other agents and runtime state outside skill read access',
+      async (permissionMode) => {
+        const classify = vi.fn(async (): Promise<CloudClassifyVerdict> => ({
+          kind: 'allow',
+          reasonLocalized: 'ok',
+        }));
+        const { facade, dataDir } = freshFacade({
+          permissionMode,
+          cloudGateway: { classify },
+          dataDirParent: homedir(),
+        });
+        try {
+          for (const relativePath of [
+            'agents/other-agent/skills/fixture-skill/references/guide.txt',
+            'agents/fixture-agent/config.yaml',
+            'agents/fixture-agent/skills-backup/guide.txt',
+            '.builtin-skills-backup/guide.txt',
+          ]) {
+            const resource = path.join(dataDir, relativePath);
+            mkdirSync(path.dirname(resource), { recursive: true });
+            writeFileSync(resource, 'synthetic private state');
+            const result = await facade.checkPermission({
+              toolName: 'read',
+              agentName: 'fixture-agent',
+              input: { path: resource },
+            });
+            expect(result.behavior).toBe('ask');
+          }
+          expect(classify).not.toHaveBeenCalled();
+        } finally {
+          cleanup(dataDir);
+        }
+      },
+    );
+
+    it.each(['.builtin-skills', 'agents/fixture-agent/skills'])(
+      'requires approval when the %s root aliases private runtime state',
+      async (skillRoot) => {
+        const { facade, dataDir } = freshFacade({ dataDirParent: homedir() });
+        try {
+          const privateRoot = path.join(dataDir, 'private-state');
+          mkdirSync(privateRoot);
+          writeFileSync(path.join(privateRoot, 'notes.txt'), 'synthetic private state');
+          const alias = path.join(dataDir, skillRoot);
+          mkdirSync(path.dirname(alias), { recursive: true });
+          symlinkSync(privateRoot, alias, 'dir');
+          for (const toolName of ['read', 'grep']) {
+            const result = await facade.checkPermission({
+              toolName,
+              agentName: 'fixture-agent',
+              input: {
+                path: toolName === 'read' ? path.join(alias, 'notes.txt') : alias,
+                pattern: '*',
+              },
+            });
+            expect(result.behavior).toBe('ask');
+          }
+        } finally {
+          cleanup(dataDir);
+        }
+      },
+    );
+
     it.each(['read', 'grep', 'glob', 'list'])(
       'keeps private runtime %s requests out of automatic approval',
       async (toolName) => {
@@ -1757,10 +1862,14 @@ describe('LocalPermissionFacade', () => {
         writeFileSync(configPath, 'synthetic: fixture-only-secret\n');
         mkdirSync(path.join(dataDir, 'memory'));
         mkdirSync(path.join(dataDir, 'skills'));
+        mkdirSync(path.join(dataDir, '.builtin-skills'));
+        mkdirSync(path.join(dataDir, 'agents', 'fixture-agent', 'skills'), { recursive: true });
         const aliases = [
           path.join(workspaceDir, 'notes.txt'),
           path.join(dataDir, 'memory', 'notes.txt'),
           path.join(dataDir, 'skills', 'notes.txt'),
+          path.join(dataDir, '.builtin-skills', 'notes.txt'),
+          path.join(dataDir, 'agents', 'fixture-agent', 'skills', 'notes.txt'),
         ];
         for (const alias of aliases) {
           symlinkSync(configPath, alias);

+ 88 - 1
packages/local-runtime/test/unit/local-runtime-host-output-safety-concurrency.test.ts

@@ -1,3 +1,5 @@
+import { LocalAgentTurnRunner } from '../../../local-runtime-v2/src/service/turn-system/agent-host/runner/local-agent-turn-runner.js';
+import { logger } from '../../src/common/logger.js';
 // Concurrency isolation for the output-safety host loop.
 //
 // The blocked flag / abort / review buffers live on per-attempt writer instances
@@ -8,7 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
 
 import { LocalRuntimeHost, type LocalTurnRunner } from '../../src/runtime/host.js';
 import { RespDataType } from '@mavis/agent-core/protocol/agent-message';
-import { RuntimeEventType, type IRuntimeEvent } from '@mavis/protocol';
+import { RuntimeEventStatus, RuntimeEventType, type IRuntimeEvent } from '@mavis/protocol';
 
 function finalMessage(content: string): IRuntimeEvent {
   return {
@@ -57,6 +59,91 @@ describe('LocalRuntimeHost output safety — concurrency isolation', () => {
     delete process.env.IDC;
   });
 
+  it('records a review stop while retaining completed terminal semantics', async () => {
+    const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
+    const fetchMock = vi
+      .spyOn(globalThis, 'fetch')
+      .mockRejectedValue(new DOMException('timeout', 'TimeoutError'));
+    const host = new LocalRuntimeHost({
+      safetyApiVersion: 'v2',
+      outputSafetyRetryDelay: async () => {},
+      piRunner: {
+        async runTurn(input) {
+          await input.eventWriter.pushRuntime(finalMessage('unreviewed-output'));
+        },
+      },
+    });
+    const output = await host.runTurn({
+      workspaceDir: '/tmp/ws',
+      systemPrompt: '',
+      userMessage: { text: 'hi' },
+      llm: { model: {} as never },
+      sessionId: 'ses',
+      turnId: 'turn',
+    });
+    expect(fetchMock).toHaveBeenCalledTimes(4);
+    expect(output).toMatchObject({ networkStopped: true, retracted: false });
+    expect(output.events.filter((event) => event.type === RuntimeEventType.STREAM_RESP)).toEqual(
+      [],
+    );
+    expect(output.events).toContainEqual(
+      expect.objectContaining({
+        type: RuntimeEventType.SESSION_STATUS,
+        payload: expect.objectContaining({ status: RuntimeEventStatus.COMPLETED }),
+      }),
+    );
+    expect(log).toHaveBeenCalledWith(
+      {
+        sessionId: 'ses',
+        turnId: 'turn',
+        reviewOutcome: 'unavailable',
+        outputSuppressed: true,
+        terminalStatus: 'completed',
+      },
+      '[content-safety] output review stopped turn',
+    );
+    expect(JSON.stringify(log.mock.calls)).not.toContain('unreviewed-output');
+  });
+
+  it.each([false, true])('diagnoses the V2 review stop without overriding runner failure: %s', async (runnerFailed) => {
+    const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
+    const events: IRuntimeEvent[] = [];
+    const eventWriter = {
+      events,
+      async pushRuntime(event: IRuntimeEvent) { events.push(event); },
+      async appendEvents(next: IRuntimeEvent[]) { events.push(...next); },
+    };
+    const reviewContent = vi.fn(async () => ({ pass: false, errorKind: 'local_error' as const }));
+    const runner = new LocalAgentTurnRunner({
+      reviewContent,
+      outputSafetyRetryDelay: async () => {},
+      piRunner: { async runTurn(input) {
+        await input.eventWriter.pushRuntime(finalMessage('unreviewed-output'));
+        if (runnerFailed) await input.eventWriter.pushRuntime({
+          ...finalMessage(''), type: RuntimeEventType.SESSION_STATUS,
+          payload: { status: RuntimeEventStatus.FAILED },
+        });
+      } },
+    });
+    const output = await runner.runTurn({
+      workspaceDir: '/tmp/ws', systemPrompt: '', userMessage: { text: 'hi' },
+      llm: { model: {} as never }, sessionId: 'ses', turnId: 'turn', eventWriter,
+      toolContext: { agentName: 'test', parentAgentConfig: {}, trustedExactWritePaths: [], eventWriter } as never,
+    });
+    expect(reviewContent).toHaveBeenCalledTimes(4);
+    expect(events.filter(event => event.type === RuntimeEventType.STREAM_RESP)).toEqual([]);
+    expect(output.outcome.status).toBe(runnerFailed ? 'failed' : 'completed');
+    if (runnerFailed) {
+      expect(log).not.toHaveBeenCalled();
+    } else {
+      expect(output).toMatchObject({ networkStopped: true, retracted: false, reconcile: { kind: 'network-reconcile' } });
+      expect(log).toHaveBeenCalledWith({
+        sessionId: 'ses', turnId: 'turn', reviewOutcome: 'unavailable',
+        outputSuppressed: true, terminalStatus: 'completed',
+      }, '[content-safety] output review stopped turn');
+    }
+  });
+
   it('a rejected turn never contaminates a concurrent clean turn', async () => {
     const fetchMock = installContentAwareFetch();
     // One shared runner + one shared host drive both turns. Each turn emits

+ 16 - 3
packages/local-runtime/test/unit/session-diff-fallback.test.ts

@@ -13,6 +13,7 @@ let root: string;
 let workspaceDir: string;
 let dataDir: string;
 let diffStore: SqliteLocalTurnDiffStore;
+const pendingReads = new Set<ReturnType<typeof readLocalSessionDiff>>();
 
 function git(...args: string[]): string {
   return execFileSync('git', args, { cwd: workspaceDir, encoding: 'utf8' });
@@ -29,11 +30,17 @@ function commit(): void {
 }
 
 async function read(messageId?: string) {
-  return readLocalSessionDiff({
+  const pending = readLocalSessionDiff({
     diffStore,
     session: { sessionId: 'test-session', workspaceDir },
     messageId,
   });
+  pendingReads.add(pending);
+  try {
+    return await pending;
+  } finally {
+    pendingReads.delete(pending);
+  }
 }
 
 beforeEach(async () => {
@@ -58,10 +65,14 @@ beforeEach(async () => {
 });
 
 afterEach(async () => {
+  // A Vitest timeout does not cancel the Git processes started by a read.
+  // Drain them before changing their environment or deleting their cwd; otherwise
+  // Windows reports EBUSY and unfinished work can overlap the next fixture.
+  await Promise.allSettled(pendingReads);
   closeLocalRuntimeDb(dataDir);
   vi.unstubAllEnvs();
   await rm(root, { recursive: true, force: true });
-});
+}, process.platform === 'win32' ? 30_000 : 10_000);
 
 const portableNames = ['中文.txt', 'with spaces.txt', 'dir/{before after}.txt'];
 const posixNames = [
@@ -77,6 +88,8 @@ describe.each(['true', 'false'])('session diff fallback with core.quotePath=%s',
     git('config', 'core.quotePath', quotePath);
   });
 
+  // This integration case creates a commit, migrates SQLite and runs real Git.
+  // Real Windows runs have exhausted its default 5s test deadline.
   it('preserves Unicode paths and attaches each tracked patch through the public API', async () => {
     for (const file of portableNames) await write(file, 'first\n');
     commit();
@@ -94,7 +107,7 @@ describe.each(['true', 'false'])('session diff fallback with core.quotePath=%s',
         diff: expect.stringContaining(`+added-${index}\n`),
       });
     }
-  });
+  }, process.platform === 'win32' ? 15_000 : 5_000);
 
   it('reports rename edits against the destination path', async () => {
     await write('before.txt', 'a\nb\nc\nd\ne\nf\n');

+ 2 - 1
packages/shared/src/asset-markup/deliver-assets.ts

@@ -413,7 +413,8 @@ function parseMediaItem(
     }
   }
 
-  const src = attrs['src']?.trim();
+  // Some models emit a local file's path as an attribute instead of src.
+  const src = attrs['src']?.trim() || attrs['path']?.trim();
   if (!src) {
     return null;
   }

+ 50 - 4
packages/shared/src/safety-check-v2.ts

@@ -36,11 +36,52 @@ export type SafetyCheckV2Headers = NonNullable<RequestInit['headers']>;
 
 export type SafetyCheckV2ErrorKind = 'auth' | 'http' | 'transport' | 'response' | 'upstream';
 
+export type SafetyTransportKind = 'dns' | 'connect' | 'tls' | 'timeout' | 'aborted' | 'unknown';
+
+/** Only allowlisted categories survive; never retain exception text, URLs or causes. */
+export function classifySafetyTransportError(error: unknown): SafetyTransportKind {
+  let current = error;
+  for (let depth = 0; depth < 4 && isSafetyCheckV2Record(current); depth += 1) {
+    const { name } = current;
+    const code = typeof current.code === 'string' ? current.code : '';
+    if (
+      name === 'TimeoutError' ||
+      [
+        'ETIMEDOUT',
+        'UND_ERR_CONNECT_TIMEOUT',
+        'UND_ERR_HEADERS_TIMEOUT',
+        'UND_ERR_BODY_TIMEOUT',
+      ].includes(code)
+    )
+      return 'timeout';
+    if (name === 'AbortError' || code === 'ABORT_ERR') return 'aborted';
+    if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') return 'dns';
+    if (
+      ['ECONNREFUSED', 'ECONNRESET', 'ENETUNREACH', 'EHOSTUNREACH', 'UND_ERR_SOCKET'].includes(code)
+    )
+      return 'connect';
+    if (
+      [
+        'CERT_HAS_EXPIRED',
+        'DEPTH_ZERO_SELF_SIGNED_CERT',
+        'SELF_SIGNED_CERT_IN_CHAIN',
+        'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
+        'ERR_TLS_CERT_ALTNAME_INVALID',
+        'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
+      ].includes(code)
+    )
+      return 'tls';
+    current = current.cause;
+  }
+  return 'unknown';
+}
+
 /** A failed check has no verdict. Callers must handle it separately from Allow. */
 export class SafetyCheckV2Error extends Error {
   constructor(
     readonly kind: SafetyCheckV2ErrorKind,
     readonly statusCode?: number,
+    readonly transportKind?: SafetyTransportKind,
   ) {
     super(`SafetyCheckV2 ${kind} error`);
     this.name = 'SafetyCheckV2Error';
@@ -71,8 +112,8 @@ export async function postSafetyCheckV2(input: {
       signal: input.signal ? AbortSignal.any([input.signal, timeout]) : timeout,
       redirect: 'error',
     });
-  } catch {
-    throw new SafetyCheckV2Error('transport');
+  } catch (error) {
+    throw new SafetyCheckV2Error('transport', undefined, classifySafetyTransportError(error));
   }
   if (!response.ok) {
     throw new SafetyCheckV2Error(
@@ -83,8 +124,13 @@ export async function postSafetyCheckV2(input: {
   let body: unknown;
   try {
     body = await response.json();
-  } catch {
-    throw new SafetyCheckV2Error('response');
+  } catch (error) {
+    const transportKind = classifySafetyTransportError(error);
+    throw new SafetyCheckV2Error(
+      transportKind === 'unknown' ? 'response' : 'transport',
+      response.status,
+      transportKind,
+    );
   }
   if (!isSafetyCheckV2Record(body)) throw new SafetyCheckV2Error('response');
   return body;

+ 3 - 1
packages/tui/docs/status-line-config.md

@@ -60,6 +60,7 @@ Configuration loading checks that the value is an array. The TUI validates indiv
 | `token-quota` | Token quota / plan |
 | `cache-read-ratio` | Aggregate cache read ratio for the current session, such as `Cache 80%` |
 | `context-remaining` | Remaining context percentage from the same runtime snapshot as `/context`; hidden if unavailable |
+| `context-meter` | Remaining context gauge, e.g. `Context ▕██████░░▏ 77% left`, from the same runtime snapshot as `/context`; hidden if unavailable; opt-in |
 | `custom-command` | External command stdout; first line inline by default, optional separate multiline block; opt-in |
 
 `cache-read-ratio` aggregates persisted session usage as `cacheRead / (input + cacheRead + cacheWrite)`, where `input` is fresh uncached input. It uses existing provider usage fields; missing cache counts contribute zero, so sessions mixing providers can underestimate cache reads. The item is hidden before any prompt tokens exist. In-process notifications refresh the session after usage persists; read failures stay silent. `/usage` also shows Read, Fresh, and Write token counts.
@@ -78,6 +79,7 @@ Configuration loading checks that the value is an array. The TUI validates indiv
 | `quota` / `token-plan` | `token-quota` |
 | `cache-read` | `cache-read-ratio` |
 | `context` / `context-left` | `context-remaining` |
+| `context-bar` / `context-gauge` | `context-meter` |
 | `custom` | `custom-command` |
 
 ## Defaults
@@ -90,7 +92,7 @@ current-dir · session-title · git-branch · review-link · plan-mode · approv
 
 `build-mode` is **not a default**. Explicitly listing it is the only way to enable the machine-readable protocol; the build type does not matter. It may appear anywhere in the list and takes over the entire line to keep free text out of the strict record. Remove it to disable the protocol.
 
-By default, `context-window` shows capacity before usage is available; `context-remaining` replaces it once a runtime usage snapshot exists. Explicit item lists retain the selected presentation. Session changes clear old data, and refresh failures do not reuse stale values. Context comes from the latest runtime snapshot, not a live per-token counter. `cache-read-ratio` remains opt-in. Narrow terminals prioritize permissions, context warnings, model, and session title. Even the shortest context display retains `Ctx` to distinguish it from `5h` / `W` plan quotas.
+By default, `context-window` shows capacity before usage is available; `context-remaining` replaces it once a runtime usage snapshot exists. Explicit item lists retain the selected presentation. Session changes clear old data, and refresh failures do not reuse stale values. Context comes from the latest runtime snapshot, not a live per-token counter. `cache-read-ratio` and `context-meter` remain opt-in; `context-meter` renders the same remaining-headroom value and thresholds as `context-remaining` with an added gauge, and takes precedence over `context-remaining` when both are listed, regardless of order. Other items retain their order, and the meter stays at its configured position. It shrinks from eight gauge cells to six, then to `Ctx N%` as space runs out. Narrow terminals prioritize permissions, context warnings, model, and session title. Even the shortest context display retains `Ctx` to distinguish it from `5h` / `W` plan quotas.
 
 `custom-command` is also **not a default**. It runs an external command and requires both an explicit item and `tui.customStatusLine.command`.
 

+ 42 - 19
packages/tui/src/acp/agent.ts

@@ -19,7 +19,7 @@ import type {
 import { buildTuiMessageParts } from '../runtime/stream-events.js';
 import type { TuiMessage, TuiStreamEvent } from '../runtime/stream-events.js';
 import type { TuiAcpRuntime } from './runtime.js';
-import { executeTuiAcpCommand, TUI_ACP_AVAILABLE_COMMANDS } from './commands.js';
+import { availableSkillCommands, executeTuiAcpCommand, TUI_ACP_AVAILABLE_COMMANDS } from './commands.js';
 import {
   ACP_CONFIG_MODEL,
   ACP_CONFIG_PERMISSION_MODE,
@@ -102,6 +102,46 @@ export function createTuiAcpAgent(options: CreateTuiAcpAgentOptions): acp.AgentA
   let permissionBroadcastRunning = false;
   const app = acp.agent({ name: 'minimax-code' });
 
+  const advertiseAvailableCommands = (client: acp.AgentContext, sessionId: string): void => {
+    const attachment = sessions.get(sessionId);
+    if (!attachment) return;
+    let commands: acp.AvailableCommand[] = [...TUI_ACP_AVAILABLE_COMMANDS];
+    const isCurrent = () =>
+      sessions.get(sessionId) === attachment && !attachment.attachmentController.signal.aborted;
+    const notify = () => {
+      if (!isCurrent()) return;
+      void client
+        .notify(acp.methods.client.session.update, {
+          sessionId,
+          update: {
+            sessionUpdate: 'available_commands_update',
+            availableCommands: commands,
+          },
+        })
+        .catch(() => undefined);
+    };
+
+    // Preserve immediate native command discovery even if Skill discovery fails or stalls.
+    setImmediate(() => {
+      if (!isCurrent()) return;
+      notify();
+      void (async () => {
+        const skills = await options.runtime.listSkills(
+          attachment.session.agentName,
+          undefined,
+          attachment.session.workspaceDir,
+        );
+        if (!isCurrent()) return;
+        commands = [...TUI_ACP_AVAILABLE_COMMANDS, ...availableSkillCommands(skills)];
+        notify();
+      })().catch(() => undefined);
+    });
+    // Some clients attach their notification listener after receiving the Session response.
+    // Retry the latest roster, so a late native-only update cannot erase discovered Skills.
+    const retry = setTimeout(notify, AVAILABLE_COMMANDS_RETRY_DELAY_MS);
+    retry.unref();
+  };
+
   const schedulePermissionBroadcast = (
     client: acp.AgentContext,
     attachments: readonly (readonly [string, AcpSession])[],
@@ -1051,6 +1091,7 @@ export function createTuiAcpAgent(options: CreateTuiAcpAgentOptions): acp.AgentA
         runtime: options.runtime,
         sessionId: active.session.sessionId,
         agentName: active.session.agentName,
+        workspaceDir: active.session.workspaceDir,
         prompt: context.params.prompt,
       });
       if (isCancelled()) return { cancelled: true as const };
@@ -1807,24 +1848,6 @@ function mapClientMcpServers(servers: readonly acp.McpServer[]): readonly TuiSes
   });
 }
 
-function advertiseAvailableCommands(client: acp.AgentContext, sessionId: string): void {
-  const notify = () => {
-    void client
-      .notify(acp.methods.client.session.update, {
-        sessionId,
-        update: {
-          sessionUpdate: 'available_commands_update',
-          availableCommands: [...TUI_ACP_AVAILABLE_COMMANDS],
-        },
-      })
-      .catch(() => undefined);
-  };
-
-  setImmediate(notify);
-  const retry = setTimeout(notify, AVAILABLE_COMMANDS_RETRY_DELAY_MS);
-  retry.unref();
-}
-
 interface KeyedSerialExecutor {
   <T>(key: string, task: (signal: AbortSignal) => Promise<T>): Promise<T>;
   reserved<T>(key: string, task: (signal: AbortSignal) => Promise<T>): Promise<T>;

+ 36 - 2
packages/tui/src/acp/commands.ts

@@ -1,7 +1,8 @@
 import * as acp from '@agentclientprotocol/sdk';
 
 import { TUI_COMMAND_DESCRIPTORS } from '../application/command-descriptors.js';
-import type { TuiModel } from '../runtime/port.js';
+import { sanitizeTerminalText } from '../tui/rendering/terminal-text.js';
+import type { TuiModel, TuiSkillList } from '../runtime/port.js';
 import type { TuiAcpRuntime } from './runtime.js';
 
 export const TUI_ACP_AVAILABLE_COMMANDS = [
@@ -41,6 +42,34 @@ export const TUI_ACP_AVAILABLE_COMMANDS = [
   },
 ] satisfies readonly acp.AvailableCommand[];
 
+/** Keep native commands authoritative and expose only invocable Skill names. */
+export function availableSkillCommands(result: TuiSkillList): acp.AvailableCommand[] {
+  const seen = new Set<string>(TUI_ACP_AVAILABLE_COMMANDS.map((command) => command.name));
+  return (result.skills ?? [])
+    .flatMap((skill): acp.AvailableCommand[] => {
+      const name = skill.name.trim().toLowerCase();
+      if (
+        skill.enabled === false ||
+        seen.has(name) ||
+        name.length > 128 ||
+        !/^[a-z0-9][a-z0-9._-]*(?::[a-z0-9][a-z0-9._-]*)?$/u.test(name)
+      )
+        return [];
+      seen.add(name);
+      const description = sanitizeTerminalText(
+        skill.displayDescription ?? skill.description ?? '',
+      ).trim();
+      return [
+        {
+          name,
+          description: description ? `[Skill] ${description}` : '[Skill]',
+          input: { hint: '[instructions]' },
+        },
+      ];
+    })
+    .sort((left, right) => left.name.localeCompare(right.name));
+}
+
 export type TuiAcpCommandResult =
   | { readonly handled: false }
   | {
@@ -63,6 +92,7 @@ export async function executeTuiAcpCommand(options: {
   >;
   readonly sessionId: string;
   readonly agentName?: string;
+  readonly workspaceDir?: string;
   readonly prompt: readonly acp.ContentBlock[];
 }): Promise<TuiAcpCommandResult> {
   const command = parseCommand(options.prompt);
@@ -112,7 +142,11 @@ export async function executeTuiAcpCommand(options: {
     return {
       handled: true,
       output: formatSkills(
-        await options.runtime.listSkills(options.agentName, command.input || undefined),
+        await options.runtime.listSkills(
+          options.agentName,
+          command.input || undefined,
+          options.workspaceDir,
+        ),
       ),
     };
   }

+ 2 - 1
packages/tui/src/application/assistant-content.ts

@@ -251,9 +251,10 @@ function simplifyAssetMarkup(content: string, assets: DeliverAssetItem[]): strin
   for (let pass = 0; pass < 3; pass += 1) {
     const segments = parseDeliverAssetsContent(remaining);
     const extracted = collectAssetSegments(segments);
+    // Keep the parser's cleanup even when every attachment was invalid.
+    remaining = extracted.text;
     if (extracted.assets.length === 0) break;
     assets.push(...extracted.assets);
-    remaining = extracted.text;
   }
   return remaining;
 }

+ 14 - 0
packages/tui/src/cli/contract.ts

@@ -1,4 +1,5 @@
 import { InvalidArgumentError, Option, type Command } from 'commander';
+import { parseHeadlessModelOverride } from '../headless/model-selection.js';
 import type { TuiMode } from '../tui/engine/public.js';
 import { parseTuiStartupEnvironment } from './environment.js';
 import type { TuiBuildEnvironment } from '../auth/environment.js';
@@ -7,6 +8,7 @@ const RETIRED_TOP_LEVEL_COMMAND_NAMES = new Set(['git', 'changes', 'projects']);
 
 export interface TuiInteractiveLaunchRequest {
   readonly initialPrompt?: string;
+  readonly model?: string;
   readonly sessionId?: string;
   readonly showSessionPicker?: boolean;
   readonly continueLatestSession?: boolean;
@@ -17,6 +19,7 @@ export interface TuiInteractiveLaunchRequest {
 }
 
 export interface RawTuiInteractiveOptions {
+  readonly model?: string;
   readonly session?: string | boolean;
   readonly continue?: boolean;
   readonly resume?: string;
@@ -31,6 +34,7 @@ export function applyInteractiveCliContract(
 ): Command {
   const configured = command
     .argument('[prompt]', 'task to execute in the interactive TUI')
+    .addOption(new Option('-m, --model <provider/model>', 'select the model for this Session only'))
     .addOption(new Option('--lane <lane>', 'managed backend lane for test or staging builds'))
     .addOption(
       new Option('--session [id]', 'open a Session by id, or browse Sessions when id is omitted'),
@@ -75,8 +79,18 @@ export function resolveInteractiveLaunchRequest(
     throw new Error('--session, --continue, and --resume cannot be combined');
   }
   const sessionId = explicitSessionId || compatibilitySessionId;
+  const model = commandOptions.model?.trim();
+  if (commandOptions.model !== undefined) {
+    parseHeadlessModelOverride(model ?? '');
+    if (showSessionPicker) {
+      throw new Error(
+        '--model requires a Session id with --session; use --session <id> or --continue.',
+      );
+    }
+  }
   return {
     ...(prompt ? { initialPrompt: prompt } : {}),
+    ...(model ? { model } : {}),
     ...(sessionId ? { sessionId } : {}),
     ...(showSessionPicker ? { showSessionPicker: true } : {}),
     ...(commandOptions.continue ? { continueLatestSession: true } : {}),

+ 7 - 1
packages/tui/src/cli/environment.ts

@@ -17,7 +17,13 @@ import { readTuiRegionPreference } from '../auth/region-preference.js';
 
 const MANAGED_BACKEND_LANE_PATTERN = /^[A-Za-z0-9._-]+$/u;
 const STARTUP_ENVIRONMENT_OPTION = '--env';
-const ROOT_OPTIONS_WITH_REQUIRED_VALUES = new Set(['--lane', '--resume', '--tui-mode']);
+const ROOT_OPTIONS_WITH_REQUIRED_VALUES = new Set([
+  '--lane',
+  '--resume',
+  '--tui-mode',
+  '-m',
+  '--model',
+]);
 const STARTUP_ENVIRONMENT_ALIASES: Readonly<Record<string, TuiBuildEnvironment>> = Object.freeze({
   test: 'test',
   pre: 'staging',

+ 2 - 0
packages/tui/src/cli/main.ts

@@ -103,6 +103,7 @@ export async function runTuiCli(dependencies: RunTuiCliDependencies = {}): Promi
       allowStartupEnvironmentSelection: dependencies.allowStartupEnvironmentSelection,
       launchTui: async ({
         initialPrompt,
+        model,
         sessionId,
         showSessionPicker,
         continueLatestSession,
@@ -114,6 +115,7 @@ export async function runTuiCli(dependencies: RunTuiCliDependencies = {}): Promi
         await launchTui({
           version: MINIMAX_CODE_VERSION,
           ...(initialPrompt ? { initialPrompt } : {}),
+          ...(model ? { model } : {}),
           ...(sessionId ? { sessionId } : {}),
           ...(showSessionPicker ? { showSessionPicker: true } : {}),
           ...(continueLatestSession ? { continueLatestSession: true } : {}),

+ 1 - 1
packages/tui/src/cli/network-proxy.ts

@@ -44,7 +44,7 @@ export function resolveTuiProxyConfiguration(
     mode: 'proxy',
     httpProxy: httpProxy?.value ?? '',
     httpsProxy: httpsProxy?.value ?? '',
-    noProxy: withLoopbackNoProxy(environment.NO_PROXY ?? environment.no_proxy),
+    noProxy: withLoopbackNoProxy(firstProxyValue(environment, 'NO_PROXY', 'no_proxy')?.value),
   };
 }
 

+ 3 - 0
packages/tui/src/cli/program.ts

@@ -194,6 +194,7 @@ export function createTuiProgram(options: CreateTuiProgramOptions): Command {
     .option('--api-key-env <name>', 'environment variable containing the API key')
     .option('--context-limit <tokens>', 'context limit for every listed model', parsePositiveSafeInteger)
     .option('--output-limit <tokens>', 'output limit for every listed model', parsePositiveSafeInteger)
+    .option('--support-image', 'declare image input support for every listed model')
     .option('--use', 'test the first model, then save and select it as the default')
     .action(
       (commandOptions: {
@@ -203,6 +204,7 @@ export function createTuiProgram(options: CreateTuiProgramOptions): Command {
         model: string[];
         contextLimit?: number;
         outputLimit?: number;
+        supportImage?: boolean;
         apiKeyEnv?: string;
         use?: boolean;
       }) => {
@@ -217,6 +219,7 @@ export function createTuiProgram(options: CreateTuiProgramOptions): Command {
           models: commandOptions.model,
           contextLimit: commandOptions.contextLimit,
           outputLimit: commandOptions.outputLimit,
+          supportImage: commandOptions.supportImage,
           apiKeyEnv: commandOptions.apiKeyEnv,
           saveAndUse: commandOptions.use,
         });

+ 2 - 0
packages/tui/src/cli/provider-command.ts

@@ -14,6 +14,7 @@ export type McodeProviderCliRequest =
       readonly models: readonly string[];
       readonly contextLimit?: number;
       readonly outputLimit?: number;
+      readonly supportImage?: boolean;
       readonly apiKeyEnv?: string;
       readonly saveAndUse?: boolean;
     }
@@ -67,6 +68,7 @@ export async function runMcodeProviderCommand(
         apiFormat: request.apiFormat,
         models: request.models.map((modelId) => ({
           modelId,
+          ...(request.supportImage ? { capabilities: { support_image: true } } : {}),
           ...(request.contextLimit !== undefined || request.outputLimit !== undefined
             ? {
                 limit: {

+ 3 - 0
packages/tui/src/provider/contract.ts

@@ -1,3 +1,5 @@
+import type { ModelConfig } from '@mavis/config';
+
 export const MCODE_PROVIDER_API_FORMATS = [
   'anthropic-messages',
   'openai-completions',
@@ -74,6 +76,7 @@ export interface McodeProviderModelInput {
   readonly reasoning?: boolean;
   readonly toolCall?: boolean;
   readonly temperature?: boolean;
+  readonly capabilities?: Readonly<NonNullable<ModelConfig['capabilities']>>;
   readonly modalities?: { readonly input?: readonly string[]; readonly output?: readonly string[] };
   readonly limit?: { readonly context?: number; readonly output?: number };
 }

+ 6 - 2
packages/tui/src/runtime/adapter.ts

@@ -532,8 +532,12 @@ export class TuiRuntimeAdapter implements TuiRuntime {
   getActiveRun(sessionId: string): Promise<TuiActiveRunSnapshot> {
     return this.productAccess.getActiveRun(sessionId);
   }
-  listSkills(agentName?: string, keyword?: string): Promise<TuiSkillList> {
-    return this.productAccess.listSkills(agentName, keyword);
+  listSkills(
+    agentName?: string,
+    keyword?: string,
+    workspaceDir?: string,
+  ): Promise<TuiSkillList> {
+    return this.productAccess.listSkills(agentName, keyword, workspaceDir);
   }
   inspectProjectMcp(
     sessionId: string,

+ 2 - 1
packages/tui/src/runtime/adapters/product-access.ts

@@ -377,11 +377,12 @@ export class TuiProductAccess {
   async listSkills(
     agentName = this.defaultAgentName,
     keyword?: string,
+    workspaceDir = this.workspaceDir,
   ): Promise<TuiSkillList> {
     const service = this.context.service("skill.list");
     const result = await service.listRuntimeSkills({
       agentName,
-      ...(this.workspaceDir ? { workspaceDir: this.workspaceDir } : {}),
+      ...(workspaceDir ? { workspaceDir } : {}),
       includePluginSkills: true,
     });
     const normalizedKeyword = keyword?.trim().toLocaleLowerCase();

+ 1 - 1
packages/tui/src/runtime/port.ts

@@ -294,7 +294,7 @@ export interface TuiInspectionPort {
     agentName?: string,
     customInstructions?: string,
   ): Promise<TuiCompactionResult>;
-  listSkills(agentName?: string, keyword?: string): Promise<TuiSkillList>;
+  listSkills(agentName?: string, keyword?: string, workspaceDir?: string): Promise<TuiSkillList>;
   listMcpServers(keyword?: string, sessionId?: string): Promise<TuiMcpServer[]>;
   inspectProjectMcp(sessionId: string): Promise<TuiProjectMcpPreview | undefined>;
   getContextSnapshot(sessionId: string): Promise<TuiContextSnapshotResponse>;

+ 1 - 1
packages/tui/src/tui/controller/product/command-flow.ts

@@ -1218,7 +1218,7 @@ export class TuiCommandFlow {
           this.options.append(
             formatTuiActionFailure(error, {
               summary: "Couldn't reload TUI configuration.",
-              nextStep: 'Fix keybindings.json and retry /reload.',
+              nextStep: 'Resolve the reported configuration or plugin refresh error, then retry /reload.',
             }),
             'warning',
           );

+ 1 - 1
packages/tui/src/tui/controller/runtime/runtime-event-flow.ts

@@ -458,7 +458,7 @@ export class TuiRuntimeEventFlow {
         event.variant === 'auth'
           ? 'Content review authentication expired. Run /login, then retry.'
           : event.variant === 'network'
-            ? 'The content review service could not be reached, so this response stopped. Check your network and proxy or VPN settings, then retry.'
+            ? 'Content review did not return a usable result, so this response stopped. Unreviewed output was withheld. Retry; if this persists, use /feedback to report the review failure.'
             : 'Content review withdrew this response. Rephrase your request, then retry.',
         'warning',
       );

+ 11 - 4
packages/tui/src/tui/engine/LOCAL_CHANGES.json

@@ -47,6 +47,13 @@
       "reason": "Keep strict TypeScript fixes and product Markdown hooks, plus Pi's post-baseline wrapped-table style restoration. 链接标签使用独立样式上下文,防止外层正文或标题颜色覆盖链接颜色。 稳定 Markdown 块缓存",
       "behaviorImpact": "MCode keeps its compact code presentation without reimplementing Pi Markdown or leaking wrapped link styles into table borders and adjacent cells. 链接保留嵌套强调与行内代码,并在结束后恢复外层样式。 保留两个尾部块并对引用回退全文。"
     },
+    {
+      "path": "components/scroll-view.ts",
+      "currentSha256": "6f82fb1f426fdf81ca7058e6a1ea4a94c9ddd8f0e15d69c9020f9c66ca5411dd",
+      "changeIds": ["L035"],
+      "reason": "Allow hosts to reserve a wider always-visible scrollbar gutter while retaining at least one content column.",
+      "behaviorImpact": "The fullscreen transcript reserves three columns; other scroll views retain the default one-column gutter."
+    },
     {
       "path": "components/settings-list.ts",
       "currentSha256": "959f7db23190e0e526ca84c3032443d7d15248d891809f28c837cfa958692b5c",
@@ -148,11 +155,11 @@
     },
     {
       "path": "tui-alt-screen.ts",
-      "currentSha256": "dd8acaa441bab2e674e6cba946dcb130b97e51098adf158bda1f73bd027d7a4b",
-      "changeIds": ["L005", "L011", "L019", "L020", "L025", "L031"],
+      "currentSha256": "b1e6b332e976c5224f77ce82ee850d35c601ad18c3719d9c824b7c9db1245a78",
+      "changeIds": ["L005", "L011", "L019", "L020", "L025", "L031", "L035"],
       "upstreamCommit": "4e494929998d6bc4fccf75e0a233f727db4b70ee,1ac6128e66bd44668b58db773c2a76c29163ade5",
-      "reason": "Keep strict TypeScript fixes and layout-first mouse dispatch, join path and kebab-case word segments, and expose configurable fullscreen selection copying helpers. 活动搜索索引与命中复用 独立面板声明键盘分页归属。",
-      "behaviorImpact": "Fullscreen product interaction clicks and Pi-owned text selection coexist; double-click selects complete path-like tokens, and hosts can disable automatic copy or copy an active selection explicitly. 搜索交互复用索引。 handlesViewportKeys 为 true 时,fullscreen 分页交给焦点面板;默认仍由外层视口处理。"
+      "reason": "Keep strict TypeScript fixes and layout-first mouse dispatch, join path and kebab-case word segments, and expose configurable fullscreen selection copying helpers. 活动搜索索引与命中复用 独立面板声明键盘分页归属。 Reserve scrollbar hit targets for gutter columns and support track jumps and thumb dragging.",
+      "behaviorImpact": "Fullscreen product interaction clicks and Pi-owned text selection coexist; double-click selects complete path-like tokens, and hosts can disable automatic copy or copy an active selection explicitly. 搜索交互复用索引。 handlesViewportKeys 为 true 时,fullscreen 分页交给焦点面板;默认仍由外层视口处理。 Fullscreen track presses jump and drag without consuming adjacent content; visible overlays cancel active scrollbar drags."
     },
     {
       "path": "tui-main-screen.ts",

+ 9 - 0
packages/tui/src/tui/engine/LOCAL_CHANGES.md

@@ -106,3 +106,12 @@ Remove `L024` when the selected Pi baseline natively matches legacy-terminal `Ct
 - Change: strip leading zone prefixes before comparing screen lines, so initial frames, differential redraws, and history caches stay clean. Fullscreen behavior is unchanged.
 - Evidence: `test/unit/tui-engine-local-deltas.test.ts` checks initial and differential writes.
 - Removal condition: the selected Pi baseline supplies equivalent normal-mode filtering.
+
+## L035: Fullscreen scrollbar track interaction
+
+- Origin: adapted from [drowzeys/minimax-code commit 0b24a7778741fda335a9a2074464c69911feb1aa](https://github.com/drowzeys/minimax-code/commit/0b24a7778741fda335a9a2074464c69911feb1aa), contributed by drowzeys under the existing MIT license in [issue #216](https://github.com/MiniMax-AI/minimax-code/issues/216).
+- Product contract: the fullscreen transcript enables an always-visible scrollbar with a three-column hit gutter. Track presses center the thumb and jump before dragging; thumb presses retain their grab offset without an initial jump.
+- Minimal difference: `components/scroll-view.ts` accepts an optional `scrollbarGutter` for always-visible bars, defaulting to one column and retaining at least one content column on narrow terminals. `tui-alt-screen.ts` restricts wide hit targets to that reserved gutter, factors drag mapping into `dragScrollbarTo`, and cancels a drag when an overlay receives the next mouse event. Auto bars retain a one-column target. `layout.ts` stays at the Pi baseline.
+- Adaptation: the original contribution widened hits over two live content columns. The reserved gutter prevents those presses from swallowing content clicks or text selection. `chat-layout.ts` opts into the three-column gutter.
+- Evidence: `test/unit/tui-scrollbar-interaction.test.ts` drives SGR press, motion, release and wheel events through VirtualTerminal, covering track jumps, thumb grabs, narrow terminals, content routing, selection, overlays and the actual fullscreen ChatLayout.
+- Removal condition: the selected Pi baseline provides equivalent reserved-gutter track and drag interaction and MCode migrates to it.

+ 8 - 2
packages/tui/src/tui/engine/components/scroll-view.ts

@@ -9,6 +9,8 @@ export interface ScrollViewOptions {
 	primary?: boolean;
 	overscroll?: "chain" | "contain";
 	scrollbar?: ScrollViewScrollbar;
+	/** Columns reserved for an always-visible scrollbar, including its hit gutter. */
+	scrollbarGutter?: number;
 	scrollbarStyle?: (text: string) => string;
 	scrollbarHideDelayMs?: number;
 }
@@ -24,6 +26,7 @@ export class ScrollView extends Container {
 	readonly primary: boolean;
 	readonly overscroll: "chain" | "contain";
 	readonly scrollbarStyle: (text: string) => string;
+	private readonly scrollbarGutter: number;
 	private currentScrollbar: ScrollViewScrollbar;
 	private readonly scrollbarHideDelayMs: number;
 	private currentScrollTop = 0;
@@ -48,6 +51,9 @@ export class ScrollView extends Container {
 		this.primary = options.primary ?? false;
 		this.overscroll = options.overscroll ?? "chain";
 		this.currentScrollbar = options.scrollbar ?? "hidden";
+		this.scrollbarGutter = Number.isFinite(options.scrollbarGutter)
+			? Math.max(1, Math.floor(options.scrollbarGutter ?? 1))
+			: 1;
 		this.scrollbarStyle = options.scrollbarStyle ?? ((text) => `\x1b[100m${text}\x1b[49m`);
 		this.scrollbarHideDelayMs = Math.max(0, Math.floor(options.scrollbarHideDelayMs ?? 1000));
 	}
@@ -84,7 +90,7 @@ export class ScrollView extends Container {
 	}
 
 	getContentWidth(width: number): number {
-		return this.scrollbar === "always" && width > 1 ? width - 1 : width;
+		return this.scrollbar === "always" && width > 1 ? Math.max(1, width - this.scrollbarGutter) : width;
 	}
 
 	private markScrollbarActivity(): void {
@@ -207,7 +213,7 @@ export class ScrollView extends Container {
 	override render(width: number): string[] {
 		const contentWidth = this.getContentWidth(width);
 		const lines = this.child.render(contentWidth);
-		return contentWidth === width ? lines : lines.map((line) => `${line} `);
+		return contentWidth === width ? lines : lines.map((line) => `${line}${" ".repeat(width - contentWidth)}`);
 	}
 
 	[LAYOUT_NODE](): ScrollLayoutNode {

+ 42 - 18
packages/tui/src/tui/engine/tui-alt-screen.ts

@@ -776,11 +776,18 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
 		for (const scrollView of getScrollViewsAt(this.currentLayout, x, y)) {
 			const box = getScrollViewBox(this.currentLayout, scrollView);
 			const geometry = box ? getScrollbarGeometry(box) : undefined;
+			// Only reserved gutter columns may capture presses beside the painted bar.
+			const hitColumns = box
+				? scrollView.scrollbar === "always"
+					? box.rect.width - scrollView.getContentWidth(box.rect.width)
+					: 1
+				: 0;
 			if (
 				geometry &&
-				x === geometry.column &&
-				y >= geometry.thumbTop &&
-				y < geometry.thumbTop + geometry.thumbHeight
+				x >= geometry.column - (hitColumns - 1) &&
+				x <= geometry.column &&
+				y >= geometry.trackTop &&
+				y < geometry.trackTop + geometry.trackHeight
 			) {
 				return { scrollView, geometry };
 			}
@@ -804,25 +811,16 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
 	}
 
 	private handleScrollbarMouseEvent(event: SgrMouseEvent): boolean {
+		if (this.hasOverlay()) {
+			this.stopScrollbarDrag();
+			return false;
+		}
 		if (this.scrollbarDrag) {
 			if (event.release) {
 				this.stopScrollbarDrag();
 				return true;
 			}
-			const box = this.currentLayout
-				? getScrollViewBox(this.currentLayout, this.scrollbarDrag.scrollView)
-				: undefined;
-			const geometry = box ? getScrollbarGeometry(box) : undefined;
-			if (geometry) {
-				const maxThumbOffset = geometry.trackHeight - geometry.thumbHeight;
-				const thumbOffset = Math.max(
-					0,
-					Math.min(maxThumbOffset, event.y - geometry.trackTop - this.scrollbarDrag.grabOffset),
-				);
-				const scrollTop =
-					maxThumbOffset === 0 ? 0 : Math.round((thumbOffset / maxThumbOffset) * geometry.maxScrollTop);
-				this.scrollbarDrag.scrollView.scrollTo(scrollTop);
-			}
+			this.dragScrollbarTo(event.y);
 			return true;
 		}
 
@@ -839,13 +837,39 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
 		this.pressedUrl = undefined;
 		this.selectionDragged = false;
 		this.setScrollbarHover(target.scrollView);
+		const onThumb =
+			event.y >= target.geometry.thumbTop &&
+			event.y < target.geometry.thumbTop + target.geometry.thumbHeight;
 		this.scrollbarDrag = {
 			scrollView: target.scrollView,
-			grabOffset: event.y - target.geometry.thumbTop,
+			grabOffset: onThumb
+				? event.y - target.geometry.thumbTop
+				: Math.max(0, Math.floor(target.geometry.thumbHeight / 2)),
 		};
+		// A press on the empty track jumps the thumb so its center follows the
+		// pointer, then keeps dragging from there; a press on the thumb itself
+		// grabs it in place without moving.
+		if (!onThumb) this.dragScrollbarTo(event.y);
 		return true;
 	}
 
+	private dragScrollbarTo(y: number): void {
+		if (!this.scrollbarDrag || !this.currentLayout) return;
+		const box = getScrollViewBox(this.currentLayout, this.scrollbarDrag.scrollView);
+		const geometry = box ? getScrollbarGeometry(box) : undefined;
+		if (!geometry) return;
+		const maxThumbOffset = geometry.trackHeight - geometry.thumbHeight;
+		const thumbOffset = Math.max(
+			0,
+			Math.min(maxThumbOffset, y - geometry.trackTop - this.scrollbarDrag.grabOffset),
+		);
+		const scrollTop =
+			maxThumbOffset === 0
+				? 0
+				: Math.round((thumbOffset / maxThumbOffset) * geometry.maxScrollTop);
+		this.scrollbarDrag.scrollView.scrollTo(scrollTop);
+	}
+
 	private stopScrollbarDrag(): void {
 		this.scrollbarDrag = undefined;
 	}

+ 14 - 3
packages/tui/src/tui/engine/tui-main-screen.ts

@@ -304,6 +304,19 @@ export class TuiMainScreen extends TuiBase implements TUI {
 		// Helper to redraw either the complete logical document or only the visible viewport.
 		// Viewport-only redraws preserve the terminal's native scrollback.
 		const fullRender = (clear: boolean, viewportOnly = false): void => {
+			// Native scrollback cannot move backwards with a shrinking document. Keep the
+			// previous viewport origin so rows already scrolled out are not painted twice,
+			// and growth still writes every row before it scrolls out. Resize previews are
+			// temporary: they show the new tail until the pending full history replay.
+			if (viewportOnly && !this.historyReplayPending && newLines.length <= prevViewportTop) {
+				// Nothing remains addressable on screen; rebuild with one consistent origin.
+				viewportOnly = false;
+			}
+			const start = viewportOnly
+				? this.historyReplayPending
+					? Math.max(0, newLines.length - height)
+					: prevViewportTop
+				: 0;
 			this.fullRedrawCount += 1;
 			const output = new BoundedTerminalWriter((data) => this.terminal.write(data));
 			output.append("\x1b[?2026h"); // Begin synchronized output
@@ -311,7 +324,6 @@ export class TuiMainScreen extends TuiBase implements TUI {
 				output.append(this.deleteKittyImages(this.previousKittyImageIds));
 				output.append(viewportOnly ? "\x1b[2J\x1b[H" : "\x1b[2J\x1b[H\x1b[3J");
 			}
-			const start = viewportOnly ? Math.max(0, newLines.length - height) : 0;
 			for (let i = start; i < newLines.length; i++) {
 				if (i > start) output.append("\r\n");
 				const line = newLines[i]!;
@@ -339,8 +351,7 @@ export class TuiMainScreen extends TuiBase implements TUI {
 			} else {
 				this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
 			}
-			const bufferLength = Math.max(height, newLines.length);
-			this.previousViewportTop = Math.max(0, bufferLength - height);
+			this.previousViewportTop = Math.max(start, newLines.length - height);
 			this.positionHardwareCursor(cursorPos, newLines.length);
 			this.previousLines = newLines;
 			this.previousKittyImageIds = this.collectKittyImageIds(newLines);

+ 1 - 0
packages/tui/src/tui/features/settings/status-line-copy.ts

@@ -52,6 +52,7 @@ const descriptions: Record<Exclude<TuiStatusLineItem, 'build-mode'>, readonly [s
   'token-quota': ['Account token quota', '账户额度'],
   'cache-read-ratio': ['Session cache read ratio', '会话缓存读取比例'],
   'context-remaining': ['Remaining context window', '剩余上下文窗口'],
+  'context-meter': ['Remaining context gauge', '剩余上下文刻度条'],
   'custom-command': ['Configured custom command output', '已配置的自定义命令输出'],
 };
 

+ 27 - 3
packages/tui/src/tui/launcher.ts

@@ -21,7 +21,8 @@ import {
 } from '../host/tui-keybindings.js';
 import { createTuiApp, type CreateTuiAppOptions, type TuiApp } from './app.js';
 import type { CreatedTuiRuntime, CreateTuiRuntimeDependencies } from '../runtime/lifecycle.js';
-import type { TuiWorkspaceRoot } from '../runtime/port.js';
+import { parseHeadlessModelOverride } from '../headless/model-selection.js';
+import type { TuiRuntime, TuiWorkspaceRoot } from '../runtime/port.js';
 import { createDeferredTuiRuntime } from '../runtime/deferred.js';
 import {
   captureTuiIncidentBestEffort,
@@ -66,6 +67,7 @@ const MINIMAX_CODE_EXIT_SLOGAN = 'Intelligence with everyone, bye~';
 export interface LaunchTuiOptions {
   version: string;
   initialPrompt?: string;
+  model?: string;
   sessionId?: string;
   showSessionPicker?: boolean;
   continueLatestSession?: boolean;
@@ -83,7 +85,8 @@ export interface LaunchTuiOptions {
 type LaunchApp = Pick<TuiApp, 'ready' | 'firstFrame' | 'start' | 'stop' | 'stopped' | 'submit'> & {
   readonly editor?: Pick<TuiApp['editor'], 'disableSubmit'>;
   readonly setStartupStatus?: TuiApp['setStartupStatus'];
-  readonly controller?: Pick<TuiApp['controller'], 'snapshot'>;
+  readonly controller?: Pick<TuiApp['controller'], 'snapshot'> &
+    Partial<Pick<TuiApp['controller'], 'ensureSession'>>;
   readonly openSession?: TuiApp['openSession'];
   readonly continueLatestSession?: TuiApp['continueLatestSession'];
   readonly suspend?: TuiApp['suspend'];
@@ -150,6 +153,12 @@ export async function launchTui(
   options: LaunchTuiOptions,
   dependencies: LaunchTuiDependencies = {},
 ): Promise<void> {
+  if (options.model !== undefined) parseHeadlessModelOverride(options.model.trim());
+  if (options.model !== undefined && options.showSessionPicker) {
+    throw new Error(
+      '--model requires a Session id with --session; use --session <id> or --continue.',
+    );
+  }
   if (!options.terminal && (!process.stdin.isTTY || !process.stdout.isTTY)) {
     throw new Error('Minimax Code interactive mode requires a TTY.');
   }
@@ -521,7 +530,7 @@ export async function launchTui(
         durationMs: performance.now() - runtimeStartedAt,
       });
       await app.ready;
-      initialStateReady = await prepareInitialTuiState(app, observability, options);
+      initialStateReady = await prepareInitialTuiState(app, observability, options, runtime.adapter);
       startupStatus.stop();
       startupStatus = undefined;
       if (app.editor) app.editor.disableSubmit = false;
@@ -884,6 +893,7 @@ async function prepareInitialTuiState(
   app: LaunchApp,
   observability: TuiObservability,
   options: LaunchTuiOptions,
+  runtime: TuiRuntime,
 ): Promise<boolean> {
   const sessionId = options.sessionId?.trim();
   if (sessionId) {
@@ -912,6 +922,20 @@ async function prepareInitialTuiState(
       return false;
     }
   }
+  if (options.model !== undefined) {
+    const model = parseHeadlessModelOverride(options.model.trim());
+    if (!app.controller?.ensureSession || !app.openSession) {
+      throw new Error('TUI Session model selection is unavailable.');
+    }
+    const session = await app.controller.ensureSession();
+    // The normal model picker also saves the global default. Startup overrides
+    // must use the Session-only operation, before login checks or any submission.
+    if (!(await runtime.selectSessionModel(model, session.sessionId))) {
+      throw new Error(`Could not select --model ${options.model}. Check the provider and model id.`);
+    }
+    // Rehydrate account status, model/effort and queued-input state from Runtime.
+    await app.openSession(session.sessionId);
+  }
   if (options.showSessionPicker) await app.submit('/sessions');
   return true;
 }

+ 2 - 0
packages/tui/src/tui/shell/chat-layout.ts

@@ -124,6 +124,8 @@ export class TuiChatLayout implements Component {
       follow: 'end',
       primary: true,
       overscroll: 'contain',
+      scrollbar: 'always',
+      scrollbarGutter: 3,
     });
     this.fullscreenLayoutRoot = new VStack([
       {

+ 20 - 8
packages/tui/src/tui/shell/chrome.ts

@@ -134,7 +134,12 @@ export class TuiStatusLine implements Component {
 function resolveStatusLineItems(state: TuiShellState): readonly TuiStatusLineItem[] {
   const items = state.statusLineItems ?? TUI_STATUS_LINE_DEFAULT_ITEMS;
   if (!items.includes('build-mode')) {
-    if (state.statusLineItems !== undefined) return items;
+    if (state.statusLineItems !== undefined) {
+      // The opt-in meter replaces the percentage at the meter's configured position.
+      return items.includes('context-meter')
+        ? items.filter((item) => item !== 'context-remaining')
+        : items;
+    }
     const remaining = contextRemainingPercent(state);
     return items.filter((item) =>
       remaining === undefined ? item !== 'context-remaining' : item !== 'context-window',
@@ -249,11 +254,12 @@ function buildStatusSegment(
         { shrinkPriority: 48, dropPriority: 10 },
       );
     case 'context-remaining':
+    case 'context-meter':
       return createStatusSegment(
         [
-          renderContextRemaining(state, 'full'),
-          renderContextRemaining(state, 'compact'),
-          renderContextRemaining(state, 'minimal'),
+          renderContextRemaining(state, 'full', item === 'context-meter'),
+          renderContextRemaining(state, 'compact', item === 'context-meter'),
+          renderContextRemaining(state, 'minimal', item === 'context-meter'),
         ],
         { shrinkPriority: 50, dropPriority: 80 },
       );
@@ -443,19 +449,25 @@ function contextRemainingPercent(state: TuiShellState): number | undefined {
   return Math.round(((contextWindow - used) / contextWindow) * 100);
 }
 
+/** Both presentations share usage, fallback, thresholds and the minimal label. */
 function renderContextRemaining(
   state: TuiShellState,
   density: 'full' | 'compact' | 'minimal' = 'full',
+  meter = false,
 ): string {
   const remaining = contextRemainingPercent(state);
   if (remaining === undefined) return '';
   const color = remaining <= 10 ? colors.error : remaining <= 25 ? colors.warning : colors.muted;
+  let gauge = '';
+  if (meter && density !== 'minimal') {
+    const cells = density === 'full' ? 8 : 6;
+    const filled = Math.round((remaining / 100) * cells);
+    gauge = `▕${'█'.repeat(filled)}${'░'.repeat(cells - filled)}▏ `;
+  }
   const label =
     density === 'full'
-      ? `Context ${remaining}% left`
-      : density === 'compact'
-        ? `Ctx ${remaining}%`
-        : `Ctx ${remaining}%`;
+      ? `Context ${gauge}${remaining}% left`
+      : `Ctx ${gauge}${remaining}%`;
   return chalk.hex(color)(label);
 }
 

+ 4 - 1
packages/tui/src/tui/shell/status-line-items.ts

@@ -9,7 +9,7 @@
  * (`tui.statusLine`), so renaming one is a breaking change. Legacy aliases keep
  * older configuration working.
  *
- * `cache-read-ratio`, `context-remaining` and `review-link` are conditional
+ * `cache-read-ratio`, `context-remaining`, `context-meter` and `review-link` are conditional
  * items. They only render when the Runtime surfaces their matching projection
  * into the shell state, so unsupported or not-yet-recorded metrics stay silent.
  *
@@ -34,6 +34,7 @@ export const TUI_STATUS_LINE_ITEMS = [
   'token-quota',
   'cache-read-ratio',
   'context-remaining',
+  'context-meter',
   'custom-command',
 ] as const;
 
@@ -67,6 +68,8 @@ const TUI_STATUS_LINE_ITEM_ALIASES: Readonly<Record<string, TuiStatusLineItem>>
   'cache-read': 'cache-read-ratio',
   context: 'context-remaining',
   'context-left': 'context-remaining',
+  'context-bar': 'context-meter',
+  'context-gauge': 'context-meter',
   custom: 'custom-command',
 };
 

+ 216 - 2
packages/tui/test/unit/acp-agent.test.ts

@@ -1,6 +1,7 @@
 import * as acp from '@agentclientprotocol/sdk';
 import { describe, expect, it, vi } from 'vitest';
 
+import { TUI_ACP_AVAILABLE_COMMANDS } from '../../src/acp/commands.js';
 import { createTuiAcpAgent } from '../../src/acp/agent.js';
 import { TuiAcpPromptContinuation } from '../../src/acp/prompt-continuation.js';
 import type { TuiAcpRuntime } from '../../src/acp/runtime.js';
@@ -79,7 +80,7 @@ function createRuntime(
     Promise.resolve(options.contextSnapshot ?? { status: 'empty' as const }),
   );
   const getSessionUsage = vi.fn(async () => options.sessionUsage ?? {});
-  const listSkills = vi.fn(async () => options.skills ?? {});
+  const listSkills = vi.fn<TuiAcpRuntime['listSkills']>(async () => options.skills ?? {});
   const listMcpServers = vi.fn(async () => [...(options.mcpServers ?? [])]);
   const requestCompaction = vi.fn(async () => ({ success: true }));
   const getPlanModeCapabilities = vi.fn(async () => ({ entryEnabled: true }));
@@ -267,6 +268,219 @@ function createRuntime(
 }
 
 describe('MiniMax Code ACP agent', () => {
+  it.each(['new', 'load', 'resume', 'fork'] as const)(
+    'advertises session Skills on %s and forwards Skill instructions to the Runtime',
+    async (method) => {
+      const { runtime, listSkills, sendMessage, getSession, forkSession } = createRuntime(
+        [{ type: 'session-status', status: 'finished' }],
+        {
+          skills: {
+            skills: [
+              {
+                name: 'matt:review',
+                description: 'Review changes',
+                enabled: true,
+              },
+              { name: 'repo-test', displayDescription: 'Test the project' },
+              { name: 'MATT:REVIEW', description: 'Duplicate' },
+              {
+                name: 'Compact',
+                description: 'Must not replace a native command',
+              },
+              { name: 'disabled', enabled: false },
+              { name: 'invalid/name' },
+              { name: 'invalid name' },
+              { name: '' },
+              { name: 'x'.repeat(129) },
+              { name: 'bad\u001b[31m' },
+            ],
+          },
+        },
+      );
+      getSession.mockImplementation(async (sessionId) => ({
+        sessionId,
+        workspaceDir: '/project',
+        agentName: 'reviewer',
+      }));
+      forkSession.mockResolvedValue({
+        session: {
+          sessionId: 'session-fork',
+          workspaceDir: '/project',
+          agentName: 'reviewer',
+        },
+      });
+      const updates: acp.SessionNotification[] = [];
+      const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
+      const client = acp
+        .client({ name: 'zed' })
+        .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
+      await client.connectWith(agent, async (connection) => {
+        await connection.request(acp.methods.agent.initialize, {
+          protocolVersion: acp.PROTOCOL_VERSION,
+          clientCapabilities: {},
+        });
+        const response = await connection.request(acp.methods.agent.session[method], {
+          sessionId: 'session-1',
+          cwd: '/project',
+          mcpServers: [],
+        });
+        const sessionId = 'sessionId' in response ? response.sessionId : 'session-1';
+        const roster = () =>
+          updates
+            .filter(
+              (update) =>
+                update.sessionId === sessionId &&
+                update.update.sessionUpdate === 'available_commands_update',
+            )
+            .at(-1)?.update;
+        const expected = {
+          sessionUpdate: 'available_commands_update',
+          availableCommands: [
+            ...TUI_ACP_AVAILABLE_COMMANDS,
+            {
+              name: 'matt:review',
+              description: '[Skill] Review changes',
+              input: { hint: '[instructions]' },
+            },
+            {
+              name: 'repo-test',
+              description: '[Skill] Test the project',
+              input: { hint: '[instructions]' },
+            },
+          ],
+        };
+        await vi.waitFor(() => expect(roster()).toEqual(expected));
+        expect(listSkills).toHaveBeenCalledWith(
+          method === 'new' ? undefined : 'reviewer',
+          undefined,
+          '/project',
+        );
+        // A delayed listener retry must retain the complete Skill roster.
+        await new Promise((resolve) => setTimeout(resolve, 130));
+        expect(roster()).toEqual(expected);
+        await expect(
+          connection.request(acp.methods.agent.session.prompt, {
+            sessionId,
+            prompt: [{ type: 'text', text: '/matt:review focus on error handling' }],
+          }),
+        ).resolves.toEqual({ stopReason: 'end_turn' });
+        expect(sendMessage).toHaveBeenCalledWith(
+          expect.objectContaining({
+            id: sessionId,
+            content: '/matt:review focus on error handling',
+          }),
+          expect.any(AbortSignal),
+        );
+      });
+    },
+  );
+
+  it.each(['reject', 'stall'] as const)(
+    'keeps native commands available when Skill discovery can %s',
+    async (failure) => {
+      const { runtime, listSkills } = createRuntime();
+      if (failure === 'reject') listSkills.mockRejectedValue(new Error('Unavailable'));
+      else listSkills.mockImplementation(() => new Promise(() => undefined));
+      const updates: acp.SessionNotification[] = [];
+      const client = acp
+        .client({ name: 'zed' })
+        .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
+      await client.connectWith(
+        createTuiAcpAgent({ runtime, version: '1.2.3' }),
+        async (connection) => {
+          await connection.request(acp.methods.agent.initialize, {
+            protocolVersion: acp.PROTOCOL_VERSION,
+            clientCapabilities: {},
+          });
+          const { sessionId } = await connection.request(acp.methods.agent.session.new, {
+            cwd: '/workspace',
+            mcpServers: [],
+          });
+          await vi.waitFor(() =>
+            expect(updates).toContainEqual({
+              sessionId,
+              update: {
+                sessionUpdate: 'available_commands_update',
+                availableCommands: TUI_ACP_AVAILABLE_COMMANDS,
+              },
+            }),
+          );
+          await expect(
+            connection.request(acp.methods.agent.session.prompt, {
+              sessionId,
+              prompt: [{ type: 'text', text: '/help' }],
+            }),
+          ).resolves.toEqual({ stopReason: 'end_turn' });
+        },
+      );
+    },
+  );
+
+  it.each(['close', 'resume'] as const)(
+    'ignores late Skill discovery after session %s',
+    async (method) => {
+      const { runtime, listSkills } = createRuntime([], {
+        skills: { skills: [{ name: 'current' }] },
+      });
+      let resolveSkills!: (skills: TuiSkillList) => void;
+      listSkills.mockImplementationOnce(
+        () =>
+          new Promise((resolve) => {
+            resolveSkills = resolve;
+          }),
+      );
+      const updates: acp.SessionNotification[] = [];
+      const client = acp
+        .client({ name: 'zed' })
+        .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
+      await client.connectWith(
+        createTuiAcpAgent({ runtime, version: '1.2.3' }),
+        async (connection) => {
+          await connection.request(acp.methods.agent.initialize, {
+            protocolVersion: acp.PROTOCOL_VERSION,
+            clientCapabilities: {},
+          });
+          const { sessionId } = await connection.request(acp.methods.agent.session.new, {
+            cwd: '/workspace',
+            mcpServers: [],
+          });
+          await vi.waitFor(() => expect(listSkills).toHaveBeenCalledOnce());
+          await connection.request(acp.methods.agent.session[method], {
+            sessionId,
+            cwd: '/workspace',
+            mcpServers: [],
+          });
+          if (method === 'resume') {
+            await vi.waitFor(() =>
+              expect(updates).toContainEqual({
+                sessionId,
+                update: {
+                  sessionUpdate: 'available_commands_update',
+                  availableCommands: [
+                    ...TUI_ACP_AVAILABLE_COMMANDS,
+                    {
+                      name: 'current',
+                      description: '[Skill]',
+                      input: { hint: '[instructions]' },
+                    },
+                  ],
+                },
+              }),
+            );
+          }
+          resolveSkills({ skills: [{ name: 'stale' }] });
+          const count = updates.length;
+          await new Promise((resolve) => setTimeout(resolve, 130));
+          const rosters = updates.flatMap(({ update }) =>
+            update.sessionUpdate === 'available_commands_update' ? update.availableCommands : [],
+          );
+          expect(rosters.some((command) => command.name === 'stale')).toBe(false);
+          if (method === 'close') expect(updates).toHaveLength(count);
+        },
+      );
+    },
+  );
+
   it('advertises and executes native help and model commands without starting an Agent turn', async () => {
     const { runtime, sendMessage, listModels, selectModel } = createRuntime([], {
       models: [
@@ -555,7 +769,7 @@ describe('MiniMax Code ACP agent', () => {
     });
 
     expect(getContextSnapshot).toHaveBeenCalledWith('session-1');
-    expect(listSkills).toHaveBeenCalledWith(undefined, 'review');
+    expect(listSkills).toHaveBeenCalledWith(undefined, 'review', '/workspace');
     expect(listMcpServers).toHaveBeenCalledWith('git', 'session-1');
     expect(getSessionUsage).toHaveBeenCalledWith('session-1');
     expect(sendMessage).not.toHaveBeenCalled();

+ 39 - 0
packages/tui/test/unit/headless-model-selection.test.ts

@@ -397,3 +397,42 @@ describe('resolveHeadlessModelSelection', () => {
     ).resolves.toEqual({ providerId: 'provider', modelId: 'model', variant: 'fast' });
   });
 });
+
+describe('resolveHeadlessModelSelection with Kimi K3 effort levels', () => {
+  const k3Runtime = () =>
+    runtimeWith(
+      catalog({
+        providerId: 'custom_provider:moonshotai',
+        modelId: 'kimi-k3',
+        selected: true,
+        effortOptions: ['low', 'high', 'max'],
+      }),
+    );
+
+  it.each(['low', 'high', 'max'] as const)('accepts --effort %s', async (effort) => {
+    await expect(
+      resolveHeadlessModelSelection({
+        model: 'custom_provider:moonshotai/kimi-k3',
+        effort,
+        session: session(),
+        runtime: k3Runtime(),
+      }),
+    ).resolves.toEqual({
+      providerId: 'custom_provider:moonshotai',
+      modelId: 'kimi-k3',
+      thinking: { effort },
+    });
+  });
+
+  it('rejects an effort level Kimi K3 does not declare', async () => {
+    await expectInvocationError(
+      resolveHeadlessModelSelection({
+        model: 'custom_provider:moonshotai/kimi-k3',
+        effort: 'medium',
+        session: session(),
+        runtime: k3Runtime(),
+      }),
+      '--effort medium is not available for custom_provider:moonshotai/kimi-k3. Available levels: low, high, max.',
+    );
+  });
+});

+ 70 - 0
packages/tui/test/unit/network-proxy.test.ts

@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest';
+import {
+  resolveTuiProxyConfiguration,
+  shouldBypassTuiProxy,
+} from '../../src/cli/network-proxy.js';
+
+const PROXY_URL = 'http://proxy.example.invalid:8080';
+
+describe('NO_PROXY environment precedence', () => {
+  it.each([undefined, '', ' \t\n '])(
+    'falls back to no_proxy when NO_PROXY is %j',
+    (noProxy) => {
+      const configuration = resolveTuiProxyConfiguration({
+        HTTPS_PROXY: PROXY_URL,
+        NO_PROXY: noProxy,
+        no_proxy: ' internal.example.invalid ',
+      });
+
+      expect(configuration.mode).toBe('proxy');
+      if (configuration.mode !== 'proxy') throw new Error('Expected proxy configuration');
+      expect(
+        shouldBypassTuiProxy(new URL('https://internal.example.invalid/v1'), configuration.noProxy),
+      ).toBe(true);
+      expect(
+        shouldBypassTuiProxy(new URL('https://external.example.invalid/v1'), configuration.noProxy),
+      ).toBe(false);
+      for (const host of ['localhost', '127.0.0.1', '[::1]']) {
+        expect(shouldBypassTuiProxy(new URL(`http://${host}/`), configuration.noProxy)).toBe(true);
+      }
+    },
+  );
+
+  it('prefers a nonblank NO_PROXY over no_proxy', () => {
+    const configuration = resolveTuiProxyConfiguration({
+      HTTPS_PROXY: PROXY_URL,
+      NO_PROXY: ' upper.example.invalid ',
+      no_proxy: 'lower.example.invalid',
+    });
+
+    expect(configuration.mode).toBe('proxy');
+    if (configuration.mode !== 'proxy') throw new Error('Expected proxy configuration');
+    expect(shouldBypassTuiProxy(new URL('https://upper.example.invalid/'), configuration.noProxy)).toBe(
+      true,
+    );
+    expect(shouldBypassTuiProxy(new URL('https://lower.example.invalid/'), configuration.noProxy)).toBe(
+      false,
+    );
+  });
+
+  it.each([undefined, '', ' \t '])(
+    'preserves the loopback defaults when both spellings are %j',
+    (noProxy) => {
+      const configuration = resolveTuiProxyConfiguration({
+        HTTPS_PROXY: PROXY_URL,
+        NO_PROXY: noProxy,
+        no_proxy: noProxy,
+      });
+
+      expect(configuration.mode).toBe('proxy');
+      if (configuration.mode !== 'proxy') throw new Error('Expected proxy configuration');
+      expect(configuration.noProxy).toBe('localhost,127.0.0.1,::1');
+    },
+  );
+
+  it('stays direct when only a bypass list is configured', () => {
+    expect(resolveTuiProxyConfiguration({ NO_PROXY: '', no_proxy: 'internal.example.invalid' })).toEqual(
+      { mode: 'direct' },
+    );
+  });
+});

+ 19 - 0
packages/tui/test/unit/runtime-product-access.test.ts

@@ -546,6 +546,25 @@ describe("TuiRuntimeAdapter product access", () => {
     expect(cliService.selectModel).toHaveBeenCalledWith(selection);
   });
 
+  it("discovers Skills in the requested Session workspace without changing the adapter default", async () => {
+    const cliService = cliServiceFixture();
+    const adapter = new TuiRuntimeAdapter(cliService, {
+      workspaceDir: "/default-workspace",
+    });
+    await adapter.listSkills("reviewer", undefined, "/session-workspace");
+    await adapter.listSkills("mavis");
+    expect(cliService.listRuntimeSkills).toHaveBeenNthCalledWith(1, {
+      agentName: "reviewer",
+      workspaceDir: "/session-workspace",
+      includePluginSkills: true,
+    });
+    expect(cliService.listRuntimeSkills).toHaveBeenNthCalledWith(2, {
+      agentName: "mavis",
+      workspaceDir: "/default-workspace",
+      includePluginSkills: true,
+    });
+  });
+
   it("registers installed Plugin Skills from the unified Runtime roster as slash commands", async () => {
     const cliService = cliServiceFixture();
     vi.mocked(cliService.listRuntimeSkills).mockImplementationOnce(

+ 247 - 5
packages/tui/test/unit/tui-app.test.ts

@@ -8,6 +8,10 @@ import {
   VStack,
   type Terminal,
 } from "../../src/tui/engine/public.js";
+import { createTuiProgram } from "../../src/cli/program.js";
+import { resolveTuiStartupEnvironmentOption } from "../../src/cli/environment.js";
+import { runTuiCli } from "../../src/cli/main.js";
+import { launchTui } from "../../src/tui/launcher.js";
 import { createTuiApp } from "../../src/tui/app.js";
 import type {
   TuiModel,
@@ -10607,7 +10611,10 @@ describe("createTuiApp", () => {
     await app.stop();
   });
 
-  it("restores a content-review retraction to the Composer without a failed Queue item", async () => {
+  it.each([
+    ['content', 'Content review withdrew this response. Rephrase your request, then retry.'],
+    ['network', 'Content review did not return a usable result, so this response stopped.'],
+  ] as const)("presents a %s review stop without a failed Queue item", async (variant, notice) => {
     const terminal = new FakeTerminal();
     const runtime = createRuntime();
     const busEvents: TuiRuntimeEvent[] = [];
@@ -10655,7 +10662,7 @@ describe("createTuiApp", () => {
         type: "content.retry.exceeded",
         timestamp: 100,
         source: "runtime-v2",
-        payload: { sessionId: "session-1", variant: "content" },
+        payload: { sessionId: "session-1", variant },
       }),
       runtimeEvent({
         type: "message.rewind",
@@ -10671,9 +10678,8 @@ describe("createTuiApp", () => {
       expect(app.editor.getText()).toBe("review this response"),
     );
     const rendered = app.tui.render(100).join("\n");
-    expect(rendered).toContain(
-      "Content review withdrew this response. Rephrase your request, then retry.",
-    );
+    expect(rendered).toContain(notice);
+    expect(rendered).not.toContain('Check your network');
     expect(rendered).not.toContain("Message kept under Failed");
     await app.submit("/queue");
     expect(app.interaction.current()).toBeUndefined();
@@ -13174,3 +13180,239 @@ describe("createTuiApp", () => {
     }
   });
 });
+
+describe("interactive CLI model startup", () => {
+  it.each([
+    [
+      "new with prompt",
+      ["-m", "custom_provider:relay/vendor/model#thinking", "hello"],
+      "session-1",
+      true,
+    ],
+    [
+      "new without prompt",
+      ["--model=custom_provider:relay/vendor/model#thinking"],
+      "session-1",
+      false,
+    ],
+    [
+      "explicit session",
+      ["--session", "existing", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
+      "existing",
+      true,
+    ],
+    [
+      "continue",
+      ["--continue", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
+      "existing",
+      true,
+    ],
+    [
+      "missing session",
+      ["--session", "missing", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
+      "missing",
+      false,
+    ],
+    [
+      "empty continue",
+      ["--continue", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
+      "existing",
+      false,
+    ],
+    ["invalid provider", ["--model", "missing/model", "hello"], "session-1", false],
+    ["invalid model", ["--model", "custom_provider:relay/missing", "hello"], "session-1", false],
+  ] as const)(
+    "routes %s through launch, hydration and submission",
+    async (_name, args, sessionId, hasPrompt) => {
+      const dataDir = await mkdtemp(join(tmpdir(), "mcode-model-startup-"));
+      const terminal = new FakeTerminal();
+      const runtime = createRuntime();
+      runtime.listBackgroundTasks = vi.fn(async () => []);
+      const models = new Map<string, { providerId: string; modelId: string; variant?: string }>();
+      const requested = {
+        providerId: "custom_provider:relay",
+        modelId: "vendor/model",
+        variant: "thinking",
+      };
+      const existing = { sessionId: "existing", workspaceDir: "/workspace", updatedAt: 10 };
+      vi.mocked(runtime.listSessions).mockResolvedValue([existing]);
+      vi.mocked(runtime.listSessionPage).mockResolvedValue({
+        sessions: [existing],
+        hasMore: false,
+      });
+      vi.mocked(runtime.getSession).mockImplementation(async (id) => ({
+        sessionId: id,
+        workspaceDir: "/workspace",
+        model: models.get(id),
+      }));
+      const failedResume = _name === "missing session" || _name === "empty continue";
+      if (_name === "missing session")
+        vi.mocked(runtime.getSession).mockRejectedValue(new Error("Session not found"));
+      if (_name === "empty continue") vi.mocked(runtime.listSessions).mockResolvedValue([]);
+      runtime.selectModel = vi.fn(async () => true);
+      runtime.selectSessionModel = vi.fn(async (model, id) => {
+        if (model.providerId !== requested.providerId || model.modelId !== requested.modelId) {
+          throw new Error("Unknown provider or model");
+        }
+        models.set(id, model);
+        return true;
+      });
+      vi.mocked(runtime.listModels).mockImplementation(async (id) => [
+        { ...requested, name: "Startup model", selected: Boolean(id && models.has(id)) },
+      ]);
+      // A global managed default needs login; the selected BYOK Session does not.
+      vi.mocked(runtime.getAccountStatus).mockImplementation(async (id) => ({
+        status: id && models.has(id) ? "ready" : "needs-login",
+        modelSource: id && models.has(id) ? "byok" : "token-plan",
+        managedTokenPresent: false,
+        warnings: [],
+      }));
+      const sentModels: unknown[] = [];
+      vi.mocked(runtime.sendMessage).mockImplementation(async function* (request) {
+        sentModels.push(models.get(request.id));
+        yield { type: "delta", content: "offline reply" };
+        yield { type: "done" };
+      });
+      const invalid = _name.startsWith("invalid");
+      const stderr = vi.fn((_text: string, callback?: () => void) => callback?.());
+      const processRef = {
+        title: "test",
+        argv: ["node", "cli.js", ...args],
+        env: {},
+        versions: { node: "24.2.0" },
+        stdout: {
+          destroyed: false,
+          writableEnded: false,
+          write: vi.fn((_text: string, cb?: () => void) => cb?.()),
+        },
+        stderr: { destroyed: false, writableEnded: false, write: stderr },
+        exit: vi.fn(),
+        exitCode: 0,
+      };
+      let app: ReturnType<typeof createTuiApp> | undefined;
+      const running = runTuiCli({
+        processRef,
+        configureNetworkProxy: () => undefined,
+        launchTui: (input) =>
+          launchTui(
+            { ...input, dataDir, terminal, workspaceDir: "/workspace" },
+            {
+              createObservability,
+              readTelemetryEnabled: () => false,
+              installProcessGuards: () => () => undefined,
+              loadRuntimeLifecycle: async () => ({
+                createTuiRuntime: async () => ({ adapter: runtime }) as never,
+                shutdownTuiRuntime: async () => false,
+              }),
+              loadUpdateApplication: async () =>
+                ({ inspect: async () => ({ status: "up-to-date" }) }) as never,
+              createApp: (options) => {
+                app = createTuiApp({ ...options, productFeatures: { queue: false } });
+                return app;
+              },
+              writeExitMessage: () => undefined,
+            },
+          ),
+      });
+      try {
+        if (invalid) {
+          await running;
+          expect(processRef.exitCode).toBe(1);
+          expect(stderr.mock.calls.flat().join(" ")).toContain("Unknown provider or model");
+          expect(runtime.sendMessage).not.toHaveBeenCalled();
+        } else if (failedResume) {
+          await vi.waitFor(() => expect(app?.editor.disableSubmit).toBe(false));
+          expect(runtime.selectSessionModel).not.toHaveBeenCalled();
+          expect(runtime.createSession).not.toHaveBeenCalled();
+          expect(runtime.sendMessage).not.toHaveBeenCalled();
+        } else {
+          await vi.waitFor(() => {
+            expect(app?.editor.disableSubmit).toBe(false);
+            expect(app?.controller.snapshot().session?.model).toEqual(requested);
+            if (hasPrompt) expect(sentModels).toEqual([requested]);
+          });
+          expect(runtime.selectSessionModel).toHaveBeenCalledWith(requested, sessionId);
+          expect(app?.controller.snapshot().account?.modelSource).toBe("byok");
+          if (sessionId === "existing") expect(runtime.createSession).not.toHaveBeenCalled();
+          if (!hasPrompt) {
+            expect(runtime.sendMessage).not.toHaveBeenCalled();
+            await app?.submit("later prompt");
+            expect(sentModels).toEqual([requested]);
+          }
+          await vi.waitFor(() => expect(app?.controller.snapshot().status).toBe("idle"));
+          await app?.submit("/new");
+          expect(app?.controller.snapshot().session).toBeUndefined();
+          expect(runtime.selectSessionModel).toHaveBeenCalledOnce();
+        }
+        expect(runtime.selectModel).not.toHaveBeenCalled();
+      } finally {
+        await app?.stop();
+        await running;
+        await rm(dataDir, { recursive: true, force: true });
+      }
+    },
+  );
+});
+
+describe("interactive model argument contract", () => {
+  function program() {
+    const launch = vi.fn(async () => undefined);
+    const command = createTuiProgram({
+      version: "test",
+      launchTui: launch,
+      runExec: vi.fn(),
+      runLogin: vi.fn(),
+      runLogout: vi.fn(),
+      runUpdate: vi.fn(),
+    })
+      .exitOverride()
+      .configureOutput({ writeErr: () => undefined });
+    return { command, launch };
+  }
+
+  it.each(["-m", "--model"])("rejects missing values for %s", async (flag) => {
+    const { command, launch } = program();
+    await expect(command.parseAsync([flag], { from: "user" })).rejects.toThrow();
+    expect(launch).not.toHaveBeenCalled();
+  });
+
+  it.each(["", "bare-model", "provider/", "/model", "provider/model#"])(
+    "rejects malformed model %j before launch",
+    async (model) => {
+      const { command, launch } = program();
+      await expect(command.parseAsync(["--model", model], { from: "user" })).rejects.toThrow(
+        "--model must use provider/model",
+      );
+      expect(launch).not.toHaveBeenCalled();
+    },
+  );
+
+  it("rejects a model with an untargeted Session picker", async () => {
+    const { command, launch } = program();
+    await expect(
+      command.parseAsync(["--session", "--model", "provider/model"], { from: "user" }),
+    ).rejects.toThrow("requires a Session id");
+    expect(launch).not.toHaveBeenCalled();
+  });
+
+  it("retains the default launch contract without a model", async () => {
+    const { command, launch } = program();
+    await command.parseAsync(["hello"], { from: "user" });
+    expect(launch).toHaveBeenCalledWith({ initialPrompt: "hello" });
+  });
+
+  it.each(["-m", "--model"])("scans startup environment after %s values", (flag) => {
+    expect(
+      resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "staging"], true),
+    ).toBe("staging");
+    expect(() =>
+      resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "prod"], false),
+    ).toThrow("only available");
+    expect(
+      resolveTuiStartupEnvironmentOption(
+        [flag, "provider/model", "exec", "--env", "staging"],
+        true,
+      ),
+    ).toBeUndefined();
+  });
+});

+ 83 - 0
packages/tui/test/unit/tui-assistant-content.test.ts

@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest';
+import { parseDeliverAssetsContent } from '@mavis/shared/asset-markup';
+import { projectAssistantContentForTerminal } from '../../src/application/assistant-content.js';
+
+describe('terminal attachment projection', () => {
+  it('renders five path-based files without seven per-tag placeholders', () => {
+    const names = ['first.py', 'second.py', 'test_first.py', 'report.md', 'notes.txt'];
+    const content = [
+      'Done.',
+      '<deliver-assets>',
+      ...names.map((name) => `<media type="file" path="/workspace/${name}" name="${name}" />`),
+      '</deliver-assets>',
+    ].join('\n');
+
+    expect(projectAssistantContentForTerminal(content)).toEqual({
+      text: 'Done.',
+      assets: names.map((name) => ({ path: `/workspace/${name}`, name })),
+    });
+  });
+
+  it.each([
+    '<deliver-assets><media type="file" name="Missing path" /></deliver-assets>',
+    '<deliver_assets><media src=" " path=" " /></deliver_assets>',
+    '<media type="file" name="Missing path" />',
+    '<deliver-assets>\n</deliver-assets>',
+  ])('removes unusable attachment markup while preserving prose: %s', (markup) => {
+    expect(projectAssistantContentForTerminal(`Before.\n\n${markup}\n\nAfter.`)).toEqual({
+      text: 'Before.\n\nAfter.',
+      assets: [],
+    });
+  });
+
+  it('preserves prose inside an invalid attachment wrapper', () => {
+    const content =
+      '<deliver-assets>Keep this explanation.<media name="Missing" /></deliver-assets>';
+    expect(projectAssistantContentForTerminal(content)).toEqual({
+      text: 'Keep this explanation.',
+      assets: [],
+    });
+  });
+
+  it('keeps valid files and deduplicates aliases in mixed attachment markup', () => {
+    const content = [
+      '<deliver-assets>',
+      '<media src="/workspace/report.txt" name="Report" />',
+      '<media path="/workspace/report.txt" />',
+      '<media name="Missing" />',
+      '<media path="/workspace/notes.txt" />',
+      '</deliver-assets>',
+    ].join('\n');
+    expect(projectAssistantContentForTerminal(content)).toEqual({
+      text: '',
+      assets: [{ path: '/workspace/report.txt', name: 'Report' }, { path: '/workspace/notes.txt' }],
+    });
+  });
+
+  it('preserves literal attachment examples in inline and fenced code', () => {
+    const markup = '<deliver-assets><media path="/workspace/example.txt" /></deliver-assets>';
+    const content = ['Example:', `\`${markup}\``, '```xml', markup, '```'].join('\n');
+    expect(projectAssistantContentForTerminal(content)).toEqual({ text: content, assets: [] });
+  });
+
+  it('projects a completed attachment after an incomplete streaming prefix', () => {
+    const prefix = 'Done.\n<deliver-assets>\n<media type="file" path="/workspace/report';
+    expect(projectAssistantContentForTerminal(prefix).assets).toEqual([]);
+    expect(projectAssistantContentForTerminal(`${prefix}.txt" />\n</deliver-assets>`)).toEqual({
+      text: 'Done.',
+      assets: [{ path: '/workspace/report.txt' }],
+    });
+  });
+});
+
+describe('shared media source compatibility', () => {
+  it.each([
+    ['src="/workspace/preferred.txt" path="/workspace/fallback.txt"', '/workspace/preferred.txt'],
+    ['src=" " path=" /workspace/fallback.txt "', '/workspace/fallback.txt'],
+    ['path="/workspace/a&amp;b.txt"', '/workspace/a&b.txt'],
+  ])('uses src before path and normalizes the source: %s', (attributes, path) => {
+    expect(parseDeliverAssetsContent(`<media type="file" ${attributes} name="Report" />`)).toEqual([
+      { type: 'deliver-assets', items: [{ path, name: 'Report', type: 'file' }] },
+    ]);
+  });
+});

+ 113 - 1
packages/tui/test/unit/tui-engine-local-deltas.test.ts

@@ -83,10 +83,122 @@ describe('MCode Pi Engine local deltas', () => {
     expect(writes).toContain('\x1b[2J\x1b[H');
     expect(writes).not.toContain('\x1b[3J');
     expect(terminal.getScrollBuffer()).toContain('activity-1');
-    expect(terminal.getViewport()).toEqual(['header', 'status', 'composer', '', '']);
+    expect(terminal.getViewport()).toEqual(['composer', '', '', '', '']);
+    expect(terminal.getScrollBuffer().filter((line) => line === 'header')).toHaveLength(1);
     expect(tui.fullRedraws).toBe(2);
   });
 
+  it('does not replay scrolled answer rows after a narrow terminal frame shrinks', async () => {
+    const terminal = new RecordingVirtualTerminal(67, 44);
+    const tui = new TuiMainScreen(terminal);
+    const component = new MutableLines();
+    const answer = Array.from({ length: 80 }, (_, index) => `Answer line ${index}`);
+    component.lines = [...answer, 'activity', `composer${CURSOR_MARKER}`, 'status'];
+    tui.addChild(component);
+    tui.renderNow();
+    await terminal.flush();
+
+    // Settle the activity row, then repaint a historical line (for example Markdown styling).
+    component.lines = [...answer, `composer${CURSOR_MARKER}`, 'status'];
+    tui.renderNow();
+    await terminal.flush();
+    terminal.takeWrites();
+    component.lines[0] = '\x1b[1mAnswer line 0\x1b[0m';
+    tui.renderNow();
+    await terminal.flush();
+
+    expect(terminal.takeWrites()).not.toContain('\x1b[3J');
+    expect(terminal.getScrollBuffer()).toEqual([...answer, 'composer', 'status', '']);
+    expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 41 });
+
+    // A later burst must continue from the same logical/physical boundary.
+    component.lines.splice(80, 0, ...Array.from({ length: 50 }, (_, index) => `More ${index}`));
+    tui.renderNow();
+    await terminal.flush();
+    expect(terminal.getScrollBuffer()).toEqual([
+      ...answer,
+      ...Array.from({ length: 50 }, (_, index) => `More ${index}`),
+      'composer',
+      'status',
+    ]);
+  });
+
+  it('keeps every appended row when a historical row changes in the same frame', async () => {
+    const terminal = new RecordingVirtualTerminal(67, 44);
+    const tui = new TuiMainScreen(terminal);
+    const component = new MutableLines();
+    const answer = Array.from({ length: 80 }, (_, index) => `Answer line ${index}`);
+    component.lines = [...answer, 'composer'];
+    tui.addChild(component);
+    tui.renderNow();
+    await terminal.flush();
+    terminal.takeWrites();
+
+    const more = Array.from({ length: 50 }, (_, index) => `More ${index}`);
+    component.lines = [...answer, ...more, 'composer'];
+    component.lines[0] = '\x1b[1mAnswer line 0\x1b[0m';
+    tui.renderNow();
+    await terminal.flush();
+
+    expect(terminal.takeWrites()).not.toContain('\x1b[3J');
+    expect(terminal.getScrollBuffer()).toEqual([...answer, ...more, 'composer']);
+  });
+
+  it('rebuilds the document when shrinking leaves no rows in the previous viewport', async () => {
+    const terminal = new RecordingVirtualTerminal(67, 44);
+    const tui = new TuiMainScreen(terminal);
+    const component = new MutableLines();
+    component.lines = Array.from({ length: 100 }, (_, index) => `Old line ${index}`);
+    tui.addChild(component);
+    tui.renderNow();
+    await terminal.flush();
+
+    component.lines = ['answer', `composer${CURSOR_MARKER}`];
+    tui.renderNow();
+    await terminal.flush();
+
+    expect(terminal.getScrollBuffer().filter(Boolean)).toEqual(['answer', 'composer']);
+    expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 1 });
+  });
+
+  it('still previews the resized tail and restores ordered scrollback after resize settles', async () => {
+    const terminal = new RecordingVirtualTerminal(67, 44);
+    const tui = new TuiMainScreen(terminal);
+    const component = new MutableLines();
+    component.lines = [
+      ...Array.from({ length: 80 }, (_, index) => `Answer line ${index}`),
+      `composer${CURSOR_MARKER}`,
+    ];
+    tui.addChild(component);
+    try {
+      tui.start();
+      tui.renderNow();
+      await terminal.flush();
+      terminal.takeWrites();
+
+      terminal.resize(60, 30);
+      tui.renderNow();
+      await terminal.flush();
+      expect(terminal.takeWrites()).not.toContain('\x1b[3J');
+      expect(terminal.getViewport()).toEqual([
+        ...Array.from({ length: 29 }, (_, index) => `Answer line ${index + 51}`),
+        'composer',
+      ]);
+
+      await new Promise<void>((resolve) => setTimeout(resolve, 200));
+      tui.renderNow();
+      await terminal.flush();
+      expect(terminal.takeWrites()).toContain('\x1b[3J');
+      expect(terminal.getScrollBuffer()).toEqual([
+        ...Array.from({ length: 80 }, (_, index) => `Answer line ${index}`),
+        'composer',
+      ]);
+      expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 29 });
+    } finally {
+      tui.stop();
+    }
+  });
+
   it('renders an urgent product interaction without resetting Main diff state', async () => {
     const terminal = new RecordingVirtualTerminal(40, 5);
     const tui = new TuiMainScreen(terminal);

+ 22 - 0
packages/tui/test/unit/tui-model-picker.test.ts

@@ -3,6 +3,28 @@ import { describe, expect, it, vi } from "vitest";
 import { TuiModelPicker } from "../../src/tui/features/model/picker.js";
 
 describe("TuiModelPicker", () => {
+  it("selects each declared Kimi K3 effort without inventing a medium level", () => {
+    const onSelect = vi.fn();
+    const model = {
+      providerId: "custom_provider:moonshotai",
+      modelId: "kimi-k3",
+      selected: true,
+      effortOptions: ["low", "high", "max"],
+    };
+    const picker = new TuiModelPicker([model], onSelect, vi.fn());
+    expect(stripAnsi(picker.render(80).join("\n"))).toContain("[ high ]");
+    for (const [key, effort] of [
+      ["\u001b[D", "low"],
+      ["\u001b[C", "high"],
+      ["\u001b[C", "max"],
+    ] as const) {
+      picker.handleInput(key);
+      expect(stripAnsi(picker.render(80).join("\n"))).toContain(`[ ${effort} ]`);
+      picker.handleInput("\r");
+      expect(onSelect).toHaveBeenLastCalledWith(model, effort);
+    }
+  });
+
   it("switches M3 context independently of thinking and restores the saved choice", () => {
     const model = {
       providerId: "minimax",

+ 305 - 0
packages/tui/test/unit/tui-scrollbar-interaction.test.ts

@@ -0,0 +1,305 @@
+import { stripVTControlCharacters } from "node:util";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+  ScrollView,
+  TuiAltScreen,
+  type Component,
+  type TuiMouseEvent,
+  visibleWidth,
+} from "../../src/tui/engine/public.js";
+import { TuiChatLayout } from "../../src/tui/shell/chat-layout.js";
+import { VirtualTerminal } from "../pi-084-upstream/virtual-terminal.js";
+
+const COLUMNS = 20;
+const ROWS = 10;
+const CONTENT_LINES = 60;
+const screens: TuiAltScreen[] = [];
+afterEach(() => {
+  for (const tui of screens.splice(0)) tui.stop();
+});
+
+class ScrollableLines implements Component {
+  private readonly lines: string[] = [];
+
+  constructor(count: number) {
+    for (let index = 0; index < count; index++) {
+      this.lines.push(`line-${String(index).padStart(2, "0")}`);
+    }
+  }
+
+  render(): string[] {
+    return [...this.lines];
+  }
+
+  invalidate(): void {}
+}
+
+function viewportText(terminal: VirtualTerminal): string {
+  return stripVTControlCharacters(terminal.getViewport().join("\n"));
+}
+
+function sgrPress(x: number, y: number): string {
+  return `\x1b[<0;${x + 1};${y + 1}M`;
+}
+
+function sgrMotion(x: number, y: number): string {
+  return `\x1b[<32;${x + 1};${y + 1}M`;
+}
+
+function sgrRelease(x: number, y: number): string {
+  return `\x1b[<0;${x + 1};${y + 1}m`;
+}
+
+async function createScrollbarScreen(
+  options: {
+    columns?: number;
+    gutter?: number;
+    content?: Component;
+    copySelection?: (text: string) => Promise<boolean>;
+  } = {},
+): Promise<{
+  terminal: VirtualTerminal;
+  tui: TuiAltScreen;
+  scrollView: ScrollView;
+}> {
+  const terminal = new VirtualTerminal(options.columns ?? COLUMNS, ROWS);
+  const content = options.content ?? new ScrollableLines(CONTENT_LINES);
+  const scrollView = new ScrollView(content, {
+    primary: true,
+    overscroll: "contain",
+    scrollbar: "always",
+    scrollbarGutter: options.gutter ?? 3,
+  });
+  const tui = new TuiAltScreen(terminal, false, undefined, {
+    copySelection: options.copySelection,
+  });
+  screens.push(tui);
+  tui.setLayoutRoot(scrollView);
+  tui.start();
+  await terminal.waitForRender();
+  return { terminal, tui, scrollView };
+}
+
+describe("Fullscreen scrollbar interaction", () => {
+  it("shows the top of the content before any interaction", async () => {
+    const { terminal } = await createScrollbarScreen();
+    expect(viewportText(terminal)).toContain("line-00");
+    expect(viewportText(terminal)).not.toContain("line-59");
+  });
+
+  it("jumps the thumb to a track press and keeps dragging from there", async () => {
+    const { terminal } = await createScrollbarScreen();
+    // Press the empty track at the bottom of the right-edge scrollbar.
+    terminal.sendInput(sgrPress(COLUMNS - 1, ROWS - 1));
+    await terminal.waitForRender();
+    expect(viewportText(terminal)).toContain("line-59");
+    expect(viewportText(terminal)).not.toContain("line-00");
+    terminal.sendInput(sgrRelease(COLUMNS - 1, ROWS - 1));
+    await terminal.waitForRender();
+  });
+
+  it("grabs near-miss clicks within the widened hit span", async () => {
+    const { terminal } = await createScrollbarScreen();
+    // Press two columns left of the painted one-column bar.
+    terminal.sendInput(sgrPress(COLUMNS - 3, ROWS - 1));
+    await terminal.waitForRender();
+    expect(viewportText(terminal)).toContain("line-59");
+    expect(viewportText(terminal)).not.toContain("line-00");
+    terminal.sendInput(sgrRelease(COLUMNS - 3, ROWS - 1));
+    await terminal.waitForRender();
+  });
+
+  it("keeps an on-thumb press in place and drags proportionally", async () => {
+    const { terminal } = await createScrollbarScreen();
+    // Jump to the end first via a track press at the bottom, then release.
+    terminal.sendInput(sgrPress(COLUMNS - 1, ROWS - 1));
+    await terminal.waitForRender();
+    terminal.sendInput(sgrRelease(COLUMNS - 1, ROWS - 1));
+    await terminal.waitForRender();
+    // The thumb now spans the bottom rows; press it directly.
+    terminal.sendInput(sgrPress(COLUMNS - 1, ROWS - 2));
+    await terminal.waitForRender();
+    // An on-thumb press must not move content on its own.
+    expect(viewportText(terminal)).toContain("line-59");
+    // Drag the thumb up the track.
+    terminal.sendInput(sgrMotion(COLUMNS - 1, Math.floor(ROWS / 2)));
+    await terminal.waitForRender();
+    const text = viewportText(terminal);
+    expect(text).not.toContain("line-59");
+    expect(text).not.toContain("line-00");
+    terminal.sendInput(sgrRelease(COLUMNS - 1, Math.floor(ROWS / 2)));
+    await terminal.waitForRender();
+  });
+
+  it("ignores presses outside the hit span", async () => {
+    const { terminal } = await createScrollbarScreen();
+    // Jump to the end via a track press, then release.
+    terminal.sendInput(sgrPress(COLUMNS - 1, ROWS - 1));
+    await terminal.waitForRender();
+    terminal.sendInput(sgrRelease(COLUMNS - 1, ROWS - 1));
+    await terminal.waitForRender();
+    // Press three columns left of the bar, outside the hit span.
+    terminal.sendInput(sgrPress(COLUMNS - 4, 0));
+    await terminal.waitForRender();
+    terminal.sendInput(sgrRelease(COLUMNS - 4, 0));
+    await terminal.waitForRender();
+    expect(viewportText(terminal)).toContain("line-59");
+  });
+});
+
+describe("Scrollbar interaction boundaries", () => {
+  it.each([1, 3])(
+    "routes the last content columns with a %i-column gutter to content",
+    async (gutter) => {
+      const handleMouse = vi.fn((_event: TuiMouseEvent) => true);
+      const content = {
+        render: (width: number) =>
+          Array.from({ length: CONTENT_LINES }, () => "x".repeat(width)),
+        invalidate() {},
+        handleMouse,
+      };
+      const { terminal, scrollView } = await createScrollbarScreen({
+        gutter,
+        content,
+      });
+      for (const x of [COLUMNS - gutter - 2, COLUMNS - gutter - 1]) {
+        terminal.sendInput(sgrPress(x, ROWS - 1));
+        terminal.sendInput(sgrRelease(x, ROWS - 1));
+        await terminal.waitForRender();
+        expect(handleMouse).toHaveBeenCalledWith(
+          expect.objectContaining({ action: "press", x }),
+        );
+        expect(scrollView.scrollTop).toBe(0);
+      }
+    },
+  );
+
+  it.each([1, 3])(
+    "keeps text selection next to a %i-column gutter",
+    async (gutter) => {
+      const copySelection = vi.fn(async (_text: string) => true);
+      const content = {
+        render: (width: number) =>
+          Array.from(
+            { length: CONTENT_LINES },
+            () => "x".repeat(width - 2) + "YZ",
+          ),
+        invalidate() {},
+      };
+      const { terminal, scrollView } = await createScrollbarScreen({
+        gutter,
+        content,
+        copySelection,
+      });
+      terminal.sendInput(sgrPress(COLUMNS - gutter - 2, 4));
+      terminal.sendInput(sgrMotion(COLUMNS - gutter - 1, 4));
+      terminal.sendInput(sgrRelease(COLUMNS - gutter - 1, 4));
+      await terminal.waitForRender();
+      expect(copySelection).toHaveBeenCalledWith("YZ");
+      expect(scrollView.scrollTop).toBe(0);
+    },
+  );
+
+  it.each([1, 2, 3, 4, 8])(
+    "preserves content and bounded mouse targets at width %i",
+    async (columns) => {
+      const widths: number[] = [];
+      const handleMouse = vi.fn(() => true);
+      const content = {
+        render: (width: number) => {
+          widths.push(width);
+          return Array.from({ length: CONTENT_LINES }, () => "x".repeat(width));
+        },
+        invalidate() {},
+        handleMouse,
+      };
+      const { terminal, scrollView } = await createScrollbarScreen({
+        columns,
+        content,
+      });
+      expect(widths.every((width) => width === Math.max(1, columns - 3))).toBe(
+        true,
+      );
+      expect(
+        terminal.getViewport().every((line) => visibleWidth(line) <= columns),
+      ).toBe(true);
+      terminal.sendInput(sgrPress(0, ROWS - 1));
+      terminal.sendInput(sgrRelease(0, ROWS - 1));
+      await terminal.waitForRender();
+      expect(handleMouse).toHaveBeenCalled();
+      expect(scrollView.scrollTop).toBe(0);
+      if (columns > 1) {
+        terminal.sendInput(sgrPress(columns - 1, ROWS - 1));
+        await terminal.waitForRender();
+        expect(scrollView.scrollTop).toBe(CONTENT_LINES - ROWS);
+      }
+    },
+  );
+
+  it("does not capture a track press while an overlay is visible", async () => {
+    const { terminal, tui, scrollView } = await createScrollbarScreen();
+    tui.showOverlay(new ScrollableLines(2), { width: 10 });
+    await terminal.waitForRender();
+    terminal.sendInput(sgrPress(COLUMNS - 1, ROWS - 1));
+    terminal.sendInput(sgrRelease(COLUMNS - 1, ROWS - 1));
+    await terminal.waitForRender();
+    expect(scrollView.scrollTop).toBe(0);
+  });
+
+  it("cancels a drag when an overlay opens and does not resume it after dismissal", async () => {
+    const { terminal, tui, scrollView } = await createScrollbarScreen();
+    terminal.sendInput(sgrPress(COLUMNS - 1, 0));
+    const overlay = tui.showOverlay(new ScrollableLines(2), { width: 10 });
+    await terminal.waitForRender();
+    terminal.sendInput(sgrMotion(COLUMNS - 1, ROWS - 1));
+    await terminal.waitForRender();
+    expect(scrollView.scrollTop).toBe(0);
+    overlay.hide();
+    await terminal.waitForRender();
+    terminal.sendInput(sgrMotion(COLUMNS - 1, ROWS - 1));
+    terminal.sendInput(sgrRelease(COLUMNS - 1, ROWS - 1));
+    await terminal.waitForRender();
+    expect(scrollView.scrollTop).toBe(0);
+  });
+
+  it("routes wheel events normally and ends dragging on release", async () => {
+    const { terminal, scrollView } = await createScrollbarScreen();
+    terminal.sendInput(`\x1b[<65;${COLUMNS};5M`);
+    await terminal.waitForRender();
+    expect(scrollView.scrollTop).toBeGreaterThan(0);
+    terminal.sendInput(sgrPress(COLUMNS - 1, ROWS - 1));
+    terminal.sendInput(sgrRelease(COLUMNS - 1, ROWS - 1));
+    await terminal.waitForRender();
+    terminal.sendInput(sgrMotion(COLUMNS - 1, 0));
+    await terminal.waitForRender();
+    expect(scrollView.scrollTop).toBe(CONTENT_LINES - ROWS);
+  });
+
+  it("enables a reserved gutter in the actual fullscreen chat layout", async () => {
+    const terminal = new VirtualTerminal(40, 15);
+    const empty = { render: () => [], invalidate() {} };
+    const layout = new TuiChatLayout(terminal, {
+      surface: () => "conversation",
+      transcript: new ScrollableLines(CONTENT_LINES),
+      welcome: empty,
+      interaction: { ...empty, isActive: () => false },
+      activity: empty,
+      followUp: empty,
+      composer: { render: () => ["composer"], invalidate() {} },
+      status: empty,
+    });
+    const tui = new TuiAltScreen(terminal);
+    screens.push(tui);
+    tui.setLayoutRoot(layout.fullscreenLayoutRoot);
+    tui.start();
+    await terminal.waitForRender();
+    expect(viewportText(terminal)).toContain("line-59");
+    terminal.sendInput(sgrPress(37, 0));
+    terminal.sendInput(sgrRelease(37, 0));
+    await terminal.waitForRender();
+    expect(viewportText(terminal)).toContain("line-00");
+    expect(viewportText(terminal)).not.toContain("line-59");
+    expect(viewportText(terminal)).toContain("composer");
+  });
+});

+ 191 - 0
packages/tui/test/unit/tui-status-line-items.test.ts

@@ -1,5 +1,7 @@
 import { afterEach, describe, expect, it } from 'vitest';
 
+import { applyTuiRenderTheme, getTuiThemeSnapshot, tuiChalk, tuiColors } from '../../src/tui/theme/runtime.js';
+import { MINIMAX_CODE_DARK_THEME, MINIMAX_CODE_LIGHT_THEME } from '../../src/tui/theme/palettes.js';
 import { TuiStatusLine } from '../../src/tui/shell/chrome.js';
 import { stripAnsi, visibleWidth } from '../../src/tui/rendering/text.js';
 import { setCapabilityOverrides } from '../../src/tui/engine/public.js';
@@ -582,3 +584,192 @@ describe('review link status item', () => {
     expect(narrow).toContain('!312');
   });
 });
+
+describe('context meter item', () => {
+  it('resolves the canonical id and its aliases', () => {
+    expect(parseTuiStatusLineItem('context-meter')).toBe('context-meter');
+    expect(parseTuiStatusLineItem('context-bar')).toBe('context-meter');
+    expect(parseTuiStatusLineItem('context-gauge')).toBe('context-meter');
+  });
+
+  it('stays out of the default status line', () => {
+    expect(TUI_STATUS_LINE_DEFAULT_ITEMS).toEqual([
+      'current-dir', 'session-title', 'git-branch', 'review-link', 'plan-mode',
+      'approval-mode', 'model-with-reasoning', 'context-window', 'subagent',
+      'token-quota', 'context-remaining',
+    ]);
+    const state = {
+      ...BASE_STATE,
+      contextUsage: { usedTokens: 20_000, contextWindowTokens: 100_000 },
+    };
+    expect(stripAnsi(render(state))).not.toContain('▕');
+  });
+
+  it('renders the remaining-headroom gauge when configured explicitly', () => {
+    const state = {
+      ...BASE_STATE,
+      statusLineItems: ['context-meter'],
+      contextUsage: { usedTokens: 20_000, contextWindowTokens: 100_000 },
+    };
+    expect(stripAnsi(render(state))).toContain('Context ▕██████░░▏ 80% left');
+  });
+
+  it('drains the gauge with the remaining headroom', () => {
+    const state = {
+      ...BASE_STATE,
+      statusLineItems: ['context-meter'],
+      contextUsage: { usedTokens: 50_000, contextWindowTokens: 100_000 },
+    };
+    expect(stripAnsi(render(state))).toContain('▕████░░░░▏ 50% left');
+  });
+
+  it('shrinks to a shorter gauge in narrow terminals', () => {
+    const state = {
+      ...BASE_STATE,
+      statusLineItems: ['context-meter'],
+      contextUsage: { usedTokens: 50_000, contextWindowTokens: 100_000 },
+    };
+    const narrow = stripAnsi(render(state, 20));
+    expect(narrow).toContain('Ctx');
+    expect(narrow).toContain('50%');
+    expect(narrow).not.toContain('left');
+    expect(narrow).not.toContain('▕████░░░░▏');
+  });
+
+  it('is hidden without usage and never shows NaN', () => {
+    expect(render({ ...BASE_STATE, statusLineItems: ['context-meter'], contextWindowTokens: 100_000 })).toBe('');
+    expect(
+      stripAnsi(
+        render({
+          ...BASE_STATE,
+          statusLineItems: ['context-meter'],
+          contextUsage: { usedTokens: Number.NaN, contextWindowTokens: 100_000 },
+        }),
+      ),
+    ).not.toContain('NaN');
+  });
+});
+
+describe('context meter presentation contract', () => {
+  it.each([
+    ['context-remaining', 'model', 'context-bar', 'context-gauge'],
+    ['context-gauge', 'model', 'context-left'],
+  ])('prefers the meter at its configured position for %j', (...configured) => {
+    const statusLineItems = parseTuiStatusLineItems(configured);
+    const line = stripAnsi(render({
+      ...BASE_STATE,
+      statusLineItems,
+      contextUsage: { usedTokens: 50_000, contextWindowTokens: 100_000 },
+    }));
+    expect(line.match(/50%/gu)).toHaveLength(1);
+    expect(line).toContain('Context ▕████░░░░▏ 50% left');
+    expect(line.indexOf('Context') < line.indexOf('m2')).toBe(configured[0] === 'context-gauge');
+  });
+});
+
+describe('context meter boundaries', () => {
+  it.each([
+    [undefined, 100_000, 50],
+    [200_000, 100_000, 75],
+    [Number.NaN, 100_000, 50],
+    [0, 100_000, 50],
+    [-1, 100_000, 50],
+    [Number.POSITIVE_INFINITY, 100_000, 50],
+  ])('resolves snapshot window %s before model window %s', (snapshot, model, remaining) => {
+    for (const item of ['context-meter', 'context-remaining'] as const) {
+      const line = stripAnsi(render({
+        ...BASE_STATE,
+        statusLineItems: [item],
+        contextWindowTokens: model,
+        contextUsage: { usedTokens: 50_000, contextWindowTokens: snapshot },
+      }));
+      expect(line).toContain(`${remaining}% left`);
+    }
+  });
+
+  it.each([undefined, 0, -1, Number.NaN, Number.POSITIVE_INFINITY])(
+    'hides the meter when neither window is usable (%s)', (window) => {
+      expect(render({
+        ...BASE_STATE,
+        statusLineItems: ['context-meter'],
+        contextWindowTokens: window,
+        contextUsage: { usedTokens: 1, contextWindowTokens: window },
+      })).toBe('');
+    },
+  );
+
+  it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])(
+    'hides invalid usage %s even with valid model capacity', (usedTokens) => {
+      expect(render({
+        ...BASE_STATE,
+        statusLineItems: ['context-meter'],
+        contextWindowTokens: 100_000,
+        contextUsage: { usedTokens },
+      })).toBe('');
+    },
+  );
+
+  it.each([
+    [-1, '▕████████▏ 100% left'],
+    [0, '▕████████▏ 100% left'],
+    [100, '▕░░░░░░░░▏ 0% left'],
+    [150, '▕░░░░░░░░▏ 0% left'],
+  ])('clamps used tokens %d to a valid gauge', (usedTokens, expected) => {
+    expect(stripAnsi(render({
+      ...BASE_STATE,
+      statusLineItems: ['context-meter'],
+      contextUsage: { usedTokens, contextWindowTokens: 100 },
+    }))).toContain(expected);
+  });
+
+  it.each([
+    [30, 'Context ▕████░░░░▏ 50% left'],
+    [20, 'Ctx ▕███░░░▏ 50%'],
+    [7, 'Ctx 50%'],
+    [6, ''],
+  ])('fits a width of %d with the expected presentation', (width, expected) => {
+    const line = render({
+      ...BASE_STATE,
+      statusLineItems: ['context-meter'],
+      contextUsage: { usedTokens: 50, contextWindowTokens: 100 },
+    }, width);
+    expect(stripAnsi(line).trim()).toBe(expected);
+    expect(line.split('\n').every((row) => visibleWidth(row) <= width)).toBe(true);
+  });
+
+  it('uses the same warning and error boundaries as the percentage item', () => {
+    const previous = getTuiThemeSnapshot();
+    applyTuiRenderTheme(MINIMAX_CODE_DARK_THEME, 3);
+    try {
+      for (const [remaining, color] of [
+        [26, tuiColors.muted], [25, tuiColors.warning],
+        [11, tuiColors.warning], [10, tuiColors.error], [0, tuiColors.error],
+      ] as const) {
+        for (const item of ['context-meter', 'context-remaining'] as const) {
+          const line = render({
+            ...BASE_STATE,
+            statusLineItems: [item],
+            contextUsage: { usedTokens: 100 - remaining, contextWindowTokens: 100 },
+          }).trim();
+          expect(line).not.toBe(stripAnsi(line));
+          expect(line).toBe(tuiChalk.hex(color)(stripAnsi(line)));
+        }
+      }
+    } finally {
+      applyTuiRenderTheme(
+        previous.appearance === 'light' ? MINIMAX_CODE_LIGHT_THEME : MINIMAX_CODE_DARK_THEME,
+        previous.colorLevel,
+      );
+    }
+  });
+
+  it('keeps build-mode in control when the meter is selected', () => {
+    const line = stripAnsi(render({
+      ...BASE_STATE,
+      statusLineItems: ['context-meter', 'build-mode', 'context-remaining'],
+      contextUsage: { usedTokens: 50, contextWindowTokens: 100 },
+    }));
+    expect(line).toContain('[V]');
+    expect(line).not.toContain('Context');
+  });
+});

+ 2 - 2
packages/tui/test/unit/tui-transcript-view.test.ts

@@ -332,7 +332,7 @@ describe('TranscriptView', () => {
     expect(updated.join('\n')).toContain('Updated answer');
   });
 
-  it('renders rich delivery markup as a compact terminal file receipt', () => {
+  it.each(['src', 'path'])('renders %s delivery markup as a compact terminal file receipt', (attribute) => {
     const view = new TranscriptView(() => [
       createTranscriptCell({
         id: 'assistant-assets',
@@ -341,7 +341,7 @@ describe('TranscriptView', () => {
         content: [
           'Done.',
           '<deliver-assets>',
-          '<media src="/workspace/chart.png" caption="Chart" />',
+          `<media ${attribute}="/workspace/chart.png" caption="Chart" />`,
           '</deliver-assets>',
         ].join('\n'),
         createdAtMs: 1,

+ 29 - 0
packages/tui/test/unit/tui-workspace-status-line.test.ts

@@ -508,3 +508,32 @@ describe('TuiWorkspaceStatusLine custom status command', () => {
     expect(runProcess).toHaveBeenCalledTimes(1);
   });
 });
+
+
+describe('context meter projection', () => {
+  it('previews and refreshes current usage without retaining cleared data', () => {
+    const runtime = { getWorkspaceGitMetadata: vi.fn() };
+    const state = {
+      version: '0.1', workspace: '/repo', runtimeStatus: 'ready' as const,
+      statusLineItems: ['context-meter', 'context-remaining'] as const,
+      contextWindowTokens: 100,
+    };
+    const status = new TuiWorkspaceStatusLine(state, runtime, vi.fn());
+    try {
+      expect(status.preview(['context-meter'], 80, 3).unavailable).toEqual(['context-meter']);
+      expect(status.render(80)).toEqual([]);
+      status.setState({ ...state, contextUsage: { usedTokens: 20 } });
+      const preview = status.preview(['context-meter', 'context-remaining'], 80, 3);
+      expect(preview.unavailable).toEqual([]);
+      expect(preview.lines.join('')).toContain('▕██████░░▏ 80% left');
+      expect(status.render(80).join('').match(/80%/gu)).toHaveLength(1);
+      status.setState({ ...state, contextUsage: { usedTokens: 90 } });
+      expect(status.render(80).join('')).toContain('▕█░░░░░░░▏ 10% left');
+      status.setState(state);
+      expect(status.render(80)).toEqual([]);
+      expect(runtime.getWorkspaceGitMetadata).not.toHaveBeenCalled();
+    } finally {
+      status.dispose();
+    }
+  });
+});

+ 14 - 1
packages/tui/test/unit/tui/controller/product/command-flow.test.ts

@@ -37,6 +37,7 @@ function createReadinessCommandFlow(options: {
   };
   persistTuiMode?: (mode: "regular" | "fullscreen") => void;
   reloadTui?: () => Promise<void>;
+  append?: (text: string, kind?: "info" | "warning" | "error") => void;
   queuedCount?: number;
 }) {
   return new TuiCommandFlow({
@@ -86,7 +87,7 @@ function createReadinessCommandFlow(options: {
     ...(options.whenControllerReady
       ? { whenControllerReady: options.whenControllerReady }
       : {}),
-    append: vi.fn(),
+    append: options.append ?? vi.fn(),
     setHint: options.setHint ?? vi.fn(),
     onChanged: vi.fn(),
   });
@@ -347,6 +348,18 @@ describe("TuiCommandFlow", () => {
     expect(setHint).toHaveBeenLastCalledWith("TUI configuration reloaded.");
   });
 
+  it.each(['Plugin refresh failed', 'Invalid keybindings.json'])("preserves /reload cause: %s", async (message) => {
+    const append = vi.fn();
+    const flow = createReadinessCommandFlow({
+      whenReady: async () => {}, append,
+      reloadTui: async () => { throw new Error(message); },
+    });
+    await expect(flow.submit('/reload')).resolves.toBe('consumed');
+    expect(append).toHaveBeenCalledWith(expect.stringContaining(message), 'warning');
+    expect(append).toHaveBeenCalledWith(expect.stringContaining('configuration or plugin refresh error'), 'warning');
+    expect(JSON.stringify(append.mock.calls)).not.toContain('Fix keybindings.json');
+  });
+
   it("retains /reload while queued work is present", async () => {
     const reloadTui = vi.fn(async () => undefined);
     const setHint = vi.fn();

+ 17 - 0
packages/tui/test/unit/tui/features/settings/status-line-picker.test.ts

@@ -145,3 +145,20 @@ describe('status line picker', () => {
     expect(picker.render(120).join('\n')).not.toContain('0%');
   });
 });
+
+
+describe('context meter settings', () => {
+  it.each([
+    ['en', 'Remaining context gauge'],
+    ['zh-Hans', '剩余上下文刻度条'],
+  ])('describes and saves the opt-in item in %s', async (locale, description) => {
+    const { picker, options } = fixture({ locale });
+    picker.handleInput('context-meter');
+    expect(picker.render(100).join('\n')).toContain(description);
+    expect(picker.render(100).join('\n')).toContain('[ ] context-meter');
+    picker.handleInput(' ');
+    picker.handleInput('\r');
+    await vi.waitFor(() => expect(options.onClose).toHaveBeenCalledOnce());
+    expect(options.save).toHaveBeenCalledWith(['model', 'current-dir', 'context-meter']);
+  });
+});

+ 5 - 0
release/public-source.json

@@ -19,6 +19,7 @@
     ".github/dependabot.yml",
     ".github/workflows/ci.yml",
     ".github/workflows/compatibility.yml",
+    ".github/workflows/label-issue-product.yml",
     ".github/workflows/security.yml",
     ".github/workflows/source-candidate.yml",
     ".github/workflows/sync-issue-to-feishu.yml",
@@ -2236,6 +2237,7 @@
     "packages/local-runtime/src/content-safety/api-v2.ts",
     "packages/local-runtime/src/content-safety/api.ts",
     "packages/local-runtime/src/content-safety/config-fields.ts",
+    "packages/local-runtime/src/content-safety/diagnostics.ts",
     "packages/local-runtime/src/content-safety/turn-api.ts",
     "packages/local-runtime/src/context/context-usage-calibration.ts",
     "packages/local-runtime/src/context/context-usage-provider-diagnostics.ts",
@@ -3214,6 +3216,7 @@
     "packages/tui/test/unit/incident-reporter-privacy.test.ts",
     "packages/tui/test/unit/mcode-tools-integration.test.ts",
     "packages/tui/test/unit/model-effort.test.ts",
+    "packages/tui/test/unit/network-proxy.test.ts",
     "packages/tui/test/unit/plugin-application.test.ts",
     "packages/tui/test/unit/provider-application.test.ts",
     "packages/tui/test/unit/run-coordinator-usage.test.ts",
@@ -3225,6 +3228,7 @@
     "packages/tui/test/unit/runtime-product-access.test.ts",
     "packages/tui/test/unit/tui-activity-line.test.ts",
     "packages/tui/test/unit/tui-app.test.ts",
+    "packages/tui/test/unit/tui-assistant-content.test.ts",
     "packages/tui/test/unit/tui-background-work-panel.test.ts",
     "packages/tui/test/unit/tui-build-mode-contract.test.ts",
     "packages/tui/test/unit/tui-capability-inspection.test.ts",
@@ -3243,6 +3247,7 @@
     "packages/tui/test/unit/tui-provider-manager.test.ts",
     "packages/tui/test/unit/tui-provider-onboarding.test.ts",
     "packages/tui/test/unit/tui-runtime-adapter.test.ts",
+    "packages/tui/test/unit/tui-scrollbar-interaction.test.ts",
     "packages/tui/test/unit/tui-session-manager.test.ts",
     "packages/tui/test/unit/tui-shell-block.test.ts",
     "packages/tui/test/unit/tui-status-line-items.test.ts",

+ 7 - 5
scripts/source-candidate.mjs

@@ -53,12 +53,14 @@ if (command === "unpack") {
         ),
       ),
     );
+  // Windows validation is temporarily paused in the candidate workflow.
+  const requiredPlatforms = ["linux", "darwin"];
   if (
-    reports.length !== 3 ||
-    new Set(reports.map((r) => r.platform)).size !== 3 ||
+    reports.length !== requiredPlatforms.length ||
+    new Set(reports.map((r) => r.platform)).size !== requiredPlatforms.length ||
     reports.some(
       (r) =>
-        !["linux", "darwin", "win32"].includes(r.platform) ||
+        !requiredPlatforms.includes(r.platform) ||
         r.status !== "PASS" ||
         r.profile !== "archive" ||
         r.revision !== receipt.revision ||
@@ -67,7 +69,7 @@ if (command === "unpack") {
     )
   )
     throw new Error(
-      "Candidate requires successful same-revision archive reports from all three platforms",
+      "Candidate requires successful same-revision archive reports from Linux and macOS",
     );
   const manifest = {
     schemaVersion: 1,
@@ -88,6 +90,6 @@ if (command === "unpack") {
   );
   writeFileSync(`${archive}.sha256`, `${digest}  ${path.basename(archive)}\n`);
   console.log(
-    `Source candidate verified on all three platforms: ${receipt.revision}`,
+    `Source candidate verified on Linux and macOS: ${receipt.revision}`,
   );
 }

+ 72 - 1
test/byok.test.mjs

@@ -14,7 +14,7 @@ import { tmpdir } from "node:os";
 import path from "node:path";
 import { fileURLToPath } from "node:url";
 import Database from "better-sqlite3";
-import { parse as parseYaml } from "yaml";
+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
 import { withoutProxyEnvironment } from "./offline-environment.mjs";
 
 const cli = fileURLToPath(new URL("../dist/cli.js", import.meta.url));
@@ -298,6 +298,7 @@ test(
       "provider", "add", "--name", "Limited", "--base-url", baseUrl,
       "--api-format", "openai-completions", "--model", "fixture-model",
       "--model", "second-model", "--context-limit", "32768", "--output-limit", "4096", "--use",
+      "--support-image",
     ];
     const beforeFailure = readFileSync(configPath, "utf8");
     rejectConnection = true;
@@ -312,6 +313,7 @@ test(
     assert.equal(config.defaultModel, "custom_provider:limited/fixture-model");
     for (const model of ["fixture-model", "second-model"]) {
       assert.deepEqual(config.custom_provider.limited.models[model].limit, { context: 32768, output: 4096 });
+      assert.deepEqual(config.custom_provider.limited.models[model].capabilities, { support_image: true });
     }
     const configured = JSON.parse(await run(["provider", "list", "--json"])).providers.find(
       (provider) => provider.name === "Limited",
@@ -330,11 +332,80 @@ test(
       await run([
         "provider", "add", "--name", name, "--base-url", baseUrl,
         "--api-format", "openai-completions", "--model", "fixture-model", flag, "32768",
+        "--support-image",
       ]);
       assert.deepEqual(savedConfig().custom_provider[name].models["fixture-model"].limit, limit);
+      assert.deepEqual(savedConfig().custom_provider[name].models["fixture-model"].capabilities, { support_image: true });
       assert.equal(savedConfig().defaultModel, config.defaultModel);
     }
     assert.equal(requests.length, beforeSaveOnly, "Limits alone must not test or select a model");
+    // Exercise the metadata persisted by provider preset import through real
+    // config reload, headless validation and the OpenAI-compatible request body.
+    const effortConfig = savedConfig();
+    effortConfig.custom_provider.fixture.models["kimi-k3"] = {
+      reasoning: true,
+      thinking: { effortOptions: ["low", "high", "max"] },
+    };
+    effortConfig.custom_provider.fixture.models["vision-modalities"] = {
+      modalities: { input: ["text", "image"], output: ["text"] },
+    };
+    effortConfig.custom_provider.fixture.models["attachment-only"] = { attachment: true };
+    writeFileSync(configPath, stringifyYaml(effortConfig));
+    // The packaged command must carry the declaration through saving, a fresh
+    // process/config reload, attachment preparation and SDK serialization.
+    const imageBase64 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGUlEQVR4nGP4n8LwnxLMMGrAqAGjBgwXAwCOqWIfmQV0zAAAAABJRU5ErkJggg==";
+    const imagePath = path.join(workspaceDir, "fixture.png");
+    writeFileSync(imagePath, Buffer.from(imageBase64, "base64"));
+    for (const [model, supportsImage] of [
+      ["custom_provider:limited/fixture-model", true],
+      ["custom_provider:context-only/fixture-model", true],
+      ["custom_provider:fixture/vision-modalities", true],
+      ["custom_provider:fixture/fixture-model", false],
+      ["custom_provider:fixture/attachment-only", false],
+    ]) {
+      const beforeImage = requests.length;
+      await run(["exec", "IMAGE_INPUT_TEST", "--model", model, "--file", imagePath,
+        "--timeout", "20s", "--max-steps", "1"]);
+      const turns = requests.slice(beforeImage).filter((r) => r.body.stream === true);
+      assert.ok(turns.length > 0, `Expected a runtime request for ${model}`);
+      for (const { body } of turns) {
+        const images = body.messages.flatMap((message) =>
+          Array.isArray(message.content)
+            ? message.content.filter((part) => part.type === "image_url")
+            : []);
+        if (supportsImage) {
+          assert.equal(images.length, 1, `Expected an inline image for ${model}`);
+          // PNG inputs are transcoded to JPEG by the real attachment pipeline.
+          const url = images[0].image_url.url;
+          assert.match(url, /^data:image\/jpeg;base64,/);
+          const bytes = Buffer.from(url.split(",")[1], "base64");
+          assert.deepEqual([...bytes.subarray(0, 3)], [0xff, 0xd8, 0xff]);
+          assert.deepEqual([...bytes.subarray(-2)], [0xff, 0xd9]);
+          assert.doesNotMatch(JSON.stringify(body.messages), /current model cannot read this image inline/);
+        } else {
+          assert.deepEqual(images, [], `${model} must remain text-only`);
+          assert.match(JSON.stringify(body.messages), /current model cannot read this image inline/);
+        }
+      }
+    }
+    const effortModel = `${selected.providerId}/kimi-k3`;
+    for (const effort of ["low", "high", "max"]) {
+      const beforeEffort = requests.length;
+      await run(["exec", "EFFORT_TEST", "--model", effortModel, "--effort", effort,
+        "--timeout", "20s", "--max-steps", "1"]);
+      // Background title generation is a separate non-streaming request and
+      // does not use the turn's effort selection.
+      const modelRequests = requests.slice(beforeEffort).filter(
+        (r) => r.body.model === "kimi-k3" && r.body.stream === true,
+      );
+      assert.ok(modelRequests.length > 0);
+      for (const request of modelRequests) assert.equal(request.body.reasoning_effort, effort);
+    }
+    const beforeInvalidEffort = requests.length;
+    await assert.rejects(run(["exec", "EFFORT_TEST", "--model", effortModel,
+      "--effort", "medium", "--timeout", "20s", "--max-steps", "1"]),
+    /Available levels: low, high, max/);
+    assert.equal(requests.length, beforeInvalidEffort, "Invalid effort must fail before transport");
     const modelArgs = ["--model", `${selected.providerId}/fixture-model`];
     // The first run must work through the saved default, without --model or managed login.
     const first = await run([

+ 36 - 20
test/smoke.test.mjs

@@ -6,6 +6,7 @@ import { tmpdir } from "node:os";
 import path from "node:path";
 import { fileURLToPath } from "node:url";
 import Database from "better-sqlite3";
+import { parse as parseYaml } from "yaml";
 import { withoutProxyEnvironment } from "./offline-environment.mjs";
 
 const root = fileURLToPath(new URL("../", import.meta.url));
@@ -167,18 +168,22 @@ test("offline smoke children ignore ambient proxy variables", async (t) => {
     "HTTP_PROXY",
     "HTTPS_PROXY",
     "ALL_PROXY",
+    "NO_PROXY",
     "http_proxy",
     "https_proxy",
     "all_proxy",
+    "no_proxy",
   ];
   for (const name of proxyNames) {
     await t.test(name, (t) => {
-      const environment = {
+      const proxyValue = name.toLowerCase() === "no_proxy" ? "*" : "http://127.0.0.1:9";
+      const environment = Object.freeze({
         ...process.env,
         ...Object.fromEntries(proxyNames.map((key) => [key, ""])),
-        [name]: "http://127.0.0.1:9",
-      };
+        [name]: proxyValue,
+      });
       const options = fixture(t, environment);
+      for (const key of proxyNames) assert.equal(options.env[key], "");
       const result = spawnSync(process.execPath, [cli, "provider", "list"], {
         ...options,
         encoding: "utf8",
@@ -186,11 +191,8 @@ test("offline smoke children ignore ambient proxy variables", async (t) => {
       });
       assertSuccessfulChild(result);
       assert.match(result.stdout, /minimax/);
-      assert.match(
-        readFileSync(options.env.MCODE_TEST_NETWORK_AUDIT + ".managed", "utf8"),
-        /https:\/\/models\.dev\/api\.json|\/mavis\/api\/v1\/models-dev\/catalog/,
-      );
-      assert.equal(environment[name], "http://127.0.0.1:9");
+      // Catalog requests are optional; the fixture still rejects any real network access.
+      assert.equal(environment[name], proxyValue);
     });
   }
 });
@@ -327,21 +329,35 @@ test("local plugin browsing remains available with managed services offline", (t
   }
 });
 
-test("provider add validates token limits before opening the runtime", (t) => {
-  const options = fixture(t);
+test("provider add rejects invalid token limits without saving a provider", async (t) => {
   const args = [
     "provider", "add", "--name", "Invalid limits", "--base-url", "http://127.0.0.1:1/v1",
     "--model", "synthetic-model",
   ];
-  for (const flag of ["--context-limit", "--output-limit"]) {
-    for (const value of ["0", "-1", "1.5", "NaN", "Infinity", "9007199254740992"]) {
-      const result = spawnSync(process.execPath, [cli, ...args, `${flag}=${value}`], {
-        ...options, encoding: "utf8", timeout: 15000,
-      });
-      assert.equal(result.status, 1, result.stderr);
-      assert.match(result.stderr, /positive safe integer/);
-      assert.ok(result.stderr.includes(flag), result.stderr);
-    }
+  for (const seeded of [false, true]) {
+    await t.test(seeded ? "default config already exists" : "fresh data directory", (t) => {
+      const options = fixture(t);
+      // Keep data separate from cwd so assertions must use the CLI's config location.
+      const dataDir = path.join(options.cwd, "data");
+      mkdirSync(dataDir);
+      options.env.MINIMAX_DATA_DIR = dataDir;
+      options.env.MAVIS_DATA_DIR = dataDir;
+      const configPath = path.join(dataDir, "config.yaml");
+      if (seeded) writeFileSync(configPath, "logLevel: info\ndefaultModel: minimax/MiniMax-M3\n", { mode: 0o600 });
+      for (const flag of ["--context-limit", "--output-limit"]) {
+        for (const value of ["0", "-1", "1.5", "NaN", "Infinity", "9007199254740992"]) {
+          const result = spawnSync(process.execPath, [cli, ...args, `${flag}=${value}`], {
+            ...options, encoding: "utf8", timeout: 15000,
+          });
+          assert.equal(result.error, undefined, result.stderr);
+          assert.equal(result.status, 1, result.stderr);
+          assert.match(result.stderr, /positive safe integer/);
+          assert.ok(result.stderr.includes(flag), result.stderr);
+          // Startup may seed defaults; only persisting a custom provider is a failure.
+          const config = existsSync(configPath) ? parseYaml(readFileSync(configPath, "utf8")) : {};
+          assert.deepEqual(config?.custom_provider ?? {}, {});
+        }
+      }
+    });
   }
-  assert.equal(existsSync(path.join(options.cwd, "config.yaml")), false);
 });

+ 84 - 13
test/source-sync.test.mjs

@@ -14,6 +14,7 @@ import { gzipSync } from 'node:zlib';
 import { createHash } from 'node:crypto';
 import { fileURLToPath } from 'node:url';
 import { parse as parseYaml } from 'yaml';
+import { runInNewContext } from 'node:vm';
 
 function fixture(t) {
   const home = mkdtempSync(path.join(tmpdir(), 'source-sync-'));
@@ -230,13 +231,13 @@ test('CI aggregate rejects failed, cancelled, missing and unexpectedly skipped c
     assert.notEqual(run({ ...full, DOCS_ONLY: scope }), 0);
 });
 
-test('ordinary CI preserves three platforms without invoking release-only matrices', () => {
+test('ordinary CI pauses Windows without invoking release-only matrices', () => {
   const readWorkflow = name => parseYaml(readFileSync(new URL(`../.github/workflows/${name}.yml`, import.meta.url), 'utf8'));
   const ci = readWorkflow('ci');
   assert.ok(Object.hasOwn(ci.on, 'pull_request'));
   assert.deepEqual(ci.on.push.branches, ['main']);
   assert.deepEqual(Object.keys(ci.jobs).sort(), ['changes', 'docs', 'verification', 'verify']);
-  assert.deepEqual(ci.jobs.verify.strategy.matrix.os, ['ubuntu-latest', 'macos-latest', 'windows-latest']);
+  assert.deepEqual(ci.jobs.verify.strategy.matrix.os, ['ubuntu-latest', 'macos-latest']);
   assert.deepEqual(ci.jobs.verify.strategy.matrix.node, ['24']);
   assert.deepEqual(ci.jobs.verify.strategy.matrix.include, [{ os: 'ubuntu-latest', node: '24', profile: 'full' }]);
   assert.equal(ci.jobs.verify.needs, 'changes');
@@ -269,7 +270,7 @@ test('manual source candidates pin every checkout and receipt to the selected re
       assert.equal(step.env.REVISION, revision);
   }
   const validate = workflow.jobs.validate;
-  assert.deepEqual(validate.strategy.matrix.os, ['ubuntu-latest', 'macos-latest', 'windows-latest']);
+  assert.deepEqual(validate.strategy.matrix.os, ['ubuntu-latest', 'macos-latest']);
   assert.ok(validate.steps.some(step => step.run?.includes('--store-dir "$RUNNER_TEMP/candidate-store" --registry https://registry.npmjs.org/')));
   const verify = validate.steps.find(step => step.run === 'pnpm verify --profile archive');
   assert.equal(verify.env.MCODE_VERIFY_REVISION, revision);
@@ -345,7 +346,7 @@ test('source archive rejects traversal, links, Git history and duplicate entries
   }
 });
 
-test('candidate rejects mismatched receipts and requires three successful same-revision reports', t => {
+test('candidate rejects mismatched receipts and requires successful same-revision Linux and macOS reports', t => {
   const f = archiveFixture(t, [{ path: 'minimax-code/README.md', content: 'source' }]);
   const revision = 'a'.repeat(40);
   const receipt = { schemaVersion: 1, revision, sha256: createHash('sha256').update(readFileSync(f.archive)).digest('hex'), format: 'source-only-no-git-history', publicationPerformed: false };
@@ -361,20 +362,22 @@ test('candidate rejects mismatched receipts and requires three successful same-r
   writeFileSync(`${f.archive}.json`, JSON.stringify(receipt));
   const reports = path.join(f.directory, 'reports');
   mkdirSync(reports);
-  for (const platform of ['linux', 'darwin', 'win32']) {
+  for (const platform of ['linux', 'darwin']) {
     const folder = path.join(reports, platform);
     mkdirSync(folder);
     writeFileSync(path.join(folder, 'verification.json'), JSON.stringify({ revision, platform, arch: 'fixture', node: 'v24', profile: 'archive', status: 'PASS', gates: [{ name: 'build', status: 'PASS' }] }));
   }
   assert.equal(run('finalize', '--reports', reports).status, 0);
-  assert.equal(JSON.parse(readFileSync(path.join(f.directory, 'candidate.json'))).sha256, receipt.sha256);
-  const windows = path.join(reports, 'win32/verification.json');
-  const report = JSON.parse(readFileSync(windows));
-  for (const change of [{ status: 'FAIL' }, { revision: 'b'.repeat(40) }, { gates: [{ name: 'build', status: 'NOT_RUN' }] }]) {
-    writeFileSync(windows, JSON.stringify({ ...report, ...change }));
+  const manifest = JSON.parse(readFileSync(path.join(f.directory, 'candidate.json')));
+  assert.equal(manifest.sha256, receipt.sha256);
+  assert.deepEqual(manifest.validation.map(report => report.platform).sort(), ['darwin', 'linux']);
+  const macos = path.join(reports, 'darwin/verification.json');
+  const report = JSON.parse(readFileSync(macos));
+  for (const change of [{ status: 'FAIL' }, { revision: 'b'.repeat(40) }, { gates: [{ name: 'build', status: 'NOT_RUN' }] }, { platform: 'linux' }, { platform: 'win32' }]) {
+    writeFileSync(macos, JSON.stringify({ ...report, ...change }));
     assert.notEqual(run('finalize', '--reports', reports).status, 0);
   }
-  rmSync(path.dirname(windows), { recursive: true });
+  rmSync(path.dirname(macos), { recursive: true });
   assert.notEqual(run('finalize', '--reports', reports).status, 0);
 });
 
@@ -422,11 +425,13 @@ test('suite runner preserves gate arguments and canonicalizes Windows temporary
 });
 
 test('public support forms preserve destination URLs and separate Desktop from CLI reports', () => {
-  const forms = ['01-bug-report.yml', '02-feature-request.yml', '03-question.yml'];
+  const forms = ['01-bug-report.yml', '02-feature-request.yml', '03-question.yml', 'docs.yml'];
   for (const name of forms) {
     const form = parseYaml(readFileSync(new URL(`../.github/ISSUE_TEMPLATE/${name}`, import.meta.url), 'utf8'));
     const product = form.body.find(field => field.id === 'product');
-    assert.equal(product.validations.required, true);
+    assert.equal(product.validations.required, name !== '03-question.yml');
+    assert.equal(product.attributes.label, 'Product or interface');
+    assert.ok(product.attributes.options.includes('CLI - interactive TUI'));
     assert.ok(product.attributes.options.includes('Desktop app'));
     assert.ok(product.attributes.options.includes('CLI - ACP'));
     assert.ok(product.attributes.options.includes('CLI - headless'));
@@ -440,6 +445,72 @@ test('public support forms preserve destination URLs and separate Desktop from C
   assert.equal(classifyChanges(['README_ZH.md', 'README.md']).docsOnly, true);
 });
 
+test('issue product labels follow current form answers without replacing unrelated labels', async () => {
+  const workflow = parseYaml(readFileSync(new URL('../.github/workflows/label-issue-product.yml', import.meta.url), 'utf8'));
+  assert.deepEqual(workflow.on, { issues: { types: ['opened', 'edited'] } });
+  assert.deepEqual(workflow.permissions, { issues: 'write' });
+  assert.equal(workflow.concurrency['cancel-in-progress'], false);
+  const job = workflow.jobs['label-product'];
+  assert.equal(job.if, "${{ github.repository == 'MiniMax-AI/minimax-code' && github.event.repository.private == false && !github.event.issue.pull_request }}");
+  assert.equal(job.steps.length, 1); // No checkout or execution of issue-supplied code.
+  const run = job.steps[0].run;
+  assert.doesNotMatch(run, /\$\{\{/);
+  const script = run.match(/^node <<'EOF'\r?\n([\s\S]*?)\r?\nEOF\s*$/)?.[1];
+  assert.ok(script);
+  async function replay(body, labels, failureStatus) {
+    const writes = [];
+    const issuePath = '/repos/MiniMax-AI/minimax-code/issues/7';
+    await runInNewContext(script, {
+      require: name => {
+        assert.equal(name, 'node:fs');
+        return { readFileSync: () => JSON.stringify({ issue: { number: 7, body: '### Product or interface\n\nDesktop app', labels: [] } }) };
+      },
+      process: { env: { GITHUB_EVENT_PATH: 'fixture.json', GITHUB_REPOSITORY: 'MiniMax-AI/minimax-code', GITHUB_API_URL: 'https://api.github.invalid', GH_TOKEN: 'synthetic' } },
+      fetch: async (url, options) => {
+        assert.equal(options.headers.Authorization, 'Bearer synthetic');
+        if (options.method === 'GET') {
+          assert.equal(url, `https://api.github.invalid${issuePath}`);
+          return { ok: !failureStatus, status: failureStatus || 200, json: async () => ({ body, labels: labels.map(name => ({ name })) }) };
+        }
+        writes.push({ method: options.method, path: url.replace(`https://api.github.invalid${issuePath}`, ''), body: options.body && JSON.parse(options.body) });
+        return { ok: true, status: 204 };
+      },
+    });
+    return writes;
+  }
+  const answer = product => `### Product or interface\n\n${product}\n\n### Question\n\nSynthetic question`;
+  const add = name => ({ method: 'POST', path: '/labels', body: { labels: [name] } });
+  const remove = name => ({ method: 'DELETE', path: `/labels/${name}`, body: undefined });
+  assert.deepEqual(await replay(answer('CLI - interactive TUI'), ['bug', 'desktop']), [add('tui'), remove('desktop')]);
+  assert.deepEqual(await replay(answer('Desktop app').replace(/\n/g, '\r\n'), ['question']), [add('desktop')]);
+  assert.deepEqual(await replay(answer('Desktop app'), ['desktop', 'bug']), []);
+  for (const product of ['CLI - headless', 'CLI - ACP', 'Source build or repository tooling']) {
+    assert.deepEqual(await replay(answer(product), ['tui', 'bug']), [remove('tui')]);
+  }
+  for (const body of [null, 'Desktop app', answer('_No response_'), answer('$(touch must-not-execute)')]) {
+    assert.deepEqual(await replay(body, ['desktop', 'bug']), []);
+  }
+  await assert.rejects(replay(answer('Desktop app'), [], 403), /GitHub GET failed: 403/);
+});
+
+test('issue forms label incoming reports for triage and retain collaborator-only PR guidance', () => {
+  for (const [name, type] of [
+    ['01-bug-report.yml', 'bug'], ['02-feature-request.yml', 'enhancement'],
+    ['03-question.yml', 'question'], ['docs.yml', 'documentation'],
+  ]) {
+    const form = parseYaml(readFileSync(new URL(`../.github/ISSUE_TEMPLATE/${name}`, import.meta.url), 'utf8'));
+    assert.deepEqual(form.labels, [type, 'needs-triage']);
+  }
+  const config = parseYaml(readFileSync(new URL('../.github/ISSUE_TEMPLATE/config.yml', import.meta.url), 'utf8'));
+  assert.equal(config.blank_issues_enabled, false);
+  const policy = config.contact_links.find(link => link.url.endsWith('/CONTRIBUTING.md'));
+  assert.match(policy.about, /only from repository collaborators/);
+  assert.match(policy.about, /external PRs are not accepted/);
+  const question = parseYaml(readFileSync(new URL('../.github/ISSUE_TEMPLATE/03-question.yml', import.meta.url), 'utf8'));
+  assert.equal(question.body.find(field => field.id === 'platform').validations.required, false);
+  assert.equal(question.body.find(field => field.id === 'question').validations.required, true);
+});
+
 test('issue notification is restricted to public destination events and builds payloads offline', t => {
   const workflow = parseYaml(readFileSync(new URL('../.github/workflows/sync-issue-to-feishu.yml', import.meta.url), 'utf8'));
   assert.deepEqual(workflow.on, { issues: { types: ['opened'] } });

+ 3 - 0
test/vitest-suites.json

@@ -8,9 +8,11 @@
       "packages/agent-tools/src/shared/replace-all-edit.test.ts",
       "packages/local-runtime-v2/test/unit/agent/agent-import.test.ts",
       "packages/tui/test/unit/auth-application.test.ts",
+      "packages/tui/test/unit/tui-assistant-content.test.ts",
       "packages/tui/test/unit/business-telemetry-privacy.test.ts",
       "packages/tui/test/unit/auth-session.test.ts",
       "packages/tui/test/unit/cli-auth-command.test.ts",
+      "packages/tui/test/unit/network-proxy.test.ts",
       "packages/tui/test/unit/application-login-gate.test.ts",
       "packages/tui/test/unit/mcode-tools-integration.test.ts",
       "packages/tui/test/unit/provider-application.test.ts",
@@ -77,6 +79,7 @@
       "packages/tui/test/unit/tui-chat-controller.test.ts",
       "packages/tui/test/unit/tui-duration.test.ts",
       "packages/tui/test/unit/tui-engine-local-deltas.test.ts",
+      "packages/tui/test/unit/tui-scrollbar-interaction.test.ts",
       "packages/tui/test/unit/tui-image-preview.test.ts",
       "packages/tui/test/unit/tui-session-manager.test.ts",
       "packages/tui/test/unit/tui-shell-block.test.ts",

+ 34 - 0
third_party/pi-mono/MINIMAX_CHANGES.md

@@ -21,6 +21,40 @@ No upstream source files are changed in the baseline import.
 - Validation: the distribution-owned `packages/local-runtime-v2/test/integration/compaction-openai-transport.integration.test.ts` exercises `compactContext` through checkpoint generation and the real SDK against a local HTTP fixture that rejects empty tools. Regressions cover absent/empty definitions, tool history, Anthropic cache compatibility, ordinary requests, and preserved nonempty definitions. Run with `pnpm exec vitest run --config vitest.oss.config.mjs packages/local-runtime-v2/test/integration/compaction-openai-transport.integration.test.ts` and the full `pnpm verify` profile. Offline fixtures do not establish live LiteLLM/vLLM, OpenAI, or Anthropic proxy acceptance.
 - Upstream PR: not created.
 
+### 2026-09-19 — preserve the system role for Mistral Chat Completions
+
+- Reason: thinking-enabled custom OpenAI-compatible connections to `api.mistral.ai` emitted `developer`, which is absent from the [Mistral Chat Completions message contract](https://docs.mistral.ai/api/endpoint/chat). [OpenClaw's compatibility defaults](https://github.com/openclaw/openclaw/blob/e2bcb1614de060927121bd72de850cee3a08d308/packages/ai/src/transports/openai-completions-compat.ts#L184-L210) also disable this role for the Mistral public endpoint.
+- Affected package: `packages/ai` (`@earendil-works/pi-ai`), OpenAI Completions compatibility detection.
+- Change: default to `system` only on the exact Mistral API host. Preserve thinking, explicit compatibility overrides, all other request options, and other endpoints. Native Mistral transport is unchanged.
+- Upstream PR: not opened.
+- Validation: outgoing-payload regressions in `packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.test.ts`; the endpoint regression fails before the fix. No live Mistral requests or full CLI acceptance were performed; the decision is based on the official contract and current upstream implementation.
+
+### 2026-09-19 — preserve the system role for SiliconFlow
+
+- Reason: thinking-enabled OpenAI-compatible requests sent the `developer` role, which is absent from SiliconFlow's documented message schema.
+- Affected package: `packages/ai` (`@earendil-works/pi-ai`), OpenAI Completions compatibility detection.
+- Change: default to the `system` role on the exact `api.siliconflow.cn` and `api.siliconflow.com` hosts. Preserve thinking, explicit compatibility overrides, other request options, and other endpoints.
+- References: [official Chat Completions schema](https://docs.siliconflow.com/en/api-reference/chat-completions/chat-completions) and [pi's SiliconFlow provider proposal](https://github.com/earendil-works/pi/pull/8113) (closed without merging).
+- Upstream PR: not opened.
+- Validation: outgoing-payload regressions in `packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.test.ts`, including both official hosts, unrelated hosts, and explicit compatibility overrides.
+
+### 2026-09-19 — preserve the system role for DashScope
+
+- Reason: DashScope endpoints were treated as supporting the `developer` role, causing thinking-enabled OpenAI-compatible conversations to send an unsupported system-prompt role.
+- Affected package: `packages/ai` (`@earendil-works/pi-ai`), OpenAI Completions compatibility detection.
+- Change: default to the `system` role for official DashScope regional and Coding Plan hosts, plus workspace, trial, and Token Plan hosts under the documented regional `maas.aliyuncs.com` domains. Preserve thinking, other request options, explicit compatibility overrides, and other providers.
+- References: [official endpoint list](https://help.aliyun.com/en/model-studio/base-url), [Coding Plan role rejection](https://github.com/openclaw/openclaw/issues/23575), [Token Plan role rejection](https://github.com/earendil-works/pi/issues/7723), and [merged OpenClaw DashScope fix](https://github.com/openclaw/openclaw/pull/24675).
+- Upstream PR: not opened.
+- Validation: request-payload regressions in `packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.test.ts`, including official endpoints, unrelated hosts, and explicit compatibility overrides.
+
+### 2026-09-19 — preserve the system role for Kimi Coding
+
+- Reason: Kimi Coding endpoints were treated as supporting the `developer` role, causing thinking-enabled OpenAI-compatible conversations to send an unsupported system-prompt role.
+- Affected package: `packages/ai` (`@earendil-works/pi-ai`), OpenAI Completions compatibility detection.
+- Change: default to the `system` role for `api.kimi.com` and `api.kimi.ai`. Preserve thinking, other request options, explicit compatibility overrides, and other providers.
+- Upstream PR: not opened.
+- Validation: offline request-payload regressions in `packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.test.ts`. Live Kimi Coding validation requires a Coding Plan key and remains untested.
+
 ### 2026-08-31 — Windows PowerShell ConstrainedLanguage compatibility
 
 - Reason: the Windows PowerShell 5.1 stdin wrapper called `Parser.ParseInput`, `ScriptBlock.Create`, and other restricted .NET APIs before user commands. Under enterprise App Control / AppLocker `ConstrainedLanguage`, the wrapper therefore failed before commands such as Python could run.

+ 12 - 1
third_party/pi-mono/packages/ai/src/providers/openai-completions.ts

@@ -1068,6 +1068,12 @@ function detectCompat(model: Model<"openai-completions">): ResolvedOpenAIComplet
 	const isTogether =
 		provider === "together" || baseUrl.includes("api.together.ai") || baseUrl.includes("api.together.xyz");
 	const isMoonshot = provider === "moonshotai" || provider === "moonshotai-cn" || baseUrl.includes("api.moonshot.");
+	const isKimiCoding = /^https?:\/\/api\.kimi\.(?:com|ai)(?::\d+)?(?:\/|$)/i.test(baseUrl);
+	const isDashScope =
+		/^https?:\/\/(?:dashscope(?:-intl|-us)?|(?:coding(?:-intl)?|cn-hongkong)\.dashscope)\.aliyuncs\.com(?::\d+)?(?:\/|$)/i.test(baseUrl) ||
+		/^https?:\/\/[a-z0-9-]+\.(?:cn-beijing|cn-hongkong|ap-southeast-1|ap-northeast-1|eu-central-1|us-east-1)\.maas\.aliyuncs\.com(?::\d+)?(?:\/|$)/i.test(baseUrl);
+	const isSiliconFlow = /^https?:\/\/api\.siliconflow\.(?:cn|com)(?::\d+)?(?:\/|$)/i.test(baseUrl);
+	const isMistralApi = /^https?:\/\/api\.mistral\.ai(?::\d+)?(?:\/|$)/i.test(baseUrl);
 	const isOpenRouter = provider === "openrouter" || baseUrl.includes("openrouter.ai");
 	const isCloudflareWorkersAI = provider === "cloudflare-workers-ai" || baseUrl.includes("api.cloudflare.com");
 	const isCloudflareAiGateway = provider === "cloudflare-ai-gateway" || baseUrl.includes("gateway.ai.cloudflare.com");
@@ -1102,7 +1108,12 @@ function detectCompat(model: Model<"openai-completions">): ResolvedOpenAIComplet
 
 	return {
 		supportsStore: !isNonStandard,
-		supportsDeveloperRole: isOpenRouterDeveloperRoleModel || (!isNonStandard && !isOpenRouter),
+		supportsDeveloperRole:
+			!isKimiCoding &&
+			!isDashScope &&
+			!isSiliconFlow &&
+			!isMistralApi &&
+			(isOpenRouterDeveloperRoleModel || (!isNonStandard && !isOpenRouter)),
 		supportsReasoningEffort:
 			!isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia && !isAntLing,
 		supportsUsageInStreaming: true,