Преглед на файлове

chore: sync ZCode source v3.18.1

Source-Commit: 8c930ce53564c6e46e2a8e13a8d3f42d12207be5
Source-Sync: zcode-open-source-v1
ZCode Source Sync Bot преди 1 седмица
родител
ревизия
c5904686ea
променени са 100 файла, в които са добавени 2734 реда и са изтрити 458 реда
  1. 3 0
      .gitignore
  2. 2 1
      README.en.md
  3. 2 1
      README.md
  4. 4 0
      apps/zcode-cli/packages/adapters/package.json
  5. 11 0
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/CONTRACT.md
  6. 6 0
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/contract.example.ts
  7. 4 0
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/contract.ts
  8. 125 0
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/index.ts
  9. 10 0
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/module.ts
  10. 193 0
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/recorder.ts
  11. 81 0
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/storage.ts
  12. 32 0
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/types.ts
  13. 254 0
      apps/zcode-cli/packages/adapters/tests/memory-diagnostics/recorder.test.ts
  14. 4 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/v4-gateway.ts
  15. 16 1
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/resource-sampler.ts
  16. 14 15
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server.ts
  17. 21 0
      apps/zcode-cli/packages/bootstrap/tests/session-event-store-retention.protocol.test.ts
  18. 4 0
      apps/zcode-cli/packages/bootstrap/tests/v4-gateway.test.ts
  19. 2 2
      apps/zcode-cli/packages/cli/package.json
  20. 18 0
      architecture-policy.yaml
  21. 3 3
      docs/browser-use/2026-11-03-browser-design-mode-spec.md
  22. 65 11
      docs/chat/composer-voice-input.md
  23. 16 0
      docs/chat/reasoning-streaming-auto-collapse.md
  24. 6 0
      docs/conversation-session-case-catalog.md
  25. 9 5
      docs/desktop/windows-installer-overhaul-spec.md
  26. 29 12
      docs/desktop/windows-installer-preserve-files.md
  27. 21 4
      docs/desktop/windows-update-install-handoff.md
  28. 4 3
      docs/dynamic-workflow/launch.md
  29. 86 38
      docs/monitoring/memory-diagnostics-log.md
  30. 1 0
      docs/superpowers/specs/2026-09-09-virtual-project-design.md
  31. 6 0
      docs/testing/conversation-session-e2e-coverage-matrix.md
  32. 10 6
      docs/testing/desktop-auth-config-e2e-cases.md
  33. 35 0
      docs/ui/macos-font-smoothing.md
  34. 1 1
      docs/ui/tool-display-rendering.md
  35. 11 16
      docs/web-remote-control/mobile-task-home-design.md
  36. 1 1
      docs/web-remote-control/web-remote-control-architecture.md
  37. 6 4
      docs/zcode-login-rework.md
  38. 2 2
      package-lock.json
  39. 1 1
      package.json
  40. 75 9
      packages/desktop/build/installer.nsh
  41. 46 0
      packages/desktop/electron-builder.config.js
  42. 1 0
      packages/desktop/scripts/test-installer-nsh-smoke.mjs
  43. 95 17
      packages/desktop/scripts/test-installer-preserve-files.mjs
  44. 13 0
      packages/desktop/src/main/exportLogs.ts
  45. 4 1
      packages/desktop/src/main/microphone-access/CONTRACT.md
  46. 5 1
      packages/desktop/src/main/microphone-access/contract.ts
  47. 88 2
      packages/desktop/src/main/microphone-access/desktopMicrophoneAccess.ts
  48. 1 0
      packages/desktop/src/main/microphone-access/index.ts
  49. 4 0
      packages/desktop/src/preload/index.ts
  50. 4 1
      packages/desktop/src/renderer/src/desktopBrowserPlatformBridge.ts
  51. 90 6
      packages/desktop/test/e2e/auth-config/login/oauth-completion-race.test.ts
  52. 11 15
      packages/desktop/test/e2e/browser/design/browser-design-mode.test.ts
  53. 16 0
      packages/desktop/test/e2e/conversation-session/projects/conversation-session-project-composer.test.ts
  54. 7 1
      packages/desktop/test/e2e/helpers/browser-design-mode.ts
  55. 2 2
      packages/desktop/test/e2e/helpers/oauth-completion-race-fixture.ts
  56. 42 0
      packages/desktop/test/e2e/settings/appearance/manual-review/pending/macos-font-smoothing.test.ts
  57. 110 12
      packages/desktop/test/e2e/ui-shell/composer/composer-voice-input.test.ts
  58. 5 1
      packages/desktop/test/fixtures/installer-nsh-smoke.nsi
  59. 28 7
      packages/desktop/test/fixtures/installer-preserve-files.nsi
  60. 2 0
      packages/desktop/test/nsis-install-section-patch.test.ts
  61. 44 1
      packages/desktop/test/windowsInstallerCompile.test.ts
  62. 11 1
      packages/services/src/feedback/compactLogArchive.ts
  63. 51 10
      packages/services/src/feedback/feedbackLogArchive.ts
  64. 27 4
      packages/services/src/oauth/oauthService.ts
  65. 7 0
      packages/shared/src/channels.ts
  66. 1 1
      packages/shared/src/index.ts
  67. 151 0
      packages/shared/src/memoryDiagnostics.ts
  68. 11 0
      packages/shared/src/platform.ts
  69. 10 0
      packages/shared/src/test-ids.ts
  70. 1 17
      packages/ui/src/App.tsx
  71. 1 1
      packages/ui/src/ElicitationDialog.tsx
  72. 8 6
      packages/ui/src/InteractionRequestOriginBadge.tsx
  73. 6 0
      packages/ui/src/SettingsPage.tsx
  74. 40 54
      packages/ui/src/ToolCallBlocks/QueuedSummaryContent.tsx
  75. 23 27
      packages/ui/src/WebRemoteControlMobileShell.tsx
  76. 2 1
      packages/ui/src/app-shell/WorkspaceShellLayout.tsx
  77. 2 1
      packages/ui/src/app-shell/animatedSidePanePanelModel.ts
  78. 0 21
      packages/ui/src/browser-use/UnifiedBrowserView.tsx
  79. 5 4
      packages/ui/src/browser-use/useBrowserDesignMode.ts
  80. 11 7
      packages/ui/src/components/ai-elements/reasoning.tsx
  81. 15 4
      packages/ui/src/i18n/locales/en-US.ts
  82. 3 0
      packages/ui/src/i18n/locales/ja-JP.ts
  83. 3 0
      packages/ui/src/i18n/locales/ko-KR.ts
  84. 3 0
      packages/ui/src/i18n/locales/ru-RU.ts
  85. 13 4
      packages/ui/src/i18n/locales/zh-CN.ts
  86. 2 1
      packages/ui/src/project-sidebar/ProjectComposerMenu.tsx
  87. 7 0
      packages/ui/src/settings-search/settingsSearchIndex.ts
  88. 21 0
      packages/ui/src/settingsCodePreview.tsx
  89. 0 32
      packages/ui/src/side-pane-full-view/enterRequest.ts
  90. 0 6
      packages/ui/src/side-pane-full-view/index.ts
  91. 23 1
      packages/ui/src/store/index.ts
  92. 4 0
      packages/ui/src/styles.css
  93. 2 0
      packages/ui/src/v4/ConversationComposer.tsx
  94. 1 0
      packages/ui/src/voice-input/CONTRACT.md
  95. 22 0
      packages/ui/src/voice-input/contract.ts
  96. 4 2
      packages/ui/src/voice-input/domain/voiceInputFailure.ts
  97. 150 48
      packages/ui/src/voice-input/ui/VoiceInputControls.tsx
  98. 9 2
      packages/ui/src/voice-input/ui/useComposerVoiceInput.ts
  99. 119 0
      packages/ui/src/voice-input/ui/useMicrophonePermissionGuide.ts
  100. 153 0
      packages/ui/test/browser/manual-review/pending/font-smoothing.test.mjs

+ 3 - 0
.gitignore

@@ -75,3 +75,6 @@ packages/desktop/resources/macos-window-bounds/
 __pycache__/
 *.pyc
 .zcode-runtime
+
+# CR-01:afterPack 生成的 NSIS helper define,按架构命名,不得入库
+packages/desktop/build/generated/

+ 2 - 1
README.en.md

@@ -15,7 +15,8 @@ ZCode is an AI coding workspace with desktop, browser, and terminal interfaces.
 
 ## Updates
 
-- **2026-11-11**: Updated to ZCode v3.18.0.
+- **2026-11-12**: Updated to ZCode v3.18.1.
+- 2026-11-11: Updated to ZCode v3.18.0.
 - 2026-11-03: Updated to ZCode v3.17.2.
 - 2026-10-30: Updated to ZCode v3.17.1.
 - 2026-10-29: Updated to ZCode v3.17.0.

+ 2 - 1
README.md

@@ -15,7 +15,8 @@ ZCode 是 AI 编程工作台,提供桌面应用、浏览器界面和终端 Age
 
 ## 更新
 
-- **2026-11-11**:更新至 ZCode v3.18.0 版本。
+- **2026-11-12**:更新至 ZCode v3.18.1 版本。
+- 2026-11-11:更新至 ZCode v3.18.0 版本。
 - 2026-11-03:更新至 ZCode v3.17.2 版本。
 - 2026-10-30:更新至 ZCode v3.17.1 版本。
 - 2026-10-29:更新至 ZCode v3.17.0 版本。

+ 4 - 0
apps/zcode-cli/packages/adapters/package.json

@@ -89,6 +89,10 @@
     "./tools": {
       "types": "./dist/tools/index.d.ts",
       "import": "./dist/tools/index.js"
+    },
+    "./memory-diagnostics": {
+      "types": "./dist/memory-diagnostics/index.d.ts",
+      "import": "./dist/memory-diagnostics/index.js"
     }
   },
   "scripts": {

+ 11 - 0
apps/zcode-cli/packages/adapters/src/memory-diagnostics/CONTRACT.md

@@ -0,0 +1,11 @@
+# CLI 内存诊断
+
+app-server 就绪后调用 startCliMemoryDiagnostics,退出时调用 stop。
+本模块独占 inspector 和诊断文件;只读取调用方提供的计数器,不持有会话或正文。
+无 source map、脚本源码、调试端口、强制 GC 或完整堆快照。
+
+采样与落盘单次在途,忙时丢样本。分配窗口、节点数、投影栈与文件大小都有上限。
+跨进程只通过既有目录锁维护一份文件预算;锁竞争不排队,失败不传播到任务。
+反馈归档按 shared 的 sanitizeCliMemoryDiagnostic 契约重新做安全投影。
+
+完整参数和验收见 docs/monitoring/memory-diagnostics-log.md。

+ 6 - 0
apps/zcode-cli/packages/adapters/src/memory-diagnostics/contract.example.ts

@@ -0,0 +1,6 @@
+import { startCliMemoryDiagnostics } from "./index.js";
+
+export function exampleMemoryDiagnostics() {
+  const diagnostics = startCliMemoryDiagnostics(() => ({ sessions: 0 }));
+  return () => diagnostics.stop();
+}

+ 4 - 0
apps/zcode-cli/packages/adapters/src/memory-diagnostics/contract.ts

@@ -0,0 +1,4 @@
+export interface CliMemoryDiagnostics {
+  /** 幂等停止采样;不等待写盘,不改变任务生命周期。 */
+  stop(): void;
+}

+ 125 - 0
apps/zcode-cli/packages/adapters/src/memory-diagnostics/index.ts

@@ -0,0 +1,125 @@
+import { createHash, randomUUID } from "node:crypto";
+import { createReadStream } from "node:fs";
+import { realpath, stat } from "node:fs/promises";
+import { Session } from "node:inspector";
+import { homedir } from "node:os";
+import { join, resolve } from "node:path";
+import { getHeapStatistics } from "node:v8";
+import { CLI_MEMORY_DIAGNOSTIC_DIRECTORY, ZCODE_COMMIT, ZCODE_VERSION } from "@zcode/shared";
+import {
+  createMemoryDiagnosticRecorder,
+  MEMORY_DIAGNOSTIC_INTERVAL_MS,
+  MEMORY_SAMPLE_INTERVAL_BYTES,
+} from "./recorder.js";
+import { writeMemoryDiagnostic } from "./storage.js";
+import type { AllocationNode, AllocationProfiler } from "./types.js";
+import type { CliMemoryDiagnostics } from "./contract.js";
+export { createMemoryDiagnosticRecorder } from "./recorder.js";
+export { writeMemoryDiagnostic } from "./storage.js";
+export type { MemoryDiagnosticOptions, MemoryDiagnosticRecorder } from "./types.js";
+
+const MAX_HASH_BYTES = 128 * 1024 * 1024;
+const SAMPLING_STACK_DEPTH = 16;
+function createProfiler(): AllocationProfiler {
+  const session = new Session();
+  const post = <T>(method: string, params: Record<string, unknown> = {}): Promise<T> =>
+    new Promise((res, rej) =>
+      session.post(method, params, (error, result) => (error ? rej(error) : res(result as T))),
+    );
+  const start = () =>
+    post<void>("HeapProfiler.startSampling", {
+      samplingInterval: MEMORY_SAMPLE_INTERVAL_BYTES,
+      stackDepth: SAMPLING_STACK_DEPTH,
+      includeObjectsCollectedByMajorGC: false,
+      includeObjectsCollectedByMinorGC: false,
+    });
+  return {
+    async start() {
+      session.connect();
+      await start();
+    },
+    async read() {
+      return (await post<{ profile: { head: AllocationNode } }>("HeapProfiler.getSamplingProfile"))
+        .profile;
+    },
+    async reset() {
+      // disable 清除采样状态,不使用 stopSampling 再复制一次完整 profile。
+      await post("HeapProfiler.disable");
+      await start();
+    },
+    dispose() {
+      session.disconnect();
+    },
+  };
+}
+
+async function hashBundle(path: string): Promise<string> {
+  if ((await stat(path)).size > MAX_HASH_BYTES) return "";
+  const hash = createHash("sha256");
+  let bytes = 0;
+  for await (const chunk of createReadStream(path)) {
+    bytes += chunk.length;
+    if (bytes > MAX_HASH_BYTES) return "";
+    hash.update(chunk);
+  }
+  return hash.digest("hex");
+}
+
+/** app-server 的独立诊断资源;不依赖 renderer、网络或业务日志级别。 */
+export function startCliMemoryDiagnostics(
+  readCounters: () => Record<string, number>,
+  options: { directory?: string } = {},
+): CliMemoryDiagnostics {
+  let bundlePath = resolve(process.argv[1] ?? "");
+  const metadata = {
+    instanceId: randomUUID(),
+    pid: process.pid,
+    version: ZCODE_VERSION,
+    commit: ZCODE_COMMIT,
+    node: process.versions.node,
+    v8: process.versions.v8,
+    bundleSha256: "",
+  };
+  const recorder = createMemoryDiagnosticRecorder({
+    get bundlePath() {
+      return bundlePath;
+    },
+    metadata: () => metadata,
+    readCounters,
+    profiler: createProfiler(),
+    readMemory: () => ({
+      ...process.memoryUsage(),
+      heapLimit: getHeapStatistics().heap_size_limit,
+    }),
+    write: (record) =>
+      writeMemoryDiagnostic(
+        options.directory ?? join(homedir(), ".zcode", "cli", CLI_MEMORY_DIAGNOSTIC_DIRECTORY),
+        record,
+      ),
+  });
+  // 哈希流式读取,不复制 bundle 到 JS 堆,也不挡住协议 ready。
+  // macOS 的 /var、/tmp 等别名与 V8 返回的真实路径不同,需异步归一化再匹配采样帧。
+  void realpath(bundlePath).then(
+    (path) => {
+      bundlePath = path;
+    },
+    () => {},
+  );
+  void hashBundle(bundlePath).then(
+    (hash) => {
+      metadata.bundleSha256 = hash;
+    },
+    () => {},
+  );
+  void recorder.start();
+  const timer = setInterval(() => {
+    void recorder.sample();
+  }, MEMORY_DIAGNOSTIC_INTERVAL_MS);
+  timer.unref();
+  return {
+    stop() {
+      clearInterval(timer);
+      recorder.stop();
+    },
+  };
+}

+ 10 - 0
apps/zcode-cli/packages/adapters/src/memory-diagnostics/module.ts

@@ -0,0 +1,10 @@
+/**
+ * cli-memory-diagnostics 模块清单(architecture-governance managed 模块)。
+ * 层:adapters。修改 requires 时同步更新 architecture-policy.yaml(检查器会校验两者一致)。
+ */
+export const cliMemoryDiagnosticsModule = {
+  id: "cli-memory-diagnostics",
+  requires: ["shared", "zcode-cli"],
+  provides: ["cli-memory-diagnostics"],
+  publicEntrypoints: ["index.ts", "contract.ts"],
+} as const;

+ 193 - 0
apps/zcode-cli/packages/adapters/src/memory-diagnostics/recorder.ts

@@ -0,0 +1,193 @@
+import { performance } from "node:perf_hooks";
+import { fileURLToPath } from "node:url";
+import { normalize } from "node:path";
+import {
+  CLI_MEMORY_MAX_ALLOCATIONS,
+  CLI_MEMORY_MAX_SAMPLES,
+  CLI_MEMORY_MAX_STACK_DEPTH,
+  sanitizeCliMemoryDiagnostic,
+  type CliMemoryAllocation,
+  type CliMemoryDiagnostic,
+  type CliMemoryReading,
+} from "@zcode/shared";
+import type { AllocationNode, MemoryDiagnosticOptions, MemoryDiagnosticRecorder } from "./types.js";
+
+export const MEMORY_SAMPLE_INTERVAL_BYTES = 1024 * 1024;
+export const MEMORY_DIAGNOSTIC_INTERVAL_MS = 15_000;
+export const MEMORY_PROFILE_WINDOW_MS = 60_000;
+const MAX_PROFILE_NODES = 4096;
+const MAX_PROFILE_WORK_MS = 25;
+const MAX_HEAP_USAGE_RATIO = 0.8;
+
+function projectAllocations(
+  head: AllocationNode,
+  bundlePath: string,
+): CliMemoryAllocation[] | null {
+  const comparablePath = (path: string) =>
+    process.platform === "win32" ? normalize(path).toLowerCase() : normalize(path);
+  const expectedPath = comparablePath(bundlePath);
+  const work: Array<{ node: AllocationNode; stack: CliMemoryAllocation["stack"] }> = [
+    { node: head, stack: [] },
+  ];
+  const top: CliMemoryAllocation[] = [];
+  let visited = 0;
+  while (work.length) {
+    if (++visited > MAX_PROFILE_NODES) return null;
+    const { node, stack: previous } = work.pop()!;
+    const frame = node.callFrame;
+    let path = frame.url;
+    if (path.startsWith("file:")) {
+      try {
+        path = fileURLToPath(path);
+      } catch {
+        path = "";
+      }
+    }
+    // 只保留已知发布 bundle 的位置,eval、插件和用户脚本的名称/路径不能进入日志。
+    const stack =
+      comparablePath(path) === expectedPath
+        ? [
+            ...previous,
+            { name: frame.functionName, line: frame.lineNumber, column: frame.columnNumber },
+          ].slice(-CLI_MEMORY_MAX_STACK_DEPTH)
+        : previous;
+    if (node.selfSize > 0 && stack.length) {
+      top.push({ bytes: node.selfSize, stack });
+      top.sort((a, b) => b.bytes - a.bytes);
+      if (top.length > CLI_MEMORY_MAX_ALLOCATIONS) top.pop();
+    }
+    // 不能先把巨大 children 全部复制到遍历栈,否则“有界投影”本身也会申请大块内存。
+    if (visited + work.length + node.children.length > MAX_PROFILE_NODES) return null;
+    for (const child of node.children) work.push({ node: child, stack });
+  }
+  return top;
+}
+
+export function createMemoryDiagnosticRecorder(
+  options: MemoryDiagnosticOptions,
+): MemoryDiagnosticRecorder {
+  const now = options.now ?? Date.now;
+  const measure = options.measure ?? (() => performance.now());
+  let stopped = false;
+  let busy = false;
+  let started = false;
+  let disposed = false;
+  let state: CliMemoryDiagnostic["sampler"]["state"] = "unsupported";
+  let windowStartedAt = 0;
+  let profileCapturedAt = 0;
+  let profileWindowStartedAt = 0;
+  let lastAllocations: CliMemoryAllocation[] = [];
+  const samples: CliMemoryReading[] = [];
+  const disposeProfiler = () => {
+    if (disposed) return;
+    disposed = true;
+    try {
+      options.profiler.dispose();
+    } catch {
+      /* 诊断清理不能影响 runtime 退出。 */
+    }
+  };
+  return {
+    async start() {
+      if (started || stopped) return;
+      started = true;
+      busy = true;
+      try {
+        const began = measure();
+        await options.profiler.start();
+        if (stopped) {
+          disposeProfiler();
+          return;
+        }
+        state = measure() - began > MAX_PROFILE_WORK_MS ? "budget-exceeded" : "active";
+        windowStartedAt = now();
+        if (state !== "active") disposeProfiler();
+      } catch {
+        disposeProfiler();
+      } finally {
+        busy = false;
+      }
+    },
+    async sample() {
+      // 磁盘慢、inspector 忙或正在退出时直接丢本轮,绝不叠加 promise 队列。
+      if (stopped || !started) return;
+      if (busy) {
+        // 慢磁盘不能把 60 秒采样窗口无限拉长;忙时不排队,窗口到期直接释放 profiler。
+        if (state === "active" && now() - windowStartedAt >= MEMORY_PROFILE_WINDOW_MS) {
+          state = "budget-exceeded";
+          disposeProfiler();
+        }
+        return;
+      }
+      busy = true;
+      try {
+        const began = measure();
+        const memory = options.readMemory();
+        samples.push({ at: now(), ...memory, counters: options.readCounters() });
+        if (samples.length > CLI_MEMORY_MAX_SAMPLES) samples.shift();
+        if (
+          state === "active" &&
+          memory.heapLimit > 0 &&
+          memory.heapUsed >= memory.heapLimit * MAX_HEAP_USAGE_RATIO
+        ) {
+          // 接近堆上限时不再物化 profile,保留此前热点,避免取证本身触发最后一次大分配。
+          state = "budget-exceeded";
+          disposeProfiler();
+        }
+        if (state === "active") {
+          try {
+            const profile = await options.profiler.read();
+            if (stopped) return;
+            const projected = projectAllocations(profile.head, options.bundlePath);
+            if (!projected || measure() - began > MAX_PROFILE_WORK_MS) {
+              state = "budget-exceeded";
+              disposeProfiler();
+            } else {
+              // 降级后仍带上最后一次有效热点,不能让后续纯指标记录把关键现场覆盖掉。
+              lastAllocations = projected;
+              profileCapturedAt = now();
+              profileWindowStartedAt = windowStartedAt;
+              if (now() - windowStartedAt >= MEMORY_PROFILE_WINDOW_MS) {
+                await options.profiler.reset();
+                if (stopped) return;
+                windowStartedAt = now();
+              }
+            }
+          } catch {
+            state = "error";
+            disposeProfiler();
+          }
+        }
+        if (stopped) return;
+        const durationMs = measure() - began;
+        if (state === "active" && durationMs > MAX_PROFILE_WORK_MS) {
+          state = "budget-exceeded";
+          disposeProfiler();
+        }
+        const record = sanitizeCliMemoryDiagnostic({
+          format: "zcode-cli-memory-v1",
+          timestamp: now(),
+          ...options.metadata(),
+          sampler: {
+            state,
+            intervalBytes: MEMORY_SAMPLE_INTERVAL_BYTES,
+            windowStartedAt: profileWindowStartedAt,
+            profileCapturedAt,
+            durationMs,
+          },
+          samples,
+          allocations: lastAllocations,
+        });
+        if (record) await options.write(record);
+      } catch {
+        /* 只丢当前样本,不在 OOM 现场增加错误日志或重试。 */
+      } finally {
+        busy = false;
+      }
+    },
+    stop() {
+      stopped = true;
+      disposeProfiler();
+    },
+  };
+}

+ 81 - 0
apps/zcode-cli/packages/adapters/src/memory-diagnostics/storage.ts

@@ -0,0 +1,81 @@
+import { lstat, mkdir, readdir, rm } from "node:fs/promises";
+import { join } from "node:path";
+import {
+  CLI_MEMORY_FILE_PATTERN,
+  CLI_MEMORY_MAX_FILES,
+  CLI_MEMORY_MAX_FILE_BYTES,
+  sanitizeCliMemoryDiagnostic,
+  type CliMemoryDiagnostic,
+} from "@zcode/shared";
+import { acquireFileLock, atomicWritePrivateTextFile } from "@zcode/shared/node";
+
+const RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
+const LOCK_OWNERLESS_GRACE_MS = 100;
+const LOCK_TRY_MS = 25;
+const MAX_FILES_PER_INSTANCE = 2;
+let writing = false;
+
+export async function writeMemoryDiagnostic(
+  directory: string,
+  record: CliMemoryDiagnostic,
+): Promise<void> {
+  if (writing) return;
+  writing = true;
+  let release: (() => Promise<void>) | undefined;
+  try {
+    const safe = sanitizeCliMemoryDiagnostic(record);
+    if (!safe || !safe.instanceId) return;
+    const text = JSON.stringify(safe) + "\n";
+    if (Buffer.byteLength(text) > CLI_MEMORY_MAX_FILE_BYTES) return;
+    await mkdir(directory, { recursive: true, mode: 0o700 });
+    // 复用跨进程锁的存活 owner 判据;竞争只试一次,不创建进程内等待队列。
+    release = await acquireFileLock(
+      join(directory, "records"),
+      [],
+      LOCK_OWNERLESS_GRACE_MS,
+      LOCK_TRY_MS,
+    );
+    const files: Array<{ path: string; name: string; mtime: number }> = [];
+    for (const name of await readdir(directory)) {
+      const path = join(directory, name);
+      if (name.startsWith(".memory-") && name.endsWith(".tmp")) {
+        await rm(path, { force: true });
+      } else if (CLI_MEMORY_FILE_PATTERN.test(name)) {
+        const info = await lstat(path);
+        if (
+          !info.isFile() ||
+          info.nlink !== 1 ||
+          info.size > CLI_MEMORY_MAX_FILE_BYTES ||
+          Date.now() - info.mtimeMs > RETENTION_MS
+        ) {
+          await rm(path, { force: true });
+        } else files.push({ path, name, mtime: info.mtimeMs });
+      }
+    }
+    files.sort((a, b) => b.mtime - a.mtime);
+    let ownFiles = 0;
+    const retained: typeof files = [];
+    for (const file of files) {
+      if (
+        file.name.endsWith("-" + safe.instanceId + ".jsonl") &&
+        ++ownFiles >= MAX_FILES_PER_INSTANCE
+      ) {
+        await rm(file.path, { force: true });
+      } else retained.push(file);
+    }
+    // 先腾出一个完整文件配额再写;临时文件也只可能有一份,崩溃后由下个持锁者回收。
+    // 先替换本实例的旧记录,避免仍活跃的 CLI 很快挤掉已崩溃实例留下的最后现场。
+    for (const old of retained.slice(CLI_MEMORY_MAX_FILES - 1)) await rm(old.path, { force: true });
+    const filename = "memory-" + Date.now() + "-" + safe.instanceId + ".jsonl";
+    await atomicWritePrivateTextFile(join(directory, filename), text, []);
+  } catch {
+    /* 存储不可用时丢本轮,不能阻塞或改变任务结果。 */
+  } finally {
+    try {
+      await release?.();
+    } catch {
+      /* 下次使用既有 abandoned-lock 恢复。 */
+    }
+    writing = false;
+  }
+}

+ 32 - 0
apps/zcode-cli/packages/adapters/src/memory-diagnostics/types.ts

@@ -0,0 +1,32 @@
+import type { CliMemoryDiagnostic, CliMemoryReading } from "@zcode/shared";
+
+export interface AllocationNode {
+  id: number;
+  selfSize: number;
+  callFrame: { functionName: string; url: string; lineNumber: number; columnNumber: number };
+  children: AllocationNode[];
+}
+export interface AllocationProfiler {
+  start(): Promise<void>;
+  read(): Promise<{ head: AllocationNode }>;
+  reset(): Promise<void>;
+  dispose(): void;
+}
+export interface MemoryDiagnosticRecorder {
+  start(): Promise<void>;
+  sample(): Promise<void>;
+  stop(): void;
+}
+export interface MemoryDiagnosticOptions {
+  bundlePath: string;
+  metadata(): Pick<
+    CliMemoryDiagnostic,
+    "instanceId" | "pid" | "version" | "commit" | "node" | "v8" | "bundleSha256"
+  >;
+  profiler: AllocationProfiler;
+  readMemory(): Omit<CliMemoryReading, "at" | "counters">;
+  readCounters(): Record<string, number>;
+  write(record: CliMemoryDiagnostic): Promise<void>;
+  now?(): number;
+  measure?(): number;
+}

+ 254 - 0
apps/zcode-cli/packages/adapters/tests/memory-diagnostics/recorder.test.ts

@@ -0,0 +1,254 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { randomUUID } from "node:crypto";
+import {
+  createMemoryDiagnosticRecorder,
+  writeMemoryDiagnostic,
+} from "../../src/memory-diagnostics/index.js";
+import {
+  sanitizeCliMemoryDiagnostic,
+  CLI_MEMORY_MAX_FILES,
+  CLI_MEMORY_MAX_FILE_BYTES,
+  type CliMemoryDiagnostic,
+} from "@zcode/shared";
+
+const profile = {
+  head: {
+    id: 1,
+    selfSize: 0,
+    callFrame: { functionName: "", url: "", lineNumber: 0, columnNumber: 0 },
+    children: [
+      {
+        id: 2,
+        selfSize: 2097152,
+        callFrame: { functionName: "grow", url: "/app/zcode.cjs", lineNumber: 5, columnNumber: 32 },
+        children: [],
+      },
+    ],
+  },
+  samples: [],
+};
+const metadata = {
+  instanceId: "00000000-0000-4000-8000-000000000000",
+  pid: 123,
+  version: "3.18.1",
+  commit: "abcdef01",
+  node: "24.21.0",
+  v8: "15.2",
+  bundleSha256: "a".repeat(64),
+};
+function fixture(measure: () => number = () => 0, heapUsed = 50) {
+  let now = 0;
+  const profiler = {
+    start: vi.fn(async () => {}),
+    read: vi.fn(async () => profile),
+    reset: vi.fn(async () => {}),
+    dispose: vi.fn(),
+  };
+  const write = vi.fn(async (_record: CliMemoryDiagnostic) => {});
+  const recorder = createMemoryDiagnosticRecorder({
+    metadata: () => metadata,
+    bundlePath: "/app/zcode.cjs",
+    profiler,
+    write,
+    readMemory: () => ({
+      rss: 100,
+      heapUsed,
+      heapTotal: 80,
+      external: 20,
+      arrayBuffers: 10,
+      heapLimit: 200,
+    }),
+    readCounters: () => ({ sessions: 2 }),
+    now: () => now,
+    measure,
+  });
+  return {
+    recorder,
+    profiler,
+    write,
+    advance: (n: number) => {
+      now += n;
+    },
+  };
+}
+const directories: string[] = [];
+afterEach(async () => {
+  await Promise.all(
+    directories.splice(0).map((path) => rm(path, { recursive: true, force: true })),
+  );
+});
+
+describe("bounded CLI memory evidence", () => {
+  it("keeps bounded history, bundle locations and resets the V8 sampling window", async () => {
+    const f = fixture();
+    await f.recorder.start();
+    for (let i = 0; i < 12; i++) {
+      f.advance(15000);
+      await f.recorder.sample();
+    }
+    const last = f.write.mock.calls.at(-1)![0];
+    expect(last.samples).toHaveLength(8);
+    expect(last.allocations[0]).toMatchObject({
+      bytes: 2097152,
+      stack: [{ name: "grow", line: 5, column: 32 }],
+    });
+    expect(JSON.stringify(last)).not.toContain("/app/");
+    expect(f.profiler.reset).toHaveBeenCalledTimes(3);
+    f.recorder.stop();
+  });
+  it("drops overlapping reads and ignores a profile that completes after stop", async () => {
+    const f = fixture();
+    await f.recorder.start();
+    let resolve!: (value: typeof profile) => void;
+    f.profiler.read.mockImplementationOnce(
+      () =>
+        new Promise((r) => {
+          resolve = r;
+        }),
+    );
+    const pending = f.recorder.sample();
+    await f.recorder.sample();
+    f.recorder.stop();
+    resolve(profile);
+    await pending;
+    expect(f.write).not.toHaveBeenCalled();
+    expect(f.profiler.read).toHaveBeenCalledTimes(1);
+    expect(f.profiler.dispose).toHaveBeenCalledTimes(1);
+  });
+  it("disables expensive profiling and keeps metrics after an oversized profile", async () => {
+    const f = fixture();
+    await f.recorder.start();
+    f.profiler.read.mockResolvedValueOnce({
+      ...profile,
+      head: { ...profile.head, children: new Array(4100).fill(profile.head.children[0]) },
+    });
+    await f.recorder.sample();
+    await f.recorder.sample();
+    expect(f.profiler.read).toHaveBeenCalledTimes(1);
+    expect(f.write.mock.calls.at(-1)![0].sampler.state).toBe("budget-exceeded");
+    expect(f.write.mock.calls.at(-1)![0].samples).toHaveLength(2);
+  });
+  it("opens the performance circuit after a slow checkpoint", async () => {
+    let elapsed = 0;
+    const f = fixture(() => elapsed);
+    await f.recorder.start();
+    f.profiler.read.mockImplementationOnce(async () => {
+      elapsed = 30;
+      return profile;
+    });
+    await f.recorder.sample();
+    await f.recorder.sample();
+    expect(f.profiler.read).toHaveBeenCalledTimes(1);
+    expect(f.write.mock.calls.at(-1)![0].sampler.state).toBe("budget-exceeded");
+    f.recorder.stop();
+  });
+  it("does not materialize a profile when the heap is near its limit", async () => {
+    const f = fixture(() => 0, 170);
+    await f.recorder.start();
+    await f.recorder.sample();
+    expect(f.profiler.read).not.toHaveBeenCalled();
+    expect(f.write.mock.calls[0]![0].sampler.state).toBe("budget-exceeded");
+    expect(f.write.mock.calls[0]![0].samples[0].heapUsed).toBe(170);
+    f.recorder.stop();
+  });
+  it("drops ticks while a write is pending instead of retaining a write queue", async () => {
+    const f = fixture();
+    await f.recorder.start();
+    let finish!: () => void;
+    f.write.mockImplementationOnce(
+      () =>
+        new Promise<void>((resolve) => {
+          finish = resolve;
+        }),
+    );
+    const pending = f.recorder.sample();
+    await Promise.resolve();
+    f.advance(60000);
+    for (let i = 0; i < 50; i++) await f.recorder.sample();
+    expect(f.write).toHaveBeenCalledTimes(1);
+    expect(f.profiler.read).toHaveBeenCalledTimes(1);
+    expect(f.profiler.dispose).toHaveBeenCalledTimes(1);
+    finish();
+    await pending;
+    f.recorder.stop();
+  });
+  it("retains external memory metrics when the inspector is unavailable", async () => {
+    const f = fixture();
+    f.profiler.start.mockRejectedValueOnce(new Error("unsupported"));
+    await f.recorder.start();
+    await f.recorder.sample();
+    const record = f.write.mock.calls[0]![0];
+    expect(record.sampler.state).toBe("unsupported");
+    expect(record.samples[0].external).toBe(20);
+    expect(record.allocations).toEqual([]);
+    f.recorder.stop();
+  });
+  it("keeps the last useful allocation evidence after the profiler fails", async () => {
+    const f = fixture();
+    await f.recorder.start();
+    f.advance(15000);
+    await f.recorder.sample();
+    f.profiler.read.mockRejectedValueOnce(new Error("inspector stopped"));
+    f.advance(15000);
+    await f.recorder.sample();
+    const last = f.write.mock.calls.at(-1)![0];
+    expect(last.sampler.state).toBe("error");
+    expect(last.sampler.profileCapturedAt).toBe(15000);
+    expect(last.timestamp).toBe(30000);
+    expect(last.allocations[0].stack[0].name).toBe("grow");
+    f.recorder.stop();
+  });
+  it("keeps useful numbers and strips unexpected content from uploaded records", async () => {
+    const f = fixture();
+    await f.recorder.start();
+    await f.recorder.sample();
+    const raw = {
+      ...f.write.mock.calls[0]![0],
+      prompt: "private",
+      source: "private",
+      environment: { token: "private" },
+    };
+    raw.allocations[0].stack[0].name = "/Users/private/token";
+    const safe = sanitizeCliMemoryDiagnostic(raw)!;
+    expect(JSON.stringify(safe)).not.toContain("private");
+    expect(safe.allocations[0].stack[0].column).toBe(32);
+  });
+  it("caps retained files across restarts and removes abandoned temporary files", async () => {
+    const directory = await mkdtemp(join(tmpdir(), "cli-memory-test-"));
+    directories.push(directory);
+    const f = fixture();
+    await f.recorder.start();
+    await f.recorder.sample();
+    const record = f.write.mock.calls[0]![0];
+    await writeFile(join(directory, ".memory-abandoned.tmp"), "old");
+    for (let i = 0; i < 24; i++)
+      await writeMemoryDiagnostic(directory, {
+        ...record,
+        instanceId: randomUUID(),
+        timestamp: Date.now() + i,
+      });
+    const names = await readdir(directory);
+    const files = names.filter((name) => name.endsWith(".jsonl"));
+    expect(files).toHaveLength(CLI_MEMORY_MAX_FILES);
+    expect(names.some((name) => name.endsWith(".tmp"))).toBe(false);
+    for (const name of files) {
+      expect((await stat(join(directory, name))).size).toBeLessThanOrEqual(
+        CLI_MEMORY_MAX_FILE_BYTES,
+      );
+      expect(
+        sanitizeCliMemoryDiagnostic(JSON.parse(await readFile(join(directory, name), "utf8"))),
+      ).not.toBeNull();
+    }
+    for (let i = 0; i < 12; i++) await writeMemoryDiagnostic(directory, record);
+    const finalNames = await readdir(directory);
+    expect(
+      finalNames.filter((name) => name.endsWith("-" + record.instanceId + ".jsonl")).length,
+    ).toBeLessThanOrEqual(2);
+    expect(finalNames.filter((name) => name.endsWith(".jsonl")).length).toBeLessThanOrEqual(
+      CLI_MEMORY_MAX_FILES,
+    );
+  });
+});

+ 4 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/v4-gateway.ts

@@ -3055,6 +3055,10 @@ export class ConversationV4Gateway {
       detachedLive: this.detachedLiveSessions.size,
       detachedTerminal: this.detachedTerminalAt.size,
       rawSeqStates: this.rawSequenceStates.size,
+      hydrations: this.hydrationInFlight.size,
+      historyOpenings: this.historyOpenings.size,
+      binaryCacheEntries: this.binaryReadCache.size,
+      binaryCacheBytes: this.binaryReadCacheBytes,
     };
   }
 

+ 16 - 1
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/resource-sampler.ts

@@ -1,4 +1,5 @@
 import type { Logger } from "@zcode/contracts";
+import { startCliMemoryDiagnostics } from "@zcode/adapters/memory-diagnostics";
 import {
   createMemorySampleWriteGate,
   memoryUsageToSampleFields,
@@ -59,7 +60,21 @@ export function startProtocolResourceSampler(
       },
     });
     sampler.start();
-    return sampler;
+    let diagnostics: { stop(): void } | undefined;
+    try {
+      diagnostics = startCliMemoryDiagnostics(() =>
+        server.collectMemoryDiagnostics({ includeEventStats: false }),
+      );
+    } catch {
+      // inspector 不可用时不能影响协议握手和既有资源采样。
+    }
+    return {
+      start: () => sampler.start(),
+      stop: () => {
+        diagnostics?.stop();
+        sampler.stop();
+      },
+    };
   } catch {
     // 资源遥测是 best effort,初始化失败不能改变 Agent 启动结果。
     return undefined;

+ 14 - 15
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server.ts

@@ -424,25 +424,24 @@ export class ZCodeProtocolAgentServer {
   }
 
   /**
-   * 内存诊断计数器,随 60s 资源采样写本地日志。
-   * 只读 Map.size / 数组长度,不触碰 session 状态;持久化 event store 不提供 getStats 时计 0。
+   * 内存诊断计数器;完整事件统计沿用 60s 周期,不触碰 session 状态。
+   * getStats 会扫描历史事件,15s 分配诊断必须跳过,避免长对话因采集增加 CPU 开销。
    */
-  collectMemoryDiagnostics(): Record<string, number> {
-    let eventRows = 0;
-    let eventEvicted = 0;
-    let eventTransientRetained = 0;
-    for (const record of this.context.sessions.values()) {
-      const stats = record.eventStore.getStats?.();
-      eventRows += stats?.events ?? 0;
-      eventEvicted += stats?.evictedEvents ?? 0;
-      eventTransientRetained += stats?.retainedTransient ?? 0;
-    }
+  collectMemoryDiagnostics(options?: { includeEventStats?: boolean }): Record<string, number> {
     const counters: Record<string, number> = {
       sessions: this.context.sessions.size,
-      eventRows,
-      eventEvicted,
-      eventTransientRetained,
     };
+    if (options?.includeEventStats !== false) {
+      counters.eventRows = 0;
+      counters.eventEvicted = 0;
+      counters.eventTransientRetained = 0;
+      for (const record of this.context.sessions.values()) {
+        const stats = record.eventStore.getStats?.();
+        counters.eventRows += stats?.events ?? 0;
+        counters.eventEvicted += stats?.evictedEvents ?? 0;
+        counters.eventTransientRetained += stats?.retainedTransient ?? 0;
+      }
+    }
     const v4 = this.context.v4Gateway?.collectMemoryDiagnostics();
     if (v4) {
       for (const [key, value] of Object.entries(v4)) {

+ 21 - 0
apps/zcode-cli/packages/bootstrap/tests/session-event-store-retention.protocol.test.ts

@@ -110,6 +110,27 @@ async function createSubscribedSession(harness: Harness): Promise<string> {
 }
 
 describe("session event store retention (protocol)", () => {
+  it("分配诊断的轻量计数不遍历历史事件,完整统计保留既有字段", async () => {
+    const h = createHarness();
+    await createSubscribedSession(h);
+    const readStats = vi.spyOn(h.stores[0]!, "getStats").mockReturnValue({
+      sessions: 1,
+      events: 23,
+      evictedEvents: 2,
+      retainedTransient: 3,
+    });
+    const cheap = h.server.collectMemoryDiagnostics({ includeEventStats: false });
+    expect(cheap.sessions).toBe(1);
+    expect(cheap).not.toHaveProperty("eventRows");
+    expect(readStats).not.toHaveBeenCalled();
+    expect(h.server.collectMemoryDiagnostics()).toMatchObject({
+      sessions: 1,
+      eventRows: 23,
+      eventEvicted: 2,
+      eventTransientRetained: 3,
+    });
+    expect(readStats).toHaveBeenCalledTimes(1);
+  });
   it("RET-006 record 使用注入的 event store 工厂,session/close 后调用 deleteSession", async () => {
     const harness = createHarness();
     const sessionId = await createSubscribedSession(harness);

+ 4 - 0
apps/zcode-cli/packages/bootstrap/tests/v4-gateway.test.ts

@@ -5040,6 +5040,10 @@ describe("ConversationV4Gateway.collectMemoryDiagnostics", () => {
       detachedLive: 0,
       detachedTerminal: 0,
       rawSeqStates: 0,
+      hydrations: 0,
+      historyOpenings: 0,
+      binaryCacheEntries: 0,
+      binaryCacheBytes: 0,
     });
   });
 });

+ 2 - 2
apps/zcode-cli/packages/cli/package.json

@@ -26,7 +26,6 @@
     "lint:fix": "oxlint --write src"
   },
   "dependencies": {
-    "@napi-rs/keyring": "2.1.2",
     "@zcode/adapters": "workspace:*",
     "@zcode/bootstrap": "workspace:*",
     "@zcode/contracts": "workspace:*",
@@ -38,6 +37,7 @@
     "@zcode/shared-types": "workspace:*",
     "@zcode/tui": "workspace:*",
     "dotenv": "^17.4.2",
-    "playwright-core": "1.59.1"
+    "playwright-core": "1.59.1",
+    "@napi-rs/keyring": "2.1.2"
   }
 }

+ 18 - 0
architecture-policy.yaml

@@ -1812,6 +1812,24 @@ modules:
       ui: .
     owner: conversation
 
+  # cli-memory-diagnostics:由 architecture:adopt 登记
+  - id: cli-memory-diagnostics
+    roots:
+      - apps/zcode-cli/packages/adapters/src/memory-diagnostics
+      - apps/zcode-cli/packages/adapters/tests/memory-diagnostics
+      - apps/zcode-cli/packages/bootstrap/src/zcode-protocol/resource-sampler.ts
+      - packages/services/src/feedback/feedbackLogArchive.ts
+    managed: true
+    requires: [shared, zcode-cli]
+    publicEntrypoints:
+      - apps/zcode-cli/packages/adapters/src/memory-diagnostics/index.ts
+      - apps/zcode-cli/packages/adapters/src/memory-diagnostics/contract.ts
+      - apps/zcode-cli/packages/bootstrap/src/zcode-protocol/resource-sampler.ts
+      - packages/services/src/feedback/feedbackLogArchive.ts
+    layers:
+      adapters: .
+    owner: agent
+
 global:
   # 临时时间戳(2026-09-10):unmanaged-new-file 只约束此日期之后首次入库的文件。
   # 基于领先 staging 很多的分支开工时,merge-base 之前的"新增"文件不应被追溯。

+ 3 - 3
docs/browser-use/2026-11-03-browser-design-mode-spec.md

@@ -50,7 +50,7 @@
   且有 `:root` / `html` 规则里的 CSS 变量、`[data-variant]` 或 `section.slide`。普通网站很多也声明 `:root` 变量,所以这三项只对本机页面看。
 - 人类 tab 的地址栏「选择元素」在任何页面上都是同一套点选(再点一次或页面里 Esc 退出),取代原来的元素选择器
   (11-06 产品决定:一个按钮一套逻辑;原来的选择器只给模型元素信息,新点选同样给,还能直接改)。
-  选中后进完整视图、右上浮出「调整面板」;能不能改由页面决定:本机 HTML 文件在面板里改并写回源码,
+  选中后不切布局(对话保持左右分栏,11-11 用户反馈);设计稿页面右上浮出「调整面板」,普通网页只把元素加进输入框、不出面板;能不能改由页面决定:本机 HTML 文件在面板里改并写回源码,
   其他页面(普通网站、localhost 开发服务)面板只读,提示「这里只能查看,想改的话在输入框里告诉 Agent」。
 - 设计稿页面另外出设计工具行(方案、翻页、调整面板开关)、深色点阵画布和舞台式去框;普通网页不出。
 - Agent 的 Browser Use tab:仍是原来的元素选择器(点一个元素,输入框上方出「N 个网页元素」标签)。
@@ -98,7 +98,7 @@
 1. 「调整面板」(11-06 由「设计」改名:「设计」读不懂)是悬浮在画布右上的卡片(`BrowserDesignInspector`,不撑满一列,高度随内容、超出时内部滚动,11-05 反馈),
    照 Figma 的 Design 面板:
    标题是元素类型(区块 / 文字 / 按钮…,多选「已选 N 个」),分区为 布局(W × H 只读、四边内边距)/ 外观(不透明度、圆角)/
-   文字(字重、字号、对齐,按钮另有文字颜色)/ 填充(文字类元素是文字颜色,其余是背景)/ 变量;字段常显边框,悬停 / 聚焦时边框变色。点中元素时打开(关过也会重新打开;刚进点选、还没选中时不开),工具行按钮开关。面板只在完整视图里出:半屏里面板要出来(选中元素)就自动进完整视图,退出完整视图或退出点选时面板收起(不支持完整视图的端退回成面板盖在画布右侧)。面板开着时原型的大小和位置都不变(每种预设都按整页 Fit、在画布里居中),面板浮在画布右上;画布窄于 720px 时面板 256 → 192px,少挡原型。用户退出完整视图后在半屏里再选元素会再次进完整视图:半屏放不下原型 + 面板,又不缩小原型,面板只能在完整视图里用(11-05 用户反馈后的产品决定)。能写回是默认情况,面板不额外说明;只在写不回时写明原因。
+   文字(字重、字号、对齐,按钮另有文字颜色)/ 填充(文字类元素是文字颜色,其余是背景)/ 变量;字段常显边框,悬停 / 聚焦时边框变色。点中元素时打开(关过也会重新打开;刚进点选、还没选中时不开),工具行按钮开关。选中元素不进完整视图(11-11 用户反馈:对话被挤成右下角浮窗看不到内容);半屏里面板浮在画布右侧,退出点选时收起。面板开着时原型的大小和位置都不变(每种预设都按整页 Fit、在画布里居中),面板浮在画布右上;画布窄于 720px 时面板 256 → 192px,少挡原型。需要更大的画布时用户自己进完整视图(11-05 曾改成选中即进完整视图,11-11 撤回)。能写回是默认情况,面板不额外说明;只在写不回时写明原因。
    有选中时上半部分是元素属性,下半部分是页面变量;没有选中时只有页面变量。数值为主、不用滑杆(设计师对数字敏感)。
 2. 元素属性(多选时显示最后点的那个元素的值,改动作用于全部选中元素):
    - 数字框:输入后回车 / 失焦提交,↑↓ 微调(Shift × 10),拖左侧标签改值。
@@ -192,7 +192,7 @@ writeDesignSourceFile(expected = 读到的内容) ──文件变了──▶ 
 ## 验收
 
 - 只有地址栏「选择元素」一个入口,人类 tab 所有页面同一套点选。设计稿页面:深色点阵画布、设计工具行,选中后右上弹出调整面板、数值能改;
-  普通网页:没有设计工具行,点选同样进输入框成 token(不再出原来的元素标签)、进完整视图,调整面板只读并说明交给 Agent。
+  普通网页:没有设计工具行,点选同样进输入框成 token(不再出原来的元素标签),不弹调整面板(11-11 用户反馈:只想把元素加进聊天,面板挡页面)。
 - 设计稿页面点一个元素 → 输入框正文末尾出现一个元素 token(图标同「选择元素」),光标落在它后面,可以前后穿插文字;
   Shift + 点另一个 → 再多一个 token;再普通点第三个 → 只剩它的 token。
 - 在正文里删掉 token → 对应引用移除、页面取消选中;撤销不会把已删引用的 token 带回来(引用的截图和页面信息已丢);

+ 65 - 11
docs/chat/composer-voice-input.md

@@ -82,22 +82,72 @@
 
 ### 失败
 
-所有失败都回到空闲状态,用 toast 提示用户,并写入后台日志。已写入的语音文字保留为普通文本。失败后不自动重试。
+所有失败都回到空闲状态,用 toast 提示用户(macOS / Windows 的权限被拒改用引导浮层,见「麦克风权限」),并写入后台日志。已写入的语音文字保留为普通文本。失败后不自动重试。
 
 #### 麦克风权限
 
 点击按钮后,先由 main 进程检查系统权限,再调用 `getUserMedia`。系统权限状态来自 `systemPreferences.getMediaAccessStatus("microphone")`,macOS 和 Windows 支持,Linux 不支持。
 
-| 系统    | 判定                    | 处理                                                                                                                                        |
-| ------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
-| macOS   | `not-determined`        | 调用 `askForMediaAccess("microphone")` 弹出系统授权。用户允许则继续,拒绝按 `denied` 处理                                                   |
-| macOS   | `denied` / `restricted` | toast 带「打开系统设置」按钮,打开 `x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone`                             |
-| Windows | `denied`                | toast 带「打开系统设置」按钮,打开 `ms-settings:privacy-microphone`。提示文字说明需要同时打开「麦克风访问权限」和「允许桌面应用访问麦克风」 |
-| Linux   | 无系统权限接口          | 不预检。`getUserMedia` 失败时按下面的设备错误处理                                                                                           |
+| 系统    | 判定                    | 处理                                                                                                                                             |
+| ------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
+| macOS   | `not-determined`        | 调用 `askForMediaAccess("microphone")` 弹出系统授权。用户允许则继续,拒绝按 `denied` 处理                                                        |
+| macOS   | `denied` / `restricted` | 显示权限引导浮层(见下文),提供「重新授权」和「打开系统设置」                                                                                   |
+| Windows | `denied`                | 显示权限引导浮层,只提供「打开系统设置」(`ms-settings:privacy-microphone`)。文字说明需要同时打开「麦克风访问权限」和「允许桌面应用访问麦克风」 |
+| Linux   | 无系统权限接口          | 不预检。`getUserMedia` 失败时按下面的设备错误处理,只用 toast 提示                                                                               |
 
 系统权限显示已允许,但 `getUserMedia` 抛出 `NotAllowedError` 时,按该系统的 `denied` 处理(Windows 关闭「允许桌面应用访问麦克风」时可能出现这种情况)。
 
-用户从系统设置返回后,需要再次点击按钮。客户端不轮询权限状态。macOS 修改麦克风权限后,部分系统版本要求重启应用,提示文字中说明这一点。
+##### 权限引导浮层
+
+macOS 的麦克风列表没有「+」按钮,只有请求过权限的 App 才会出现在列表里。用户点过「不允许」,或系统没有弹框就拒绝(签名身份变化、旧版本缺少 entitlement 等),`askForMediaAccess` 都不会再弹框。用户可能在设置页里找不到 ZCode。所以 macOS 提供「重新授权」:只重置 ZCode 自己的麦克风记录,再请求一次,让系统重新弹框。
+
+浮层挂在麦克风按钮上(`Popover`,`bg-popover`、`rounded-xl`),不自动消失。点击浮层外部或按 Escape 关闭。浮层打开和关闭都不移动焦点:焦点和光标留在输入框,与「点击按钮不抢输入框焦点」一致。
+
+```text
+macOS                                                         Windows
+┌──────────────────────────────────────────┐                  ┌──────────────────────────────────┐
+│ 需要麦克风权限                            │                  │ 需要麦克风权限                    │
+│ 点击「重新授权」,在系统弹框中选择「允许」 │                  │ 同时打开「麦克风访问权限」和……    │
+│              [打开系统设置] [重新授权]    │                  │                    [打开系统设置] │
+└──────────────────────────────────────────┘                  └──────────────────────────────────┘
+```
+
+「重新授权」的流程全部在 main 进程完成:
+
+```text
+renderer 点击「重新授权」
+  │  IPC zcode:reset-microphone-access
+  ▼
+main:读取当前状态
+  ├─ granted(例如用户已在系统设置里打开)───────────────▶ granted(不执行 tccutil)
+  ├─ restricted(MDM 管控)──────────────────────────────▶ failed
+  ├─ 打包版:/usr/bin/tccutil reset Microphone <bundle id> ── 失败 ─▶ failed
+  │   (bundle id 读自当前 App 的 Info.plist;开发版跳过这一步)
+  ▼
+main:重新读取状态
+  ├─ granted ───────────────────────────────────────────▶ granted
+  ├─ not-determined ─▶ askForMediaAccess ─▶ 系统弹框 ─┬─ 允许 ▶ granted
+  │                                                    └─ 拒绝 ▶ denied
+  └─ 仍是 denied(当前进程仍沿用旧的授权结果)──────────────▶ restart-required
+```
+
+| 结果               | 浮层                                                                                                    |
+| ------------------ | ------------------------------------------------------------------------------------------------------- |
+| `granted`          | 关闭浮层,toast 提示「已开启麦克风权限」。不自动开始录音,用户再次点击按钮开始                          |
+| `denied`           | 保持浮层内容不变                                                                                        |
+| `restart-required` | 浮层改为「需要重启 ZCode」,提供「重启 ZCode」(`DesktopCommandIds.RelaunchApp`)。重启后点击按钮会弹框 |
+| `failed`           | 打开系统麦克风设置页,浮层保持                                                                          |
+
+- 只重置 ZCode 自己 bundle id 的麦克风记录,不影响其他 App 和其他权限。用户仍需在系统弹框中点「允许」,不会绕过用户的选择。
+- 开发版(未打包)的 bundle id 是所有未改名 Electron 共用的 `com.github.Electron`,TCC 记录按路径保存,按 bundle id 重置无效,还会影响其他项目,所以跳过 `tccutil`,只做后面的状态判断。
+- 是否需要重启由重置后的状态决定,不用超时或计时判断:仍是 `denied` 说明当前进程读不到重置结果。
+- 已经是 `granted` 时不重置,避免删掉用户刚给出的授权。
+- 重置在 main 进程串行:上一次「重新授权」还没结束时,后来的请求(例如分屏的另一个输入框)直接等待同一次结果,不会同时执行 `tccutil` 或请求系统授权。
+- 开发版跳过 `tccutil`,状态仍是 `denied` 时同样返回 `restart-required`,但重启后仍是 `denied`。这只影响开发版;保留这条路径是为了让 E2E 能覆盖「需要重启」的浮层。
+- 「重启 ZCode」失败时写 `warn` 日志,浮层保持。
+- 浮层打开时,窗口重新获得焦点(`window` 的 `focus` 事件)就再检查一次权限。结果是 `granted` 时关闭浮层,并 toast 提示「已开启麦克风权限」。这是事件触发,不轮询。用户在系统设置里打开开关后回到 ZCode,浮层会自动关闭。
+- macOS 在系统设置里修改权限后,当前进程有时仍读到旧状态。此时用户再点「重新授权」会进入 `restart-required`,重启后生效。
+- 日志:main 的 `info` 记录重置结果(`reset microphone access result=…`),`tccutil` 失败记 `warn`。不记录 bundle id 以外的路径信息。
 
 #### 设备与采集
 
@@ -195,7 +245,7 @@ Renderer(packages/ui)                       Window Host(packages/services
 
 - macOS `Info.plist` 声明 `NSMicrophoneUsageDescription`。
 - macOS entitlements 声明 `com.apple.security.device.audio-input`(hardened runtime 下缺少该项会采集到静音)。
-- 权限检查、授权请求和打开系统设置页都在 main 进程完成,renderer 通过 `IPlatformService` 的可选能力调用。各系统的处理见「失败 / 麦克风权限」。打开设置页只允许本文列出的固定地址。
+- 权限检查、授权请求、重新授权和打开系统设置页都在 main 进程完成,renderer 通过 `IPlatformService` 的可选能力调用。各系统的处理见「失败 / 麦克风权限」。打开设置页只允许本文列出的固定地址;重新授权只执行固定的 `/usr/bin/tccutil reset Microphone <当前 App bundle id>`,renderer 不能传参数。
 
 ## 验收
 
@@ -214,7 +264,10 @@ E2E:`packages/desktop/test/e2e/ui-shell/composer/composer-voice-input.test.ts`
 | VI-12 | 用户在语音文字后追加输入、等待最终结果时按 Escape:只删除语音文字,保留用户输入和光标,迟到的结果不写回         |
 | VI-03 | ticket 429 `rate_limited` 提示                                                                                  |
 | VI-04 | `completed` 空文本提示                                                                                          |
-| VI-05 | 系统权限被拒提示,按钮打开系统麦克风设置(macOS / Windows)                                                     |
+| VI-05 | 系统权限被拒显示引导浮层,「打开系统设置」打开系统麦克风设置(macOS / Windows),不申请 ticket                  |
+| VI-15 | macOS「重新授权」:重置后状态变为未询问,系统弹框允许后关闭浮层并提示已开启                                     |
+| VI-16 | macOS「重新授权」:重置后仍是 `denied`,浮层改为「需要重启 ZCode」                                              |
+| VI-17 | 浮层打开时窗口重新获得焦点,权限已开启则关闭浮层                                                                |
 | VI-13 | 经 HTTP 代理:ticket 成功,代理在 WS 握手后丢弃数据帧并断开,提示代理问题,Host 日志记录 `opened` 与 `viaProxy` |
 | VI-14 | 经 HTTP 代理:服务端在 WS 握手阶段返回 403,提示通用失败而不是代理问题,Host 日志 `opened=false`                |
 
@@ -226,6 +279,7 @@ E2E:`packages/desktop/test/e2e/ui-shell/composer/composer-voice-input.test.ts`
 - 录音中按 Cmd/Ctrl+Z:整段语音文字一次撤销。
 - 服务端返回错误或在 `completed` 前断开:回到空闲并提示。
 - 静音音频输入:提示没有检测到声音。有声音但服务端返回空文本:提示没有识别到内容。
-- macOS / Windows 拒绝权限:toast 的按钮打开对应系统设置页。Linux 设备错误:只显示文字提示。
+- macOS / Windows 拒绝权限:引导浮层的按钮打开对应系统设置页。Linux 设备错误:只显示文字提示。
+- macOS 打包版(需手动验收,E2E 跑开发版且 mock 了系统权限接口):在系统弹框中点「不允许」后,点「重新授权」能再次弹框;允许后可以录音。重置后当前进程仍读到 `denied` 时,重启 ZCode 后点击按钮能弹框。
 - 每种失败在 Host 或 UI 日志中有一条记录,日志中没有识别文本和凭据。
 - 深浅两套主题、中英文界面下按钮显示正确。

+ 16 - 0
docs/chat/reasoning-streaming-auto-collapse.md

@@ -22,6 +22,22 @@ Assistant thought / reasoning 块本身已经表达“模型正在思考”。
 - 展开的 thought 内容默认跟随底部;用户主动向上滚动离开底部后暂停吸底,用户回到底部后恢复吸底。
 - `open` 受控时尊重外部传入状态,只负责同步耗时与内容延迟卸载。
 
+## 流式摘要状态与回归(XSG03)
+
+`QueuedSummaryContent` 只管理摘要身份切换的播放状态。当前摘要 key 不变时,正文、次要内容和尾部计数从当前输入派生,不在 effect 中逐 token 复制进 React state;关闭动画、分组预览和 reduced motion 直接显示输入。原因是连续同步投影提交与 effect 内的内容复制会持续留下待处理更新,触发 React #185。
+
+```text
+相同 key 的内容更新 → 直接显示最新输入,保留同一文本节点,不重播纵向动画
+新 key → 当前项 + 两个待播项 → 300ms 切换 + 500ms 停留
+关闭动画 / reduced motion → 释放播放状态和 timer → 直接显示最新输入
+```
+
+思考块作为 flex 摘要子项时允许收缩,不能由默认最小宽度撑开内部流式视口。横向溢出检测只有在布尔值改变时才调用状态 setter;相等判断放在 dispatch 之前,不能逐 token 提交返回旧值的 updater。
+
+动画快照仅保存已提交的输入;当前项随后离开输入位置时,仍保留它最后一次已提交的正文与计数。等待项的同 key 内容更新替换原快照;队满时保留下一条,仅替换最后可插队项。关闭后重新开启动画不得恢复旧队列或闪回旧正文;组件卸载后 timer 不再推进。
+
+浏览器回归使用生产 React、真实 `ReasoningTrigger` 与连续分组,覆盖 200 次连续同步更新、独立与双层摘要、同 key 文本节点保持、非空换行/摘要 key 切换、待播项刷新/有界队列、关闭/重开/reduced motion、完成态及卸载清理。桌面和手机尺寸、深浅主题、中英文共用此合同;该回归只验展示,不把合成更新当作真实远控网络回放。
+
 ## 兼容性
 
 该变更只影响 UI 层 thought / reasoning 展示,不修改 ZCode Protocol、消息快照、desktop continuous 或 mobile replayable 语义。移动 Web 与桌面端消费同一 message parts,共用默认收起和单行原位流式摘要规则。

+ 6 - 0
docs/conversation-session-case-catalog.md

@@ -4297,6 +4297,8 @@ VP30(accepted/pending,2026-09-11):输入框项目选择器与侧栏同
 
 VP30 验证:6 个单测文件 / 54 项通过;桌面 E2E `desktop-e2e-20260911064219714-p80661-11b105212443f5cb` 1/1 通过,包含完整候选、搜索、自定义名称、零 root 进入草稿、改名/删除同步、1200/390px 明暗主题及底部入口可见性。保持 pending;远端 Host 参数与禁用态有单测,未复测真实手机/SSH/WSL GUI。`pnpm typecheck`、desktop `typecheck:e2e`、fixture check、lint(48 个既有警告、0 error)、architecture(baseline 0 / new 0)通过。
 
+VP30 搜索点击回归(2026-11-11):菜单 `no-drag` 计算样式、点击聚焦和筛选断言通过,运行 `packages/desktop/.e2e-artifacts/desktop-e2e-20261111-063949-271` 1/1 PASS;1200/390px、Zai Light/Dark 布局通过。WebDriver 点击不等同于原生鼠标命中,标题栏重叠处的原生点击和实机手机仍待人工验收。
+
 ARM01–ARM05(accepted/pending,2026-09-11):设置/数据与统计新增归档管理,虚拟项目与 Host 隔离分组、搜索/时间排序/项目筛选、单项与组/筛选结果批量取消归档/删除、确认取消与部分失败、明暗/窄屏。spec `docs/superpowers/specs/2026-09-11-archive-management.md`;pending `conversation-session-archive-management.test.ts`。复用 Host/CLI 既有命令,真实远端/手机链路待验。
 
 ARM06(accepted/pending,2026-09-15):归档分组名称右侧显示折叠箭头,默认全部收起、不挂载聊天内容;鼠标/键盘独立展开与收起,收起立即卸载行;数量、搜索和折叠组批量动作仍按全部匹配项处理。复用同一 spec 和 pending E2E,覆盖中英文/明暗/窄屏的收起与展开布局;本页状态不持久化。
@@ -6024,3 +6026,7 @@ AAP01 扩展已有 `task-list-archive-confirmation.test.ts`;AAP02 扩展已有
 `conversation-session-auto-archived-task-closes-side-pane-tabs.test.ts`;AAP04 的手机配对归档扩展
 `conversation-session-archive-management.test.ts`。其余边界使用真实 SQLite 运行验收;手机与
 独立 Source 传输覆盖须单独记录,不能以数据库隔离代替。
+
+## XSG03 流式摘要同步与动画(accepted)
+
+生产 React 中独立思考与收起组头的双层摘要连续接收 200 次同步内容更新,正文到达末尾且没有 #185。相同 key 的 primary/secondary/trailing 内容原位更新、文本节点不换、纵向动画不重播;换 key 保留真实切换动画和 300ms + 500ms 节奏,当前项冻结其最新内容,待播项刷新不丢字,队满保留下一条和最新插队项。关闭动画/reduced motion 立即显示最新输入并清空队列;重新启用不回放旧项,思考完成/卸载不留下 timer。覆盖 390px/1200px、深浅主题、中英文;使用真实共享 renderer 的浏览器候选,不声明完整 Agent 或手机 replayable 网络覆盖。

+ 9 - 5
docs/desktop/windows-installer-overhaul-spec.md

@@ -72,8 +72,8 @@ installer-completed (日志可查,完成页直接启动 `$INSTDIR\\ZCode.exe`)
 
 ### 失败与回滚
 
-- manifest cleanup 的 Delete 失败必须记录 cleanup 阶段、失败原因和卸载器 PID,并以非零退出码返回;未处理的文件保持原状;新安装器在调用旧卸载器前备份受管文件,失败时补回已删除文件。
-- 管理版本之间更新时,SHELL_CONTEXT 和 HKCU 路径的旧卸载器返回非零都由外层安装器显示清理失败信息;保留 electron-builder 的五次重试,但重试耗尽时显示清理失败、重试/取消提示;取消后恢复已删除文件,不再显示“应用无法关闭”。
+- manifest cleanup 的 Delete 失败必须记录 cleanup 阶段、失败原因和卸载器 PID,并以非零退出码返回;未处理的文件保持原状;新安装器在调用旧卸载器前尽力备份受管文件,只有完整备份成功后才在旧卸载失败时补回已删除文件。备份失败视为无备份,记录日志并继续安装;半份备份不得用于恢复。备份目录删除失败仅记录路径,不弹框阻断安装。
+- 管理版本之间更新时,SHELL_CONTEXT 和 HKCU 路径的旧卸载器返回非零都由外层安装器显示清理失败信息;保留 electron-builder 的五次重试,但重试耗尽时显示清理失败、重试/取消提示;有完整备份时取消后恢复已删除文件,备份失败被弃用后取消仅退出安装,提示必须明确说明无法自动恢复,不得承诺不存在的恢复,不再显示“应用无法关闭”。
 - 无 manifest 的历史卸载器不要求返回可分类错误,也不要求执行备份/恢复/回滚。
 - 解压、复制和目录保护的细粒度 Win32 错误链路作为后续收敛项;当前不得把它们写成已实现的强保证。
 
@@ -82,8 +82,8 @@ installer-completed (日志可查,完成页直接启动 `$INSTDIR\\ZCode.exe`)
 - 本版本交互安装器始终显示 Details 区域(覆盖 electron-builder 默认的 `nevershow`),并把安装段的 `SetDetailsPrint none` 改为 `listonly`。安装详情按顺序显示安装开始、清理阶段、解压阶段、逐项 NSIS `File` 条目、快捷方式阶段和完成收尾;进程启动、初始化事件发生在 `.onInit`,以文件日志为准。
 - 上一版本卸载器是独立进程,外层详情先显示 cleanup 开始/完成,进程返回后回放本次卸载器日志;当前版本卸载器会将 manifest 中实际尝试删除的相对路径逐项写入 `%TEMP%\\ZCode-uninstaller.log`。
 - 静默更新不显示 UI,但写 `%TEMP%\\ZCode-installer.log`;UAC 提权内层直接尝试写 `%WINDIR%\\Logs\\ZCode-installer.log`。当前没有“外层临时日志按权限复制到 Windir”的实现,日志不可写不应阻断安装。
-- 日志 marker 使用数字 PID 和阶段枚举,不写 `$CMDLINE`。当前已实现安装阶段为 `install-started`、`cleanup-started/completed`、`extract-started/completed`、`shortcuts-started/completed`、`install-finalization-started` 和 `install-completed`;managed cleanup 的失败分类限于 `permission-or-disk-space` 和旧卸载器返回非零,`reparse-point`、`extract` 的 Win32 错误码作为后续收敛项。
-- 交互式 managed 更新保留最多 5 次旧卸载器重试;重试耗尽后使用本项目的清理失败及退出码提示,用户取消后恢复已删除文件。真实应用进程检查仍使用原有“应用无法关闭”提示;静默路径以退出码和日志为准。
+- 日志 marker 使用数字 PID 和阶段枚举,不写 `$CMDLINE`。安装阶段为 `install-started`、`cleanup-started/completed`、`extract-started/completed`、`shortcuts-started/completed`、`install-finalization-started` 和 `install-completed`;managed cleanup 的文件删除失败记录相对路径及即时 Win32 错误码,不再固定归为 `permission-or-disk-space`。旧安装进程收口记录路径匹配、结束/等待/复查阶段及 PID;旧卸载器非零退出仍保留原退出码。`reparse-point`、`extract` 的细粒度诊断作为后续收敛项。
+- 交互式 managed 更新保留最多 5 次旧卸载器重试;重试耗尽后使用本项目的清理失败及退出码提示,提示按是否存在完整备份区分:有备份时承诺取消后恢复已删除文件,无备份时明确取消仅退出安装且无法自动恢复。真实应用进程检查仍使用原有“应用无法关闭”提示;静默路径以退出码和日志为准。
 - 清理失败错误框带 `/SD IDOK`,交互模式显示提示,静默模式自动确认并返回退出码 `2`,不得阻塞无人值守更新。
 
 ## 快捷方式与 AUMID
@@ -101,8 +101,12 @@ installer-completed (日志可查,完成页直接启动 `$INSTDIR\\ZCode.exe`)
 | WIN-INSTALL-OWNERSHIP-002 | 旧版本无 manifest                      | 非本轮保证;允许旧卸载器沿用原生行为,后续只在有明确收益时增加迁移支持 |
 | WIN-INSTALL-DIAG-001      | managed cleanup 遇到锁定/权限/磁盘错误 | cleanup 日志有阶段、分类和数字 PID;外层返回非零并显示清理失败         |
 | WIN-INSTALL-RECOVERY-001  | 旧卸载器先删主程序、后因文件占用失败   | 主程序原字节恢复,锁定文件与无关文件保留,退出码非零                   |
-| WIN-INSTALL-RECOVERY-002  | 备份源文件被独占打开                   | 不运行旧卸载器,原安装目录不变                                         |
+| WIN-INSTALL-RECOVERY-002  | 备份源文件被独占打开,备份后释放句柄   | 记录备份失败,弃用半份备份,旧卸载成功后仍写入新载荷、退出码为零       |
 | WIN-INSTALL-RECOVERY-003  | 已删除主程序的位置出现同名目录         | 不能声明恢复成功,保留备份并报告路径                                   |
+| WIN-INSTALL-RECOVERY-004  | 完整备份后旧卸载成功,但备份删除失败   | 日志保留备份路径,不弹框,仍写入新载荷、退出码为零                     |
+| WIN-INSTALL-RECOVERY-005  | 备份失败后旧卸载也失败                 | 不使用半份备份恢复,保留旧卸载失败退出码,不声称旧版完整               |
+| WIN-INSTALL-PROCESS-001   | 旧安装目录的 ZCode.exe 进程存活        | 句柄校验路径并终止后确认退出;旧安装目录外的同名进程保持运行           |
+| WIN-INSTALL-PROCESS-002   | 旧安装目录候选进程不能查询或结束       | 备份和卸载未开始;日志含阶段及 PID,旧版文件未改动                     |
 | WIN-INSTALL-DIAG-003      | 旧版本无 manifest 或解压阶段失败       | 非本轮细粒度诊断保证;保留原生安装器结果,后续按真实问题逐步收敛       |
 | WIN-INSTALL-DIAG-002      | 静默 `/S` 更新                         | 无 UI 但有阶段日志,日志 PID 为数字且无原始命令行                      |
 | WIN-INSTALL-SHORTCUT-001  | 正确/失效/被删除的快捷方式             | 正确项保留参数,失效项修复,删除项不重建                               |

+ 29 - 12
docs/desktop/windows-installer-preserve-files.md

@@ -32,36 +32,53 @@ managed 覆盖更新只清理由 ZCode 发行包声明拥有的文件,安装
 
 ## 旧卸载器清理失败的恢复
 
-新安装器必须在调用旧卸载器前、按该卸载器实际 `InstallLocation` 读取旧 manifest,
+新安装器必须在调用旧卸载器前,通过随包的原生 helper 按完整路径检查实际旧安装目录下的主程序进程,
+结束残留 Crashpad/renderer 等同映像进程并确认退出;不能仅按名称或父 PID 强杀。
+先用查询权限识别候选路径,只有匹配目标路径后才申请终止权限;终止句柄须重新核验路径,
+并继续用同一句柄结束和等待。其他目录的同名进程不应因拒绝终止权限阻断安装。
+无法读取候选进程路径、无法结束目标进程或复查发现残留时,在备份前停止并记录阶段、PID。
+该检查不依赖 PowerShell 或 Add-Type;日志写入是尽力操作,失败不改变进程检查结果,诊断保留在 stdout/stderr。
+随后按该卸载器实际 `InstallLocation` 读取旧 manifest,
 将仍存在的受管文件复制到安装目录同级的唯一备份目录。备份清单先单独保存一次;即使清单包含自身条目,遍历也不得再次排他复制它。
-备份完成前不得删除旧文件;
-备份失败立即停止安装,旧版保持原状。无 manifest 的历史安装继续遵守上文的 legacy 边界。
+备份尝试结束前不得删除旧文件。备份是可选保护,不是安装前置条件:
+备份失败只记录日志,尽力删除本次半份备份并弃用其恢复引用,继续运行旧卸载器和后续安装。
+半份备份不能用于恢复;清理半份备份失败时记录实际路径,不弹框、不退出。
+无 manifest 的历史安装继续遵守上文的 legacy 边界。
 
-旧卸载器非零退出时,从备份恢复被删除的文件;尚存的原文件不覆盖,避免再次触碰锁定文件。
+旧卸载器非零退出时,仅在完整备份成功的情况下恢复被删除的文件;尚存的原文件不覆盖,避免再次触碰锁定文件。
+本次没有完整备份时不尝试恢复,也不声称旧版完整,沿用旧卸载器失败的错误处理。
 恢复时按备份中仍存在的文件校验相对路径;Windows NSIS 的路径规范化可能对已删除的目标返回空值,
 不得因此跳过待恢复文件或误报恢复成功。
 恢复成功后清理备份并报告清理失败;恢复失败保留备份路径并报告,不能声称旧版已完整恢复。
-旧卸载器成功后移除本次清理备份。该保护针对卸载清理阶段,不承诺后续解压失败或断电的完整安装事务。
+旧卸载器成功后移除本次清理备份。删除失败必须保留备份路径并记录 `cleanup-backup-delete-failed`,
+只记录日志,不弹框阻断安装,也不能声称已删除;半份备份删除失败同样记录路径,但必须弃用恢复引用。不枚举或通配删除安装目录同级的
+`ns*.tmp`,因为不能据名称证明其所有权。安装器被强杀、断电后的历史备份回收不属于本轮保证。
+该保护针对卸载清理阶段,不承诺后续解压失败或断电的完整安装事务。
 
 ```text
-旧 InstallLocation + manifest → 完整备份 → 运行旧卸载器
-                                  │          ├─成功 → 删除备份 → 解压新包
-                                  │          └─失败 → 补回已删文件 → 报清理失败
-                                  └─失败 → 原安装目录不变,停止
+旧 InstallLocation → 进程句柄收口 + 二次枚举 → 尝试 manifest 备份 → 运行旧卸载器
+                       │                          │             ├─成功 → 尽力删除备份 → 解压新包
+                       │                          │             └─失败 → 有完整备份才恢复 → 报错
+                       │                          └─失败 → 记录日志、弃用半份备份,继续旧卸载
+                       └─失败 → 原目录未删除、未备份,报告 PID 与阶段
 ```
 
 旧卸载器重试耗尽的提示必须描述清理失败和退出码,不得用“应用无法关闭”替代;
-只有真实进程检查失败才继续使用该提示。保留交互式重试/取消;取消后恢复已删除文件,静默安装默认取消。两种路径都保留安装器日志。
+只有真实进程检查失败才继续使用该提示。保留交互式重试/取消;提示按是否存在完整备份区分:
+有备份时承诺取消后恢复已删除文件,备份失败被弃用后取消仅退出安装,提示必须明确说明无法自动恢复,
+不得承诺不存在的恢复。静默安装默认取消。两种路径都保留安装器日志。
 重试提示与取消后的最终清理失败提示均跟随安装器语言,不能在英文安装流程末尾固定显示中文。
 
 验收使用隔离安装目录:清单中先放主程序、再放可删除文件、最后放被独占打开的文件。
 运行旧卸载器后断言非零、前两项字节恢复、锁定文件不变、无关文件不变;释放句柄后重试
-能够完成清理。另测备份写入失败、无 manifest、成功清理、恢复目的目录不可写及重试耗尽提示。
+能够完成清理。另测备份写入失败后释放故障句柄,旧卸载和新载荷写入仍成功;
+无完整备份且旧卸载失败时不恢复半份备份;成功清理后备份删除失败也继续写入新载荷。
+另测无 manifest、成功清理、恢复目的目录不可写及重试耗尽提示。
 
 自引用清单回归须包含正常清理、备份后旧卸载器失败的恢复,以及成功清理后删除备份。
 
 ### 旧卸载器的清单自引用兼容
 
-旧完整包的卸载器可能未跳过正在读取的清单自身。新安装器须先保留原清单与受管文件,成功备份后为旧卸载器原子替换一份仅移除自引用项的清单;备份或替换失败则不得开始旧卸载。清理失败时恢复原始清单字节,即使清单文件仍存在。完整包回归包含原始旧卸载器的自引用清单升级,以及失败后的原清单逐字节一致性。
+旧完整包的卸载器可能未跳过正在读取的清单自身。新安装器须先保留原清单与受管文件,成功备份后为旧卸载器原子替换一份仅移除自引用项的清单;备份或替换失败则弃用本次备份并继续旧卸载,不承诺该次恢复保护。完整备份成功且清理失败时恢复原始清单字节,即使清单文件仍存在。完整包回归包含原始旧卸载器的自引用清单升级,以及失败后的原清单逐字节一致性。
 
 本轮隔离 Windows 11 x64 完整包验证:原版 3.16.2 的清单加入自引用后,旧实现升级返回 2;修复后的完整 NSIS 安装包在自动更新清理失败时恢复 1,430 个文件及原清单字节,随后原版升级成功,再次用包含自引用的新清单覆盖安装成功。受管主程序、app.asar、工具均与完整载荷哈希一致,无关文件保留,成功后临时备份清除。安装器未配置正式签名,此结果不代表正式签名信任链、断电或解压失败回滚。

+ 21 - 4
docs/desktop/windows-update-install-handoff.md

@@ -18,14 +18,26 @@ update-downloaded
   -> 最多等待 9 秒(7.5 秒触发强制结束)
   -> 实时扫描仍引用随包资源的 runtime,并对匹配进程执行 taskkill
   -> electron-updater.quitAndInstall()
-  -> NSIS CHECK_APP_RUNNING 做最终安装目录进程检查
-  -> NSIS 覆盖安装并保留已有快捷方式身份
+  -> NSIS CHECK_APP_RUNNING 做现有的安装目录进程检查
+  -> 解析旧安装目录后,在备份前再次检查同目录 ZCode.exe 残留并确认退出
+  -> NSIS 读取旧安装目录 manifest 并按所有权备份
+  -> 运行旧卸载器清理旧版本
   -> 完成页直接启动新安装目录下的 ZCode.exe
 ```
 
 Main 进程不能在调用 `quitAndInstall()` 前按整个安装目录杀进程,因为 renderer、GPU
-和当前 main 自身也从该目录运行。Main 只负责自己拥有的 host/agent/runtime;当前应用
-退出后的最终安装目录检查继续由 NSIS 原生 `CHECK_APP_RUNNING` 负责。
+和当前 main 自身也从该目录运行。Main 只负责自己拥有的 host/agent/runtime;安装器启动后
+按旧安装目录收口 ZCode.exe 进程,包括独立存活的 Crashpad handler。只按进程名匹配不安全,
+安装器随包的原生 helper 必须先以查询权限读取完整映像路径,仅对目标目录的进程申请终止权限,
+并在用于终止和等待的同一句柄上重新核对路径,避免 PID 复用或其他目录的同名进程权限不足误阻断更新。
+结束后再枚举确认无残留。若候选路径无法查询、目标进程无法结束或复查失败,安装器停止旧版本清理并记录阶段、
+进程名及 PID;独立诊断日志写入失败不能改变检查结果,stdout 仍返回诊断。
+检查不依赖 PowerShell、Add-Type 或其他动态编译环境。
+
+旧卸载器清理前的最终检查位于 `uninstallOldVersion` 已解析旧安装目录后的备份 hook,
+同时覆盖自动更新和手动覆盖安装。现有 `CHECK_APP_RUNNING` 保持不变;本次不能证明它
+漏检的原因。最终检查不依赖父进程是否存活、PowerShell 是否可用或动态编译权限;二次枚举只验证,若进程
+仍存活则阻断。查询失败时必须阻断清理,不能解释为无残留。
 
 ## 行为约束
 
@@ -54,6 +66,8 @@ Main 进程不能在调用 `quitAndInstall()` 前按整个安装目录杀进程
   `taskkill`。
 - 不绕过 NSIS 的最终运行中应用检查;该检查不承诺覆盖所有独立 runtime。产品接受极少数
   runtime 持续占用时安装资源可能不完整的残余风险,并通过新版本启动完整性诊断保留证据。
+- 旧卸载器进程收口:按完整映像路径和旧安装目录识别主程序及 Crashpad handler;结束与确认使用同一进程句柄;二次枚举发现重生、访问拒绝或查询失败时在备份前中止并记录 PID 与阶段。
+- 注册表写入安装信息键和卸载项时都写入实际 `$INSTDIR` 的 `InstallLocation`,兼容通过 `UninstallString` 回退旧路径的历史安装。
 - 覆盖更新保留用户“是否创建快捷方式”的选择:用户已删除的快捷方式不重新创建。
 - 手动运行安装包覆盖已有版本(包括版本降级)时没有 `--updated` 参数。electron-builder 26.8.1
   在允许修改安装目录的 assisted installer 中会因此跳过 `KeepShortcuts`,旧卸载器继而调用
@@ -125,6 +139,9 @@ Main 进程不能在调用 `quitAndInstall()` 前按整个安装目录杀进程
 
 - Windows 覆盖更新:本地/Remote Host 正常退出、Host 需要强制退出、随包 runtime 子进程
   残留,以及 PowerShell 查询进程不得匹配自身。
+- NSIS 安装目录进程检查:孤儿 Crashpad handler 在旧 ZCode.exe 仍加载时必须被找到并退出;
+  其他安装目录的同名进程不得被结束;查询/结束/复查异常时安装器不得开始旧卸载清理。
+- Windows 注册表:安装成功后安装信息键和卸载项的 `InstallLocation` 均指向实际安装目录。
 - 快捷方式:开始菜单/桌面快捷方式目标正确、目标失效或被用户删除;只允许修复失效 `.lnk`。
 - 完成页:存在旧 `.lnk` 时仍从新安装目录直接启动 exe。
 - 原子写锁:同目标并发写、owner 崩溃留下新锁、超过 stale 阈值的锁、旧锁等待期间被新

+ 4 - 3
docs/dynamic-workflow/launch.md

@@ -1082,6 +1082,8 @@ These places do not show the window, on purpose:
 
 ## Permissions inside a run
 
+来源显示为标题下方的独立描述,使用 `text-ui-base` 和次级文字色,不显示胶囊边框。完整名称自动换行,连续长标识也在容器内折行,不截断、不显示省略号。原生 title 保留来源类型。权限与提问共用此描述,深浅主题、桌面与窄屏遵循同一规则。
+
 A run's subagents work in the permission mode of the session that launched the run: Build,
 Edit, YOLO, Guarded or Auto. A subagent asks the user whenever the main agent would ask for
 the same tool call in that mode: an edit or a command in Build, a dangerous command in Guarded
@@ -1111,9 +1113,8 @@ twice). Only these interaction events are mirrored; the subagent's tool activity
 own transcript and on the run card. The request carries an `origin` of kind `subagent`
 with the subagent's session id, and a `description` of the form `<name> (<siteId>@<ordinal>)`,
 `<name>` being the subagent's persona name, or `subagent` when it has none. The permission
-dialog shows the origin badge with that description: "Subagent · reviewer (agent#2@1)" /
-「子智能体 · reviewer (agent#2@1)」. The badge truncates a long description and keeps the whole
-text in its tooltip.
+dialog shows the origin description below its heading: "Subagent · reviewer (agent#2@1)" /
+「子智能体 · reviewer (agent#2@1)」. The description wraps below the heading without truncation; its title also retains the origin type.
 
 The dialog offers what the same ask from an ordinary subagent offers. Full access is never
 offered on a subagent's ask. A Guarded

+ 86 - 38
docs/monitoring/memory-diagnostics-log.md

@@ -2,6 +2,54 @@
 
 状态:**已确认,按本 spec 实现**
 
+## CLI 分配诊断(3.18.1)
+
+在下述 60 秒基础日志之外,CLI app-server 就绪后启用独立、有界的诊断记录。
+目的是关联内存增长与发布代码位置,不改变任务调度、恢复或模型行为。
+
+- CLI adapter 是采集和文件留存的唯一 owner。Bootstrap 只提供只读计数器并随 runtime 停止采集。
+- 每 15 秒读取内存细分和只读计数,保留最近 8 个读数;只读会话数与 V4 容器大小,
+  不调用会遍历历史事件的 `eventStore.getStats()`。完整事件统计保持原有 60 秒周期,
+  不遍历消息正文、不重新序列化业务对象。
+- 使用进程内 inspector Session,不开放调试端口,不读取脚本源码,不生成/加载 source map,
+  不拍 heap snapshot,不主动 GC。分配采样间隔 1 MiB,栈深 16;每 60 秒重置采样窗口。
+- 每 15 秒取样,最多检查 4096 个 profile 节点,只输出前 32 个分配热点及每个热点最后 8 层栈。
+  profile 不是 retained-size/持有链,Buffer backing store 也未必反映在 JS profile 中,必须结合 external。
+- 只保存发布 bundle 的函数名与从 0 开始的行列号。其他脚本不保存路径、函数名或源码。保存 bundle SHA-256、
+  构建版本、Node/V8 版本、进程实例和 PID,便于在内部同版本产物上定位。
+- 每轮最多一个采集/写盘操作,忙时丢本轮,不排队。单次同步采样/投影超过 25ms 或节点数超限,
+  本进程永久降级为纯指标。采样异常同样降级;不得向任务抛错。启动和退出不等待磁盘采集。
+  降级后的记录保留最后一次有效热点及其采集时间,避免纯指标轮转覆盖已有证据。
+  堆使用达到上限的 80% 后同样降级,不在临近 OOM 时物化 profile。
+  写盘在途而采样窗口到期时释放 profiler,慢磁盘不能导致采样状态无限积累。
+- 所有 CLI 进程共用 `~/.zcode/cli/memory-diagnostics`:每个实例最多 2 个完成文件,全目录最多 16 个,每个 64 KiB,
+  完成文件合计不超过 1 MiB。目录锁串行执行淘汰和写入,竞争只作短暂尝试后丢本轮。
+  先淘汰再写,原子替换;锁内清理上次崩溃留下的临时文件,因此额外最多一个 64 KiB 临时文件。
+  文件超过 7 天也淘汰。JSONL 不追加,不能随运行时长或进程重启无限增长。
+- 反馈 full/compact 和手动日志导出都携带记录。反馈将此目录放在普通日志前,
+  仅接受指定文件名和结构化数字/位置字段,不能因通用正文脱敏而整段丢弃 profile;
+  不上传环境变量、对话、工具参数、配置或脚本内容。反馈未选择附带日志时,不打包或上传此目录。
+- 远端 CLI 在远端记录;本机反馈不自动下载远端诊断。手机仍复用 Host,不增加重复采集器。
+
+```text
+app-server ready → adapter 分配采样 + 15s 指标 → 有界文件(目录锁唯一写入)
+                        ↓ 60s 重置                    ↓
+                   超预算只留指标           既有反馈/日志导出 → 结构化安全投影
+runtime stop → 停表、断开 inspector;崩溃依赖此前已经写好的文件
+```
+
+验收:CLI 回归覆盖采样窗口重置、超预算降级、stop 后不再写入、慢写无排队、并发留存上限、
+过期/临时文件清理和禁止数据字段;真实运行时验证压缩 bundle 的分配位置与 Buffer 的 external
+增长;真实归档函数用合成记录验证 full/compact 携带、隐私过滤及总预算。执行同负载采样开关
+交替对比,记录 CPU/耗时和单次采集成本;不以“低采样频率”代替性能证据。
+
+本机验证(2026-11-11,macOS,随桌面端分发的 Node 24.21.0):压缩且没有 source map 的
+合成 bundle 成功记录分配位置和匹配的 SHA-256,单次检查耗时 13.8ms。8 次交替开关采样的
+同负载测试中,耗时中位数为关闭 441.9ms、开启 446.6ms(约 +1.1%),CPU 中位数没有增加。
+该短测试衡量分配采样成本,15 秒定时检查成本另行测量,不能外推为所有真实任务的性能保证。
+8 个进程竞争写入 400 次后保留 14 个有效文件、合计 10,164 字节,无残留锁或临时文件。
+真实反馈归档保留分配位置并剔除注入的正文与环境变量字段;Windows/Linux 运行时尚未验证。
+
 ## 问题
 
 用户反馈桌面端内存持续增长时,拿到日志压缩包无法回答三个问题:哪个进程在涨、涨的是
@@ -17,8 +65,8 @@ host / agent CLI 四类进程,必须先有运行时证据才能决定修哪一
 ## 产品合同
 
 1. 四类进程各自采样自己的内存:main、renderer(每窗口)、utility_host(每窗口 Local Host)、
-   agent_node(每 workspace 的 `zcode-cli`)。采样周期固定 `60_000ms`;agent_node 复用既有的
-   `process/resourceSample` sampler 节拍,不新增定时器。
+   agent_node(每 workspace 的 `zcode-cli`)。基础日志采样周期固定 `60_000ms`;agent_node 复用既有的
+   `process/resourceSample` sampler 节拍。3.18.1 的分配诊断另用上述 15 秒定时器。
 2. 采样与写盘分离。每次采样后按以下任一条件写盘,否则丢弃:
    - 首次采样(`reason=first`);
    - `heapUsedKb` 相对**上一次写盘值**变化超过 `5%`,或 `rssKb` / `externalKb` 变化超过 `10%`,或任一领域计数器
@@ -70,28 +118,28 @@ CLI 侧写结构化日志:`event=zcode_protocol.process.memory_sample`,`modu
 
 ## 领域计数器
 
-| role | provider.key | 语义 |
-| --- | --- | --- |
-| agent_node | `sessions` | 协议 server 常驻 session record 数 |
-| agent_node | `eventRows` | 全部 record 的内存 event store 行数之和 |
-| agent_node | `eventEvicted` / `eventTransientRetained` | 按 turn 窗口策略累计淘汰的瞬态事件数 / 当前仍驻留的瞬态事件数(`apps/zcode-cli/docs/design/v2/session-event-store-retention.md`) |
-| agent_node | `v4.publishers` / `v4.detachedLive` / `v4.detachedTerminal` / `v4.rawSeqStates` | V4 gateway 的 publisher、detached 子 session、已终态待释放的 detached 子 session、raw seq 状态表大小 |
-| utility_host | `agent.sessionEmitters` / `agent.seqStates` / `agent.pendingPermissions` / `agent.pendingUserInputs` | `zcodeAgentService` 的 per-session 镜像表 |
-| utility_host | `task.runtimeCommands` / `task.toolMemoryTasks` / `task.taskEmitters` / `task.overlays` | `zcodeTaskServiceAdapter` 的 per-task 表 |
-| utility_host | `terminal.open` / `fileWatcher.open` | pty 与 `fs.watch` 实例数 |
-| utility_host | `bots.streamSubs` / `bots.runningTasks` / `bots.typingIntervals` / `bots.liveStatusProgress` | bots 的 per-task 状态 |
-| main | `app.windows` / `app.willDownloadListeners` | 窗口数、`defaultSession` 上的 `will-download` 监听数 |
-| main | `taskBus.streamBatches` / `taskBus.leases` / `taskBus.sessionRoutes` | `TaskRealtimeBus` 三张表 |
-| main | `guest.tabs` / `guest.closedTabIds` | `BrowserGuestManager` |
-| main | `broadcast.claims` / `broadcast.processes` | `BroadcastHub` |
-| main | `ws.<process_role>`(`ws.main` / `ws.renderer_main` / `ws.renderer_guest` / `ws.gpu` / `ws.chromium_other` / `ws.host` / `ws.scheduler`) | `app.getAppMetrics()` 按 `process_role` 求和的 working set(KB)。角色词表与 ARMS `perf_process_window` 同源(`docs/monitoring/process-resource-telemetry.md`),只输出本 tick 有存活进程的角色 |
-| renderer | `shiki.tokensCache` / `shiki.highlighters` | 代码高亮 token 缓存条数 |
-| renderer | `taskSnapshotCache.entries` / `taskSnapshotCache.persisted` | task snapshot 内存缓存与持久缓存条数 |
-| renderer | `sessionStore.workspaces` | `zcodeSessionStore` 的 workspace 桶数 |
-| renderer | `projection.stores` / `projection.rows` | 存活的 V4 projection store 数与其 `rows.window` 行数之和 |
-| renderer | `xterm.sessions` | 常驻侧栏终端实例数 |
-| renderer | `taskQueryCache.queryKeys` / `taskQueryCache.taskMetas` | task 列表查询缓存条数 |
-| renderer | `toolLayout.openState` | 工具卡片展开状态表大小 |
+| role         | provider.key                                                                                                                              | 语义                                                                                                                                                                                            |
+| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| agent_node   | `sessions`                                                                                                                                | 协议 server 常驻 session record 数                                                                                                                                                              |
+| agent_node   | `eventRows`                                                                                                                               | 全部 record 的内存 event store 行数之和                                                                                                                                                         |
+| agent_node   | `eventEvicted` / `eventTransientRetained`                                                                                                 | 按 turn 窗口策略累计淘汰的瞬态事件数 / 当前仍驻留的瞬态事件数(`apps/zcode-cli/docs/design/v2/session-event-store-retention.md`)                                                               |
+| agent_node   | `v4.publishers` / `v4.detachedLive` / `v4.detachedTerminal` / `v4.rawSeqStates`                                                           | V4 gateway 的 publisher、detached 子 session、已终态待释放的 detached 子 session、raw seq 状态表大小                                                                                            |
+| utility_host | `agent.sessionEmitters` / `agent.seqStates` / `agent.pendingPermissions` / `agent.pendingUserInputs`                                      | `zcodeAgentService` 的 per-session 镜像表                                                                                                                                                       |
+| utility_host | `task.runtimeCommands` / `task.toolMemoryTasks` / `task.taskEmitters` / `task.overlays`                                                   | `zcodeTaskServiceAdapter` 的 per-task 表                                                                                                                                                        |
+| utility_host | `terminal.open` / `fileWatcher.open`                                                                                                      | pty 与 `fs.watch` 实例数                                                                                                                                                                        |
+| utility_host | `bots.streamSubs` / `bots.runningTasks` / `bots.typingIntervals` / `bots.liveStatusProgress`                                              | bots 的 per-task 状态                                                                                                                                                                           |
+| main         | `app.windows` / `app.willDownloadListeners`                                                                                               | 窗口数、`defaultSession` 上的 `will-download` 监听数                                                                                                                                            |
+| main         | `taskBus.streamBatches` / `taskBus.leases` / `taskBus.sessionRoutes`                                                                      | `TaskRealtimeBus` 三张表                                                                                                                                                                        |
+| main         | `guest.tabs` / `guest.closedTabIds`                                                                                                       | `BrowserGuestManager`                                                                                                                                                                           |
+| main         | `broadcast.claims` / `broadcast.processes`                                                                                                | `BroadcastHub`                                                                                                                                                                                  |
+| main         | `ws.<process_role>`(`ws.main` / `ws.renderer_main` / `ws.renderer_guest` / `ws.gpu` / `ws.chromium_other` / `ws.host` / `ws.scheduler`) | `app.getAppMetrics()` 按 `process_role` 求和的 working set(KB)。角色词表与 ARMS `perf_process_window` 同源(`docs/monitoring/process-resource-telemetry.md`),只输出本 tick 有存活进程的角色 |
+| renderer     | `shiki.tokensCache` / `shiki.highlighters`                                                                                                | 代码高亮 token 缓存条数                                                                                                                                                                         |
+| renderer     | `taskSnapshotCache.entries` / `taskSnapshotCache.persisted`                                                                               | task snapshot 内存缓存与持久缓存条数                                                                                                                                                            |
+| renderer     | `sessionStore.workspaces`                                                                                                                 | `zcodeSessionStore` 的 workspace 桶数                                                                                                                                                           |
+| renderer     | `projection.stores` / `projection.rows`                                                                                                   | 存活的 V4 projection store 数与其 `rows.window` 行数之和                                                                                                                                        |
+| renderer     | `xterm.sessions`                                                                                                                          | 常驻侧栏终端实例数                                                                                                                                                                              |
+| renderer     | `taskQueryCache.queryKeys` / `taskQueryCache.taskMetas`                                                                                   | task 列表查询缓存条数                                                                                                                                                                           |
+| renderer     | `toolLayout.openState`                                                                                                                    | 工具卡片展开状态表大小                                                                                                                                                                          |
 
 新增计数器时在对应模块用 `registry.register(name, provider)` 自注册,provider 必须是纯读取
 (只读 `Map.size` / `Set.size` / 数组长度),不得改状态、不得做 IO。
@@ -106,7 +154,7 @@ CLI 侧写结构化日志:`event=zcode_protocol.process.memory_sample`,`modu
   Web 端无桥时 no-op。UI 模块不得直接调用 `window.zcode.log`。
 - main 不用 `ps` / PowerShell 补采其他进程;只用 `process.memoryUsage()` 与
   `app.getAppMetrics()`。
-- CLI 侧每个 workspace 进程只有既有的一个 `unref()` 定时器。
+- CLI 的基础日志复用资源采样定时器;分配诊断独立持有一个 `unref()` 定时器,并随 runtime 停止。
 
 ## 如何看
 
@@ -149,16 +197,16 @@ grep memory_sample ~/.zcode/cli/log/zcode-2026-09-03.jsonl | jq -c '[.time, .con
 
 ## 验收 Case
 
-| Case ID | Setup | Action | Assertions | Layer |
-| --- | --- | --- | --- | --- |
-| MEM-001 | 空 gate | 首次 evaluate | 返回 `first` | unit |
-| MEM-002 | 上次 heap 100000 | heap 104000、计数器不变 | 返回 `null` | unit |
-| MEM-003 | 上次 heap 100000 | heap 106000 | 返回 `changed` | unit |
-| MEM-004 | 计数器某 key 变化 | evaluate | 返回 `changed` | unit |
-| MEM-005 | 全部不变 | 满 300s | 返回 `heartbeat`,之后重新计时 | unit |
-| MEM-006 | registry 有 provider 抛错 | collect | 其余 provider 正常返回,抛错者跳过 | unit |
-| MEM-007 | CLI sampler | 注入 readMemoryUsage | onSample 第二参数为完整 memoryUsage,协议样本形状不变 | unit |
-| MEM-008 | host 60s tick | 推进 timer | logger.info 一行含 `role=utility_host heapUsedKb=`;stop 后不再输出;同一次读数同时经 parentPort 发出 `HostResourceSample` | unit |
-| MEM-009 | main 6 个 10s tick | 推进 timer | logger.info 一行含 `role=main` 与 `ws.<process_role>=`;同一次读数同时作为 `perf_process_window` 的 main heap 样本 | unit |
-| MEM-010 | renderer 生产构建 | `logMemoryDiagnostics` | 仍调用桥;无桥 no-op | unit |
-| MEM-011 | renderer 60s tick | 推进 timer | 同一次读数既经 preload 桥发出 heap 样本,又按门控写本地行;门控跳过写盘的 tick 仍发样本;桥抛错不影响本地行 | unit |
+| Case ID | Setup                     | Action                  | Assertions                                                                                                                 | Layer |
+| ------- | ------------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----- |
+| MEM-001 | 空 gate                   | 首次 evaluate           | 返回 `first`                                                                                                               | unit  |
+| MEM-002 | 上次 heap 100000          | heap 104000、计数器不变 | 返回 `null`                                                                                                                | unit  |
+| MEM-003 | 上次 heap 100000          | heap 106000             | 返回 `changed`                                                                                                             | unit  |
+| MEM-004 | 计数器某 key 变化         | evaluate                | 返回 `changed`                                                                                                             | unit  |
+| MEM-005 | 全部不变                  | 满 300s                 | 返回 `heartbeat`,之后重新计时                                                                                             | unit  |
+| MEM-006 | registry 有 provider 抛错 | collect                 | 其余 provider 正常返回,抛错者跳过                                                                                         | unit  |
+| MEM-007 | CLI sampler               | 注入 readMemoryUsage    | onSample 第二参数为完整 memoryUsage,协议样本形状不变                                                                      | unit  |
+| MEM-008 | host 60s tick             | 推进 timer              | logger.info 一行含 `role=utility_host heapUsedKb=`;stop 后不再输出;同一次读数同时经 parentPort 发出 `HostResourceSample` | unit  |
+| MEM-009 | main 6 个 10s tick        | 推进 timer              | logger.info 一行含 `role=main` 与 `ws.<process_role>=`;同一次读数同时作为 `perf_process_window` 的 main heap 样本         | unit  |
+| MEM-010 | renderer 生产构建         | `logMemoryDiagnostics`  | 仍调用桥;无桥 no-op                                                                                                       | unit  |
+| MEM-011 | renderer 60s tick         | 推进 timer              | 同一次读数既经 preload 桥发出 heap 样本,又按门控写本地行;门控跳过写盘的 tick 仍发样本;桥抛错不影响本地行                | unit  |

+ 1 - 0
docs/superpowers/specs/2026-09-09-virtual-project-design.md

@@ -1148,6 +1148,7 @@ Shell active workspace + task UI -> 选中态;mobileViewState -> 手机标记
 
 ### 2026-09-11 补充:输入框项目选择器与侧栏同源
 
+- 桌面项目菜单整体排除原生窗口拖拽命中。菜单向上展开并与标题栏重叠时,搜索框仍可点击聚焦、输入和筛选;菜单外标题栏保留拖拽。Web 与手机沿用同一搜索行为。
 - 项目选择器列出侧栏完整的未删除虚拟项目,包含未打开目录、零 root、自定义名称与本机保留的远程入口;不再读取 workspace tabs,不截断为前 5 项。项目排序复用侧栏偏好;置顶项目排在普通项前,区内顺序不变。搜索文案为“搜索项目” / “Search projects”,按项目名称和 roots 搜索。
 - `project-sidebar` 的窗口级 Provider 单独持有项目树读取及偏好;侧栏与 composer 读取同一投影。Host 仍是项目、roots、远端入口的唯一权威,UI 不写库、不创建第二份项目缓存。读取错误显式显示,不退回 tabs。远端离线/未解析入口可见但不可选。
 - 选中态取草稿 `projectId` 与 workspace 的 Host 身份,同 cwd 的不同项目独立。无项目归属显示“选择项目”。选择项只调用现有 `onCreateTask({projectId, hostId})`,由 Root/Host 的 `prepareSession` 准备主要目录(零 root 自动补齐),再进入草稿;不自行按目录推断归属、不为展示项目拉起 Agent。已提交 session 的 cwd 与归属不改。

+ 6 - 0
docs/testing/conversation-session-e2e-coverage-matrix.md

@@ -4231,6 +4231,8 @@ VP30(accepted/pending,2026-09-11):输入框项目选择器与侧栏同
 
 VP30 验证:6 个单测文件 / 54 项通过;桌面 E2E `desktop-e2e-20260911064219714-p80661-11b105212443f5cb` 1/1 通过,包含完整候选、搜索、自定义名称、零 root 进入草稿、改名/删除同步、1200/390px 明暗主题及底部入口可见性。保持 pending;远端 Host 参数与禁用态有单测,未复测真实手机/SSH/WSL GUI。`pnpm typecheck`、desktop `typecheck:e2e`、fixture check、lint(48 个既有警告、0 error)、architecture(baseline 0 / new 0)通过。
 
+VP30 搜索点击回归(2026-11-11):菜单 `no-drag` 计算样式、点击聚焦和筛选断言通过,运行 `packages/desktop/.e2e-artifacts/desktop-e2e-20261111-063949-271` 1/1 PASS;1200/390px、Zai Light/Dark 布局通过。WebDriver 点击不等同于原生鼠标命中,标题栏重叠处的原生点击和实机手机仍待人工验收。
+
 ARM01–ARM05(accepted/pending,2026-09-11):设置/数据与统计新增归档管理,虚拟项目与 Host 隔离分组、搜索/时间排序/项目筛选、单项与组/筛选结果批量取消归档/删除、确认取消与部分失败、明暗/窄屏。spec `docs/superpowers/specs/2026-09-11-archive-management.md`;pending `conversation-session-archive-management.test.ts`。复用 Host/CLI 既有命令,真实远端/手机链路待验。
 
 ARM06(accepted/pending,2026-09-15):归档分组名称右侧显示折叠箭头,默认全部收起、不挂载聊天内容;鼠标/键盘独立展开与收起,收起立即卸载行;数量、搜索和折叠组批量动作仍按全部匹配项处理。复用同一 spec 和 pending E2E,覆盖中英文/明暗/窄屏的收起与展开布局;本页状态不持久化。
@@ -6988,3 +6990,7 @@ XSG02 分组原生滚动链(2026-11-09,pending-review):`packages/ui/test
 手动归档 E2E 1/1 通过,证据:`packages/desktop/.e2e-artifacts/desktop-e2e-20261110101949556-p96688-49fa1b7ffb90c01b/`。首次外置盘运行阻塞在 Electron 启动;使用源码与构建产物哈希一致的内置盘测试副本完成复跑,未更改系统权限。
 
 自动归档、归档管理(含手机配对)及运行中禁止归档共 10/10 通过,证据:`packages/desktop/.e2e-artifacts/desktop-e2e-20261110102113563-p755-750efeb9fca1c38c/`。合计 4 个文件、11 项检查全部通过。手机路径使用移动视口浏览器与真实 Host attachment,不代表实体手机或 Windows / Linux 整机验证;未变更 CI 准入范围。
+
+XSG03 流式摘要同步与动画(covered / pending-review,2026-11-11):候选 `packages/ui/test/browser/manual-review/pending/queued-summary-streaming.test.mjs` 在 macOS Chrome 的生产 React 中 16/16 通过;覆盖 390px/1200px、浅色英文/深色中文、连续 200 次增长、独立/双层摘要、同 key 节点保持、横向跟随与遮罩、换行、队列刷新/插队、动画关闭/恢复/reduced motion、完成与卸载。补充真实纵向 transform 断言后,动画 4/4 通过。加载发布基线 `692af48e` 的旧摘要组件时,同一组头用例仍因 React #185 失败。证据:`packages/desktop/.e2e-artifacts/queued-summary-streaming/` 下的 `baseline-react-185.log`、`regression-16.log`、`vertical-animation-4.log`、`stream-*.png` 与 `animation-*.json`。仅共享组件浏览器验收,不代表完整 Electron/Agent、实体手机远控或 Windows/Linux 验收;候选未晋升 formal/CI。
+
+XSG03 共享展示回归:固定最终源码后,已有 `tool-summary-groups.test.mjs` 36/36 通过,覆盖真实分享 Timeline 的分组生命周期、展开/收起、统计、文件/Bash 摘要与滚动链;日志为上述证据目录的 `groups-36.log`。一次回放因开发热更新打断滚动断言而失败,该运行不计作通过证据。

+ 10 - 6
docs/testing/desktop-auth-config-e2e-cases.md

@@ -37,11 +37,15 @@ fixture 同时覆盖换证 URL 和 `ZAI_BUSINESS_BASE_URL`,确保登录完成
 
 扩展既有 OAuth race HTTP fixture,不连接真实业务域:
 
-- 正常登录界面切换国内/全球,捕获 init 请求分别为 `zai_cn`/`zai`,中国区完整授权 URL 不重写;两次取消均不写登录态。
+- 正常登录界面切换国内/全球,捕获 init 请求分别为 `zai_cn`/`zai`;中国区保留授权站、state、client ID,只将回调改为当前环境的官网中转页并带 `provider=zai_cn`,复制链接与浏览器打开地址一致;两次取消均不写登录态。
 - 真实 Host polling 接收中国区 ready,原子保存中国区 OAuth 和 ZCode JWT、不同 ID 的关联 BigModel;全程不调用全球区业务换证接口。
 - 关联 Secret 不出现在日志,旧全球区会话字段被清理;保留旧登录协议的既有场景。
 - 中国区上游短期 token 已过期,但 ZCode JWT 仍有效时正常恢复;profile 401 或返回另一用户 ID 时保留原会话;关联密文损坏只清理关联。Renderer 不能直接读取关联私有键。
 
+`v3.18.0` hotfix 回归补充:在上述中国区场景中先投递官网 deep link,确认带归因和不带归因的授权码都不触发客户端兑换;随后释放 polling,验证主会话和关联材料落盘。polling 完成后再投递回调只更新归因,取消后的迟到回调必须拒绝。
+
+2026-11-11 macOS Electron:`auth-config/login/oauth-completion-race.test.ts` 12/12 通过,产物 `packages/desktop/.e2e-artifacts/desktop-e2e-20261110-162553-457`(目录时间为 UTC)。修复前同一中转断言已在 `desktop-e2e-20261110-162344-980` 失败:实际回调仍指向 fixture 的服务端地址。该回归使用真实 Main/Host/RPC 和合成 OAuth 服务,不代表真实上游授权、Windows/Linux 或手机 Web 已完成验收。
+
 2026-10-28 macOS Electron:三份规格共七个场景通过;最新构建来源的 WelcomeScreen sourcemap 与当前源文件一致。产物 `packages/desktop/.e2e-artifacts/desktop-e2e-20261028120903566-p6156-0de5353fd4d28b7b`。
 CLI adapters 27 项、bootstrap 9 项通过。该证据不包含真实套餐调用、MCP、手机和混版本远端;完整接入仍在实施。
 
@@ -128,7 +132,7 @@ JWT 仍按现有明确专项保留,不因为存在账号 mock 就默认注入
 
 | 字段             | 内容                                                                                  |
 | ---------------- | ------------------------------------------------------------------------------------- |
-| Spec             | `packages/desktop/test/e2e/auth-config/credentials/oauth-credential-recovery.test.ts`                         |
+| Spec             | `packages/desktop/test/e2e/auth-config/credentials/oauth-credential-recovery.test.ts` |
 | Fixture manifest | `packages/desktop/test/e2e/fixtures/cases/auth-config/oauth-credential-recovery.json` |
 | Provider fixture | 无,`providerRequestPolicy: "none"`                                                   |
 | 当前状态         | 已转正,正式路径 cold-start case                                                      |
@@ -196,7 +200,7 @@ Docker 准入暂不执行:该 case 不依赖 provider replay,也不属于 co
 
 | 字段             | 内容                                                                                         |
 | ---------------- | -------------------------------------------------------------------------------------------- |
-| Spec             | `packages/desktop/test/e2e/workspace/runtime/provider-readiness-agent-startup.test.ts`                         |
+| Spec             | `packages/desktop/test/e2e/workspace/runtime/provider-readiness-agent-startup.test.ts`       |
 | Fixture manifest | `packages/desktop/test/e2e/fixtures/cases/auth-config/provider-readiness-agent-startup.json` |
 | Provider fixture | 无,`providerRequestPolicy: "none"`                                                          |
 | 当前状态         | 已转正,正式路径 cold-start case                                                             |
@@ -252,7 +256,7 @@ Docker 准入不执行:该 auth/config case 不依赖 provider replay,也不
 
 | 字段             | 内容                                                                                    |
 | ---------------- | --------------------------------------------------------------------------------------- |
-| Spec             | `packages/desktop/test/e2e/auth-config/session/jwt-expiry-reauthentication.test.ts`                         |
+| Spec             | `packages/desktop/test/e2e/auth-config/session/jwt-expiry-reauthentication.test.ts`     |
 | Fixture manifest | `packages/desktop/test/e2e/fixtures/cases/auth-config/jwt-expiry-reauthentication.json` |
 | Provider fixture | 无,`providerRequestPolicy: "none"`                                                     |
 | 当前状态         | 候选 case,等待人工确认过期提示与重新登录入口后转正                                     |
@@ -330,7 +334,7 @@ Welcome 展示 Z.ai + BigModel 登录入口
 
 | 字段             | 内容                                                                            |
 | ---------------- | ------------------------------------------------------------------------------- |
-| Spec             | `packages/desktop/test/e2e/auth-config/session/jwt-401-auto-logout.test.ts`                         |
+| Spec             | `packages/desktop/test/e2e/auth-config/session/jwt-401-auto-logout.test.ts`     |
 | Fixture manifest | `packages/desktop/test/e2e/fixtures/cases/auth-config/jwt-401-auto-logout.json` |
 | Provider fixture | 无,`providerRequestPolicy: "none"`                                             |
 | 当前状态         | 候选 case,等待人工确认 401 触发提示、凭据清理和重启动作后转正                  |
@@ -390,7 +394,7 @@ Renderer 显示“登录已过期”
 
 | 字段             | 内容                                                                                                     |
 | ---------------- | -------------------------------------------------------------------------------------------------------- |
-| Spec             | `packages/desktop/test/e2e/coding-plan/account/subagent-coding-plan-login-catalog-stale.test.ts`                             |
+| Spec             | `packages/desktop/test/e2e/coding-plan/account/subagent-coding-plan-login-catalog-stale.test.ts`         |
 | Fixture manifest | `packages/desktop/test/e2e/fixtures/cases/auth-config/subagent-coding-plan-login-catalog-stale.json`     |
 | Provider fixture | 无模型请求;OAuth、`release/latest`、`client/configs`、套餐与 API key 接口均由 case-local HTTP mock 固定 |
 | 当前状态         | 已转正,正式路径登录后 UI 可用性与当前 Environment Model Selection 就绪 case                             |

+ 35 - 0
docs/ui/macos-font-smoothing.md

@@ -0,0 +1,35 @@
+# macOS 字体平滑
+
+设置 → 外观 → 界面字号下方显示「字体平滑」开关,仅 macOS 桌面端可见,设置搜索使用相同可见条件。默认开启(未保存及无效值均视为开启,已保存的关闭选择保持关闭)。关闭不设置字体平滑属性,由系统决定;开启应用 `-webkit-font-smoothing: antialiased`。不是关闭所有抗锯齿,不使用 `none`。
+
+说明:开启后使用灰度平滑,文字可能显得更细。效果因显示器而异。
+
+不添加独立字体预览行。切换立即生效,无须重启,主题切换不改变偏好。仅改变当前应用 DOM 文字的平滑,不承诺影响 Canvas、终端、PDF 或嵌入网页自身的渲染。
+
+## 状态与平台边界
+
+```text
+开关 → 本机 UI Store → 本机 localStorage
+                  ├→ 根元素展示标记 → 仅 macOS desktop CSS 生效
+                  └→ state: 广播 → 本机其他窗口 Store(防回环)
+重载 → 读取同一本机偏好 → 恢复展示标记
+```
+
+复用既有 Store 的偏好持久化与 BroadcastService,不写 Host 设置、不同步账号、不通过远控协议投递。非 macOS 桌面(含 Web/手机)即使存在该存储值或收到相同广播也不应用字体平滑,不显示入口。CSS 以本机 renderer 的 `platform-mac-desktop` 标记作为生效边界,不使用远端 Host 的 OS。
+
+## 验收
+
+- macOS 桌面:默认开启、开启/关闭即时改变计算样式、重载保留、设置搜索可定位。
+- 本机多个窗口:变化跟随同一偏好,收到广播不再次发送。
+- Windows/Linux/Web:入口隐藏,遗留偏好不影响计算样式。
+- 中英文、深浅主题、窄布局均可操作,说明文字不横向溢出。
+- 桌面候选用例 `settings/appearance/manual-review/pending/macos-font-smoothing.test.ts`;浏览器验收只证明组件及平台标记隔离,不等同其他操作系统 GUI 或实机手机。
+
+已验证:macOS 桌面运行 `desktop-e2e-20261111-082725-093` 1/1 通过,覆盖默认开启、设置搜索定位、关闭及重载。浏览器验收覆盖真实 Store 和外观组件的开关、多窗口广播防回环、主题/语言/宽度以及非 macOS 平台标记隔离;未测试其他操作系统 GUI 和实机手机。
+
+可重复命令(本场景不调用模型):
+
+```bash
+node --test packages/ui/test/browser/manual-review/pending/font-smoothing.test.mjs
+E2E_PROVIDER_HTTP_MODE=replay E2E_PROVIDER_REPLAY_FIXTURE_PATH=packages/desktop/test/e2e/fixtures/upstream/common.json pnpm --filter @zcode/desktop exec wdio run wdio.conf.ts --spec ./test/e2e/settings/appearance/manual-review/pending/macos-font-smoothing.test.ts
+```

+ 1 - 1
docs/ui/tool-display-rendering.md

@@ -153,7 +153,7 @@ App 与分享复用工具 renderer 注册表及分组 presentation。App 通过
 
 所有工具及 UI 合成分组的摘要不再插入装饰性中点;类别、正文、状态、计数和文件列表使用 gap-2(8px)分隔。公共摘要不提供分隔符参数。正文使用普通字重和 foreground-subtle,类别使用 font-normal;Node REPL 动作标题遵循正文层级。文件、Agent 类型及错误状态保留语义样式。用户内容、命令和详情正文中的标点不删除。桌面、手机远控及公开分享复用此规则;不改变分组算法、展开行为或摘要滚动时序。本文前述摘要示例中的中点均由此规则替换为空间间距。
 
-全局界面在 body 设置 `-webkit-font-smoothing: antialiased`,桌面与 Web 共用;保持现有字体栈、字号和行高。该属性是否生效由浏览器和操作系统决定。
+macOS 桌面默认开启灰度平滑,可在外观设置关闭以恢复系统默认;其他平台不指定 `-webkit-font-smoothing`,详见 [macOS 字体平滑](macos-font-smoothing.md);字体栈、字号和行高保持不变。
 
 思考摘要同样仅用 gap-2 分隔:思考标签与耗时、标签与流式摘要均不插入装饰性中点;不改思考正文、耗时计算及展开行为。
 

+ 11 - 16
docs/web-remote-control/mobile-task-home-design.md

@@ -554,7 +554,7 @@ pinned?: boolean;
 
 ## 状态与路由
 
-第一版不需要引入真实 URL 路由,可以在 mobile shell 内部用 React state:
+手机 Shell 持有当前视图。任务列表和聊天共用 URL;浏览器历史只用于刷新恢复和浏览器自身的前进、后退。
 
 ```text
 currentMobilePage: "home" | "chat"
@@ -562,27 +562,22 @@ currentMobilePage: "home" | "chat"
 
 进入聊天:
 
-1. 用户点击 task。
-2. task 选择成功。
-3. 设置 `currentMobilePage = "chat"`。
-4. 如果当前 history state 不是 `{ zcodeMobilePage: "chat" }`,补一层 chat history state。
+1. 用户打开任务或草稿成功后,设置 `currentMobilePage = "chat"`。
+2. 窄屏聊天显示时,在浏览器历史中记录 `zcodeMobilePage: "chat"`。初次进入聊天用 `pushState`,已标记为 `chat` 时不重复写;当前记录是箭头留下的 `home` 时,用 `replaceState` 复用这一项。
 
 返回首页:
 
-1. 点击 header 返回按钮。
-2. 如果当前 history state 是 `{ zcodeMobilePage: "chat" }`,调用 `history.back()`,由 `popstate` 回到 home。
-3. 如果当前没有 chat history state,直接设置 `currentMobilePage = "home"` 作为兜底。
-4. 保留当前 active task 的选中态。
+1. 点击页头箭头,直接设置 `currentMobilePage = "home"`,保留当前任务选中态。即使聊天是浏览器历史的第一项,也能返回列表。
+2. 若当前历史项标记为 `chat`,用 `replaceState` 原位改为 `home`,保留 URL 和该项的其他字段。刷新停留在任务列表;反复用箭头退出再打开任务不会增加历史项。
 
 浏览器返回键:
 
-1. mobile shell 初始进入 `home` 时不写 history,保留扫码入口原始历史栈。
-2. 只有用户从 `home` 点击 task 并成功进入 `chat` 时,调用一次 `history.pushState({ zcodeMobilePage: "chat" }, "")`。
-3. 如果当前已经是这层 `chat` state,不重复 push,避免同一个 task 多次点击堆叠历史。
-4. `popstate` 命中 `{ zcodeMobilePage: "chat" }` 时设置 `currentMobilePage = "chat"`;从 chat 点返回按钮时用 `history.back()` 回到 home,而不是直接改 state。
-5. `popstate` 回到非 `zcodeMobilePage` state 时设置 `currentMobilePage = "home"`,并放行浏览器后续默认返回行为。
-6. 跨 workspace task 点击成功并重新挂载 Root 后,仍按“用户点击进入 chat”的规则补一层 `chat` state;这层 state 来自点击流程的一次性 `mobileNavigationIntent`,扫码初始 `initialTaskId` 不补这层 state。
-7. mobile shell unmount 时移除 `popstate` listener。
+1. 手机 Shell 初始进入 `home` 时不写历史,保留扫码入口的历史栈。
+2. 浏览器前进或后退触发 `popstate` 后,Shell 按目标项显示界面:标记为 `chat` 时显示聊天,其余情况显示任务列表。用页头箭头回到列表后,浏览器后退仍会访问上一项;若上一项也是任务列表,界面保持在列表。
+3. 跨工作区打开任务并重新挂载 Root 后,按一次性 `mobileNavigationIntent` 显示聊天,并按相同规则同步历史。扫码初始 `initialTaskId` 只选中任务,不进入聊天。
+4. 手机 Shell 卸载时移除 `popstate` 监听。宽屏仍直接显示侧栏;本地界面切换不改变远控连接、任务归属或 replayable 交付。
+
+MRO01 返回回归:从任务列表进入聊天,用页头箭头退出并重新打开,历史长度不增长;浏览器后退到列表、前进到聊天。将当前聊天置于历史首项,再点页头箭头,保持当前 URL、立即显示列表,刷新仍停在列表。
 
 不要把 workspace/task 状态塞进 URL,避免和扫码入口及配对态互相耦合。
 

+ 1 - 1
docs/web-remote-control/web-remote-control-architecture.md

@@ -14,7 +14,7 @@
 2. 窄屏首次扫码默认进入任务首页:首页与桌面共用项目侧栏,可按项目或跨项目时间线浏览任务;
    Relay V2 连接时侧栏最顶部(“新建任务”之上)显示当前电脑行,整行点击即“切换设备”。二维码携带的初始任务用于选中和定位,不直接跳进聊天页。
 3. 点击任务进入聊天;项目或全局的新建任务入口进入对应草稿页。跨工作区操作先切换 bridge,
-   再访问目标工作区服务。返回首页保留任务选中态;聊天页刷新可以根据浏览器 history state 恢复聊天页。
+   再访问目标工作区服务。手机页头箭头直接返回首页并保留任务选中态;刷新按当前历史项恢复首页或聊天页。
 4. 手机选中的工作区和任务独立于桌面选中态,不会使桌面切换 tab/task。
 5. 网络恢复或页面回到前台时恢复连接,并按 replayable 协议重新同步任务状态;
    断开的远程工作区可从首页触发桌面已有重连流程,连接成功前不能打开或新建其中的任务。

+ 6 - 4
docs/zcode-login-rework.md

@@ -2,7 +2,7 @@
 
 状态:实施中。已完成共享会话原子提交、桌面国内/全球分流、中国区关联材料保存及恢复保护。核心套餐凭据、旧账号补关联、套餐界面及官方 MCP 公共身份头已接通;购买/奖励嵌入页与远端原子同步已实现;Web/官网区域入口已完成本地实现与合成浏览器验收;真实整站与远端实机验收尚未完成;额度重置与团队权益已改为关联会话材料。
 
-更新日期:2026-10-29。
+更新日期:2026-11-11。
 
 ## 迁移设计复核(2026-10-29)
 
@@ -185,7 +185,9 @@ Content-Type: application/json
 
 全球区发送 `zai`,旧客户端可以继续发送 `bigmodel`。初始化返回 `authorize_url`、`flow_id`、`poll_interval_sec`、`expires_at`;本次服务端还返回 `poll_token`。轮询令牌是 flow 凭据,不是登录后的账号 token,不写入 App Credential Store。
 
-中国区客户端打开服务端给出的完整 `authorize_url`,不自行修改 provider、state、client ID 或回调地址。本次中国区授权路径为 `/auth/oauth/authorize`,回调路径为 `/api/v1/oauth/cli/callback/zai_cn`;这与源码中全球区的默认授权路径不同。旧 `zai/bigmodel` 已有的桌面回调地址改写先保持兼容,移除该行为须另有回跳验证。测试与生产各自解析配置,不将测试地址写死在业务组件中。
+中国区桌面客户端保留服务端 `authorize_url` 的 origin、path、state、client ID,只将 `redirect_uri` 改为当前环境的 `/app/oauth/login?redirect=zcode%3A%2F%2Foauth%2Fcallback&app_version=...&provider=zai_cn`。官网中转页按 `provider=zai_cn` 将 code/state 转发至同源 `/api/v1/oauth/cli/callback/zai_cn`,并唤起客户端;provider 不进入最终 deep link。授权码只由后端兑换,Host 的中国区 polling flow 收到 deep link 时只保存归因,登录仍由同一 flow 的 polling 原子提交。归因写入继续受发起时的凭据代次约束;取消、过期及被替换的 flow 不能写回新会话。旧 `zai/bigmodel` 回跳行为不变。测试与生产各自解析配置,不将测试地址写死在业务组件中。
+
+`v3.18.0` 未包含此前本地的中国区中转修复;本次 hotfix 只恢复桌面中转和单次兑换契约。Web 远控/分享仍使用既有原页面轮询,不增加桌面唤起。真实上游对中转 `redirect_uri` 的接受及官网部署状态需单独验证,合成 E2E 不代替该证据。
 
 ### 4.2 登录完成响应
 
@@ -326,13 +328,13 @@ polling flow 的期限取服务端 `expires_at` 与本地五分钟中的较早
 
 ### 5.4 分区接入的存储约束
 
-`zai_cn` 是独立登录渠道,不是第三种模型供应商家族。中国区使用服务端 init 返回的完整授权 URL;其 `zai.access_token` 保存在 `oauth:zai_cn:access_token`,禁止送往全球区业务换证接口。中国区个人业务端点尚无契约证据,本阶段只接已明确的身份授权和 BigModel 关联材料。
+`zai_cn` 是独立登录渠道,不是第三种模型供应商家族。中国区使用服务端 init 返回的授权站和参数;桌面仅按第 4.1 节改写官网中转地址。其 `zai.access_token` 保存在 `oauth:zai_cn:access_token`,禁止送往全球区业务换证接口。中国区个人业务端点尚无契约证据,本阶段只接已明确的身份授权和 BigModel 关联材料。
 
 关联 BigModel 使用 Host 私有加密键 `oauth:linked_bigmodel`,内容包含绑定的 ZCode `userId`、`customerId` 和 `accessToken`。新登录在同一事务中写入当前响应的关联或移除旧关联,退出也一并清除。不得复用 `oauth:bigmodel:*` 伪造第二个登录。
 
 profile 请求显式声明 `authFailurePolicy: caller-handled`,由当前会话校验结果自行处理失败;不修改全局业务请求的 401 规则。中国区缓存恢复只按 ZCode JWT 判定主体过期,短期上游 OAuth 到期不清除主登录。关联密文损坏只清除关联键,不能删除有效主体。
 
-区域入口验收:国内发送 `zai_cn`、全球发送 `zai`,中国区 URL 不做回调重写,等待期间的取消保持原流程。完成响应中的关联必须完整合法;新登录缺失 `user.user_id` 必须拒绝。测试使用与 ZCode user ID 不相等的 BigModel customer ID,验证字段不混用。
+区域入口验收:国内发送 `zai_cn`、全球发送 `zai`;中国区授权站、state、client ID 保持原值,回调指向带 `provider=zai_cn` 的官网中转页,复制链接与浏览器打开地址一致。分别验证 deep link 先到、polling 先完成、取消后迟到的回调;不得重复兑换授权码或改写新会话。等待期间的取消保持原流程。完成响应中的关联必须完整合法;新登录缺失 `user.user_id` 必须拒绝。测试使用与 ZCode user ID 不相等的 BigModel customer ID,验证字段不混用。
 
 ### 5.5 套餐凭据解析(核心链路已实现)
 

+ 2 - 2
package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "zcode",
-  "version": "3.18.0",
+  "version": "3.18.1",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "zcode",
-      "version": "3.18.0",
+      "version": "3.18.1",
       "devDependencies": {
         "@vitest/coverage-v8": "^4.1.1",
         "concurrently": "^9.1.2",

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "zcode",
-  "version": "3.18.0",
+  "version": "3.18.1",
   "private": true,
   "type": "module",
   "scripts": {

+ 75 - 9
packages/desktop/build/installer.nsh

@@ -14,6 +14,17 @@
   !define ZCODE_INSTALLER_IS_ELEVATED_INNER `${UAC_IsInnerInstance}`
 !endif
 
+!ifndef ZCODE_INSTALLER_PROCESS_HELPER
+  ; CR-01 修复原因:普通 NSIS 只有 APP_64/APP_ARM64(压缩包路径),没有 APP_DIR_*;
+  ; 正式构建由 afterPack 落盘按架构的 helper define 文件(见 electron-builder.config.js),
+  ; 编译时按目标架构 include;缺失不在此报错,宏内在真正使用处明确失败。
+  !ifdef APP_ARM64
+    !include /NONFATAL "${__FILEDIR__}\generated\zcode-process-helper-arm64.nsh"
+  !else
+    !include /NONFATAL "${__FILEDIR__}\generated\zcode-process-helper-x64.nsh"
+  !endif
+!endif
+
 !ifndef ZCODE_INSTALL_MANIFEST_NAME
   !define ZCODE_INSTALL_MANIFEST_NAME ".zcode-install-manifest"
 !endif
@@ -112,11 +123,12 @@
       Goto zcodeManifestRead
 
     zcodeManifestDeleteFailed:
+      System::Call 'kernel32::GetLastError() i.R2'
       FileClose $R0
       !ifdef BUILD_UNINSTALLER
-        !insertmacro ZCodeReportUninstallerStage "cleanup-failed reason=permission-or-disk-space"
+        !insertmacro ZCodeReportUninstallerStage "cleanup-failed reason=delete-failed path=$R1 win32-error=$R2"
       !endif
-      Abort "无法删除旧版本文件:$INSTDIR\$R1"
+      Abort "无法删除旧版本文件:$INSTDIR\$R1(Win32 错误 $R2)"
 
     zcodeManifestClose:
       FileClose $R0
@@ -306,8 +318,30 @@
   Var ZCodeCleanupManifest
   Var ZCodeCleanupManifestHasSelf
 
-  ; 旧卸载器已删除的文件不会自行恢复。新安装器在调用旧代码前保存受管文件,
-  ; 清理失败只补回缺失项,避免覆盖仍被占用的原文件;备份失败时不进入旧卸载器。
+  ; 修复原因:PowerShell 或 Add-Type 被禁用时不能阻断已退出应用的更新;随包 helper 按路径验证句柄。
+  !macro ZCodeStopPreviousInstallProcesses
+    InitPluginsDir
+    SetOutPath "$PLUGINSDIR"
+    ; CR-01 修复原因:普通 NSIS 只有 APP_64/APP_ARM64(压缩包路径),没有 APP_DIR_*;
+    ; helper 来源由文件顶层的生成 define 提供,缺失在此明确失败,不得回退压缩包宏。
+    !ifndef ZCODE_INSTALLER_PROCESS_HELPER
+      !error "Installer process helper requires ZCODE_INSTALLER_PROCESS_HELPER or generated define"
+    !endif
+    File /oname=zcode-installer-process-helper.exe "${ZCODE_INSTALLER_PROCESS_HELPER}"
+    nsExec::ExecToStack /TIMEOUT=30000 `"$PLUGINSDIR\zcode-installer-process-helper.exe" "$installationDir\${APP_EXECUTABLE_FILENAME}"`
+    Pop $R1
+    Pop $R2
+    StrCmp $R1 "0" zcodePreviousProcessesStopped
+    !insertmacro ZCodeReportInstallerStage "process-cleanup-failed exit-code=$R1 install-dir=$installationDir details=$R2"
+    !insertmacro ZCodeCleanupErrorMessage "无法验证或关闭旧版本进程,安装已停止。请关闭 ZCode 后重试。进程信息:$R2" "Cannot verify or close previous-version processes. Setup stopped. Close ZCode and retry. Process details: $R2"
+    SetErrorLevel 2
+    Quit
+    zcodePreviousProcessesStopped:
+      !insertmacro ZCodeReportInstallerStage "process-cleanup-completed install-dir=$installationDir details=$R2"
+  !macroend
+
+  ; 旧卸载器已删除的文件不会自行恢复。新安装器在调用旧代码前尽力保存受管文件,
+  ; 只有完整备份才能用于清理失败后的恢复;备份失败不阻断安装。
   ; 自定义 include 先于 common.nsh;延迟展开,确保卸载器名称已定义,避免正式打包 warning 6000。
   !macro ZCodeDefineCleanupSnapshot
   Function ZCodeCleanupSnapshot
@@ -449,29 +483,49 @@
 
   !macro customOldUninstallPrepare
     StrCpy $ZCodeCleanupSource "$installationDir"
+    !insertmacro ZCodeStopPreviousInstallProcesses
     StrCpy $ZCodeCleanupMode "backup"
     Call ZCodeCleanupSnapshot
     ${If} $ZCodeCleanupFailed == "1"
-      ; 此时尚未运行旧卸载器,原文件仍完整;失败的半份备份可以安全清理。
+      ; 修复原因:备份是可选保护;失败时弃用半份备份,避免旧卸载失败后误用它恢复。
+      !insertmacro ZCodeReportInstallerStage "cleanup-backup-skipped path=$ZCodeCleanupBackup"
+      StrCmp $ZCodeCleanupBackup "" zcodePreviousBackupCleanupDone
+      ClearErrors
       RMDir /r "$ZCodeCleanupBackup"
-      !insertmacro ZCodeCleanupErrorMessage "无法备份旧版本文件,安装已停止,旧版本未改动。请检查权限与剩余空间。" "Cannot back up the previous version. Setup stopped without changing it. Check permissions and free disk space."
-      SetErrorLevel 2
-      Quit
+      IfErrors zcodePreviousBackupCleanupFailed
+      Goto zcodePreviousBackupCleanupDone
+      zcodePreviousBackupCleanupFailed:
+        !insertmacro ZCodeReportInstallerStage "cleanup-backup-delete-failed path=$ZCodeCleanupBackup"
+      zcodePreviousBackupCleanupDone:
+      StrCpy $ZCodeCleanupBackup ""
     ${EndIf}
   !macroend
 
   !macro customOldUninstallRetryFailed
     ; 上游把任意卸载非零都显示成应用未关闭;实际进程检查仍由 CHECK_APP_RUNNING 负责。
-    !insertmacro ZCodeReportInstallerStage "cleanup-retries-exhausted exit-code=$R0"
+    ; 备份失败被弃用后没有可恢复的完整备份;提示必须与能否恢复一致,不能在无备份时承诺恢复。
+    StrCmp $ZCodeCleanupBackup "" zcodeRetryExhaustedNoBackup
+    !insertmacro ZCodeReportInstallerStage "cleanup-retries-exhausted exit-code=$R0 recoverable=1"
     ${If} $LANGUAGE == 2052
       MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "旧版本清理失败(错误码 $R0)。请排除文件占用或权限问题后重试,或取消以恢复旧版本。日志:$ZCodeInstallerLogPath" /SD IDCANCEL IDRETRY OneMoreAttempt
     ${Else}
       MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "Previous version cleanup failed (exit code $R0). Resolve file locks or permissions and retry, or cancel to restore the previous version. Log: $ZCodeInstallerLogPath" /SD IDCANCEL IDRETRY OneMoreAttempt
     ${EndIf}
+    Goto zcodeRetryExhaustedDone
+    zcodeRetryExhaustedNoBackup:
+    !insertmacro ZCodeReportInstallerStage "cleanup-retries-exhausted exit-code=$R0 recoverable=0"
+    ${If} $LANGUAGE == 2052
+      MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "旧版本清理失败(错误码 $R0)。本次更新没有完整备份:排除占用后可重试,取消将退出安装且无法自动恢复旧版本文件。日志:$ZCodeInstallerLogPath" /SD IDCANCEL IDRETRY OneMoreAttempt
+    ${Else}
+      MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "Previous version cleanup failed (exit code $R0). No complete backup exists for this update: retry after resolving file locks, or cancel to exit setup without automatic restore. Log: $ZCodeInstallerLogPath" /SD IDCANCEL IDRETRY OneMoreAttempt
+    ${EndIf}
+    zcodeRetryExhaustedDone:
   !macroend
 
   Function ZCodeFinishOldUninstall
     ${If} $R0 != 0
+      ; 修复原因:没有完整备份时不能用半份文件恢复,旧卸载失败仍由原流程报告。
+      StrCmp $ZCodeCleanupBackup "" zcodeFinishOldUninstallDone
       StrCpy $ZCodeCleanupMode "restore"
       Call ZCodeCleanupSnapshot
       ${If} $ZCodeCleanupFailed == "1"
@@ -480,8 +534,14 @@
       ${EndIf}
     ${EndIf}
     StrCmp $ZCodeCleanupBackup "" zcodeFinishOldUninstallDone
+    ClearErrors
     RMDir /r "$ZCodeCleanupBackup"
+    IfErrors zcodeFinishOldUninstallBackupDeleteFailed
     StrCpy $ZCodeCleanupBackup ""
+    Goto zcodeFinishOldUninstallDone
+    zcodeFinishOldUninstallBackupDeleteFailed:
+      ; 修复原因:备份清理故障不影响旧卸载结果及后续新版本安装,只保留路径供排查。
+      !insertmacro ZCodeReportInstallerStage "cleanup-backup-delete-failed path=$ZCodeCleanupBackup"
     zcodeFinishOldUninstallDone:
   FunctionEnd
 
@@ -629,6 +689,12 @@
   ; 修复原因:手动覆盖没有 --updated,继承旧快捷方式时仍需检查目标;首次安装没有旧项,
   ; 不应额外启动 PowerShell。用户已删除的快捷方式也不会重建。
   ; assisted installer 完成页始终直接运行本次安装落盘的 exe。
+  ; 修复原因:安装信息键的 InstallLocation 用于旧卸载器路径解析;卸载注册表键也写入相同值,
+  ; 避免 Windows 应用列表中的卸载项长期为空,并为后续迁移提供确定目录。
+  WriteRegStr SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}" InstallLocation "$INSTDIR"
+  !ifdef UNINSTALL_REGISTRY_KEY_2
+    WriteRegStr SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY_2}" InstallLocation "$INSTDIR"
+  !endif
   StrCpy $launchLink "$appExe"
   !ifndef BUILD_UNINSTALLER
     !insertmacro ZCodeReportInstallerStage "install-completed"

+ 46 - 0
packages/desktop/electron-builder.config.js

@@ -600,6 +600,41 @@ function signWindowsHelper(context, relativeHelperPath) {
   ]);
 }
 
+// CR-01 修复原因:普通 NSIS 构建只提供 APP_64/APP_ARM64(压缩包路径),没有 APP_DIR_*;
+// installer.nsh 无法自行推导 helper 来源。afterPack 先于 makensis 执行,在这里把实际
+// appOutDir 下的 helper 写成按架构命名的生成 define 文件,NSIS 编译时按架构 include。
+export function installerProcessHelperDefineLine(appOutDir) {
+  const helperPath = join(
+    appOutDir,
+    "resources",
+    "tools",
+    "runtime-host",
+    "zcode-installer-process-helper.exe",
+  );
+  // NSIS 的 File 指令只认反斜杠绝对路径;引号字符串中 $ 与 " 需转义,属防御性处理。
+  const escaped = helperPath.replaceAll("$", "$$").replaceAll('"', '$\\"');
+  return `!define ZCODE_INSTALLER_PROCESS_HELPER "${escaped}"\n`;
+}
+
+async function writeInstallerProcessHelperDefine(context, archName) {
+  const helperPath = resolve(
+    context.appOutDir,
+    "resources",
+    "tools",
+    "runtime-host",
+    "zcode-installer-process-helper.exe",
+  );
+  if (!existsSync(helperPath)) {
+    throw new Error(`Installer process helper missing after pack: ${helperPath}`);
+  }
+  mkdirSync(join(desktopPackageRoot, "build", "generated"), { recursive: true });
+  await writeFile(
+    join(desktopPackageRoot, "build", "generated", `zcode-process-helper-${archName}.nsh`),
+    installerProcessHelperDefineLine(context.appOutDir),
+    "utf8",
+  );
+}
+
 /** @type {import("electron-builder").Configuration} */
 export default {
   appId: desktopProductIdentity.appId,
@@ -750,7 +785,13 @@ export default {
       );
     }
     if (context.electronPlatformName === "win32") {
+      // 普通打包没有 APP_DIR_* 宏;makensis 前落盘按架构的 helper define(见函数注释)。
+      await writeInstallerProcessHelperDefine(
+        context,
+        actualWindowsTarget?.arch ?? targetPlatform.arch,
+      );
       signWindowsHelper(context, "tools/runtime-host/zcode-runtime-host.exe");
+      signWindowsHelper(context, "tools/runtime-host/zcode-installer-process-helper.exe");
     }
     if (shouldPackageWindowsBrowserImportHelper) {
       runTimedSync("afterPack:signWindowsBrowserImportHelper", () =>
@@ -761,6 +802,7 @@ export default {
   afterSign: async (context) => {
     if (context.electronPlatformName === "win32") {
       assertSignedWindowsHelper(context, "tools/runtime-host/zcode-runtime-host.exe");
+      assertSignedWindowsHelper(context, "tools/runtime-host/zcode-installer-process-helper.exe");
     }
     if (shouldPackageWindowsBrowserImportHelper) {
       runTimedSync("afterSign:assertSignedWindowsBrowserImportHelper", () =>
@@ -783,6 +825,10 @@ export default {
             from: `bundled-tools/${targetPlatform.key}/runtime-host/zcode-runtime-host.exe`,
             to: "tools/runtime-host/zcode-runtime-host.exe",
           },
+          {
+            from: `bundled-tools/${targetPlatform.key}/runtime-host/zcode-installer-process-helper.exe`,
+            to: "tools/runtime-host/zcode-installer-process-helper.exe",
+          },
         ]
       : []),
     { from: resolve(workspaceRoot, noticesFileName), to: noticesFileName },

+ 1 - 0
packages/desktop/scripts/test-installer-nsh-smoke.mjs

@@ -98,6 +98,7 @@ function compileFixture({
     `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
     `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
     `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
+    `/DZCODE_INSTALLER_PROCESS_HELPER=${resolve(desktopDir, `bundled-tools/win32-${process.arch}/runtime-host/zcode-installer-process-helper.exe`)}`,
     `/DFIXTURE_EXE=${process.env.ComSpec ?? "C:\\Windows\\System32\\cmd.exe"}`,
     `/DOUTPUT_FILE=${outputPath}`,
     `/DDEFAULT_LOG_PATH=${defaultLogPath}`,

+ 95 - 17
packages/desktop/scripts/test-installer-preserve-files.mjs

@@ -34,12 +34,15 @@ if (process.platform !== "win32") {
       makensisPath,
       [
         "/V2",
+        "/INPUTCHARSET",
+        "UTF8",
         "/WX",
         "/DBUILD_UNINSTALLER",
         `/DNSIS_INCLUDE_DIR=${resolve(nsisDir, "Include")}`,
         `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
         `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
         `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
+        `/DZCODE_INSTALLER_PROCESS_HELPER=${resolve(desktopDir, `bundled-tools/win32-${process.arch}/runtime-host/zcode-installer-process-helper.exe`)}`,
         // 夹具只校验文件字节,不执行该载荷;避免 32 位 NSIS 将 System32 重定向到 SysWOW64。
         `/DFIXTURE_EXE=${fixturePath}`,
         `/DOUTPUT_FILE=${uninstallerOutput}`,
@@ -52,6 +55,8 @@ if (process.platform !== "win32") {
       makensisPath,
       [
         "/V2",
+        "/INPUTCHARSET",
+        "UTF8",
         "/WX",
         `/DOUTPUT_FILE=${legacySelfUninstaller}`,
         resolve(desktopDir, "test/fixtures/legacy-self-manifest-uninstaller.nsi"),
@@ -67,10 +72,13 @@ if (process.platform !== "win32") {
       const installDir = join(tempRoot, scenario);
       const compileArgs = [
         "/V2",
+        "/INPUTCHARSET",
+        "UTF8",
         `/DNSIS_INCLUDE_DIR=${resolve(nsisDir, "Include")}`,
         `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
         `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
         `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
+        `/DZCODE_INSTALLER_PROCESS_HELPER=${resolve(desktopDir, `bundled-tools/win32-${process.arch}/runtime-host/zcode-installer-process-helper.exe`)}`,
         `/DFIXTURE_EXE=${fixturePath}`,
         `/DOUTPUT_FILE=${outputPath}`,
         fixturePath,
@@ -99,12 +107,15 @@ if (process.platform !== "win32") {
     const failureLogPath = join(tempRoot, "failure-uninstaller.log");
     const failureCompileArgs = [
       "/V2",
+      "/INPUTCHARSET",
+      "UTF8",
       "/WX",
       "/DBUILD_UNINSTALLER",
       `/DNSIS_INCLUDE_DIR=${resolve(nsisDir, "Include")}`,
       `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
       `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
       `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
+      `/DZCODE_INSTALLER_PROCESS_HELPER=${resolve(desktopDir, `bundled-tools/win32-${process.arch}/runtime-host/zcode-installer-process-helper.exe`)}`,
       `/DFIXTURE_EXE=${fixturePath}`,
       `/DOUTPUT_FILE=${failureOutputPath}`,
       `/DZCODE_UNINSTALLER_LOG_PATH=${failureLogPath}`,
@@ -128,7 +139,10 @@ if (process.platform !== "win32") {
       throw new Error("manifest cleanup failure unexpectedly returned success");
     }
     const failureLog = readFileSync(failureLogPath, "utf8");
-    for (const marker of ["cleanup-started", "cleanup-failed reason=permission-or-disk-space"]) {
+    for (const marker of [
+      "cleanup-started",
+      "cleanup-failed reason=delete-failed path=owned-by-zcode.txt win32-error=",
+    ]) {
       if (!failureLog.includes(marker)) {
         throw new Error(`uninstaller log is missing ${marker}: ${failureLog}`);
       }
@@ -140,16 +154,29 @@ if (process.platform !== "win32") {
     if (existsSync(join(failureInstallDir, "ZCode.exe"))) {
       throw new Error("old cleanup fixture did not reproduce the deleted application");
     }
-    // 真正运行旧清理进程:先删主程序,再因独占文件句柄失败;新安装器必须补回主程序。
+    // 真正运行旧清理进程,分别验证完整恢复、可选备份失败和成功后的新载荷写入。
     for (const scenario of [
       "recovery",
       "backup-failure",
+      "backup-and-uninstall-failure",
       "restore-failure",
+      "backup-delete-failure",
+      "backup-delete-success",
       "self-manifest-recovery",
       "self-manifest-success",
     ]) {
+      const installSucceeds = [
+        "backup-failure",
+        "backup-delete-success",
+        "self-manifest-success",
+      ].includes(scenario);
+      const backupFails =
+        scenario === "backup-failure" || scenario === "backup-and-uninstall-failure";
+      const deleteFails =
+        scenario === "backup-delete-failure" || scenario === "backup-delete-success";
       const recoveryOutputPath = join(tempRoot, `${scenario}.exe`);
       const recoveryInstallDir = join(tempRoot, scenario);
+      const installerLogPath = join(tempRoot, `${scenario}-installer.log`);
       const recoveryArgs = failureCompileArgs.filter(
         (arg) =>
           arg !== "/DBUILD_UNINSTALLER" &&
@@ -161,11 +188,13 @@ if (process.platform !== "win32") {
       recoveryArgs.push(
         `/DOUTPUT_FILE=${recoveryOutputPath}`,
         "/DRECOVERY_TEST",
-        `/DOLD_CLEANUP_EXE=${scenario === "self-manifest-success" ? legacySelfUninstaller : failureOutputPath}`,
+        `/DZCODE_INSTALLER_DEFAULT_LOG_PATH=${installerLogPath}`,
+        `/DOLD_CLEANUP_EXE=${installSucceeds ? legacySelfUninstaller : failureOutputPath}`,
       );
       if (scenario.startsWith("self-manifest")) recoveryArgs.push("/DSELF_MANIFEST");
-      if (scenario === "backup-failure") recoveryArgs.push("/DBACKUP_FAILURE");
+      if (backupFails) recoveryArgs.push("/DBACKUP_FAILURE");
       if (scenario === "restore-failure") recoveryArgs.push("/DRESTORE_FAILURE");
+      if (deleteFails) recoveryArgs.push("/DBACKUP_DELETE_FAILURE");
       recoveryArgs.push(fixturePath);
       execFileSync(makensisPath, recoveryArgs, { cwd: workspaceDir, encoding: "utf8" });
       let recoveryExitCode = 0;
@@ -174,24 +203,71 @@ if (process.platform !== "win32") {
       } catch (error) {
         recoveryExitCode = error.status ?? 0;
       }
-      const expectedExitCode = scenario === "self-manifest-success" ? 0 : 2;
+      const expectedExitCode = installSucceeds ? 0 : 2;
       if (recoveryExitCode !== expectedExitCode)
-        throw new Error(`${scenario}: exit code ${recoveryExitCode}`);
-      if (scenario !== "backup-failure") {
-        const backupDir = readFileSync(join(recoveryInstallDir, "backup-dir.txt"), "utf8");
-        if (existsSync(backupDir) !== (scenario === "restore-failure")) {
-          throw new Error(`${scenario}: wrong backup retention state`);
-        }
+        throw new Error(
+          `${scenario}: exit code ${recoveryExitCode}, expected ${expectedExitCode}; fixture=${tempRoot}`,
+        );
+      const backupDirPath = join(recoveryInstallDir, "backup-dir.txt");
+      if (!existsSync(backupDirPath)) {
+        throw new Error(`${scenario}: backup directory marker missing`);
+      }
+      const backupDir = readFileSync(backupDirPath, "utf8");
+      if (backupFails && backupDir !== "") {
+        throw new Error(`${scenario}: partial backup is still available for recovery`);
+      }
+      const shouldRetainBackup = scenario === "restore-failure" || deleteFails;
+      if ((backupDir !== "" && existsSync(backupDir)) !== shouldRetainBackup) {
+        throw new Error(`${scenario}: wrong backup retention state`);
+      }
+      if (
+        scenario === "restore-failure" &&
+        readFileSync(join(backupDir, "ZCode.exe"), "utf8") !== "old application payload"
+      ) {
+        throw new Error(`${scenario}: recoverable application backup was lost`);
+      }
+      const installerLog = readFileSync(installerLogPath, "utf8");
+      // 重试耗尽的提示按是否存在完整备份切换;recoverable 标志验证提示分支与文件状态一致。
+      if (
+        !installSucceeds &&
+        !installerLog.includes(
+          `cleanup-retries-exhausted exit-code=2 recoverable=${backupFails ? "0" : "1"}`,
+        )
+      ) {
+        throw new Error(`${scenario}: retry prompt recoverable flag mismatch`);
+      }
+      if (backupFails) {
         if (
-          scenario === "restore-failure" &&
-          !readFileSync(join(backupDir, "ZCode.exe")).equals(readFileSync(fixturePath))
+          !installerLog.includes("cleanup-backup-completed failed=1") ||
+          !installerLog.includes("cleanup-backup-skipped")
         ) {
-          throw new Error(`${scenario}: recoverable application backup was lost`);
+          throw new Error(`${scenario}: backup failure was not logged`);
+        }
+        if (installerLog.includes("cleanup-restore-completed")) {
+          throw new Error(`${scenario}: attempted recovery without a complete backup`);
         }
       }
-      if (
+      if (deleteFails && !installerLog.includes(`cleanup-backup-delete-failed path=${backupDir}`)) {
+        throw new Error(`${scenario}: cleanup failure path was not logged`);
+      }
+      const installMarker = join(recoveryInstallDir, "remove-result.txt");
+      if (existsSync(installMarker) !== installSucceeds) {
+        throw new Error(`${scenario}: wrong new-payload installation state`);
+      }
+      if (installSucceeds) {
+        if (
+          !readFileSync(join(recoveryInstallDir, "ZCode.exe")).equals(readFileSync(fixturePath)) ||
+          readFileSync(installMarker, "utf8") !== "removed"
+        ) {
+          throw new Error(`${scenario}: new application payload was not installed after cleanup`);
+        }
+      } else if (scenario === "backup-and-uninstall-failure") {
+        if (existsSync(join(recoveryInstallDir, "ZCode.exe"))) {
+          throw new Error(`${scenario}: partial backup was incorrectly restored`);
+        }
+      } else if (
         scenario !== "restore-failure" &&
-        !readFileSync(join(recoveryInstallDir, "ZCode.exe")).equals(readFileSync(fixturePath))
+        readFileSync(join(recoveryInstallDir, "ZCode.exe"), "utf8") !== "old application payload"
       ) {
         throw new Error(`${scenario}: original application bytes were lost`);
       }
@@ -209,6 +285,8 @@ if (process.platform !== "win32") {
 
     process.stdout.write("[installer-preserve-files] passed\n");
   } finally {
-    rmSync(tempRoot, { recursive: true, force: true });
+    if (process.env.ZCODE_KEEP_INSTALLER_FIXTURE !== "1") {
+      rmSync(tempRoot, { recursive: true, force: true });
+    }
   }
 }

+ 13 - 0
packages/desktop/src/main/exportLogs.ts

@@ -17,6 +17,7 @@ import { dirname, join, posix } from "node:path";
 import { Transform } from "node:stream";
 import { pipeline } from "node:stream/promises";
 import { ZipFile } from "yazl";
+import { CLI_MEMORY_DIAGNOSTIC_DIRECTORY, CLI_MEMORY_FILE_PATTERN } from "@zcode/shared";
 
 import {
   createFeedbackDiagnosticArchive,
@@ -1264,6 +1265,12 @@ export async function createLogArchiveArtifacts(
   );
 
   const zcodeCliDir = getZCodeCliDir();
+  await collectLogArchiveFilesByName(
+    join(zcodeCliDir, CLI_MEMORY_DIAGNOSTIC_DIRECTORY),
+    posix.join(".zcode", "cli", CLI_MEMORY_DIAGNOSTIC_DIRECTORY),
+    (name) => CLI_MEMORY_FILE_PATTERN.test(name),
+    files,
+  );
   // 排查 agent CLI 问题还需要它的运行配置与模型 IO 轨迹。
   // config.json 是当前生效配置;rollout 是 model-io 调用轨迹,
   // 二者都不在 ~/.zcode/cli/log 下,需要额外收集才能完整还原现场。
@@ -1436,6 +1443,12 @@ export async function createFeedbackLogArchiveFromExportLogs(
 ): Promise<{ path: string; size: number }> {
   return createFeedbackDiagnosticArchive({
     sources: [
+      {
+        directory: join(getZCodeCliDir(), CLI_MEMORY_DIAGNOSTIC_DIRECTORY),
+        archivePrefix: ".zcode/cli/memory-diagnostics",
+        contentPolicy: "cli-memory",
+        onlyCurrentDay: false,
+      },
       { directory: join(sourceDir, "logs"), archivePrefix: "logs" },
       { directory: getZCodeCliLogDir(), archivePrefix: ".zcode/cli/log" },
       {

+ 4 - 1
packages/desktop/src/main/microphone-access/CONTRACT.md

@@ -1,9 +1,12 @@
 # desktop-microphone-access
 
-Composer 语音输入(`docs/chat/composer-voice-input.md`)在 Main 进程的系统权限部分:检查 / 请求麦克风系统权限,打开系统设置页。
+Composer 语音输入(`docs/chat/composer-voice-input.md`)在 Main 进程的系统权限部分:检查 / 请求麦克风系统权限,macOS 重新授权,打开系统设置页。
 
 不变量:
 
 - 只打开本模块列出的固定系统设置地址;renderer 只能选择 `privacy` 或 `sound`,不能传 URL。
 - macOS `not-determined` 时才调用 `askForMediaAccess`;Windows 无法判定时返回 `unsupported`,交给 `getUserMedia` 的真实结果。
 - Linux 没有统一的系统设置地址,`openSettings` 返回 `false`。
+- 重新授权只执行 `/usr/bin/tccutil reset Microphone <当前 App bundle id>`,bundle id 读自运行中 App 的 Info.plist,renderer 不能传参数。开发版(未打包)跳过 tccutil。
+- 重置后是否需要重启由重置后的状态决定(仍是 `denied` → `restart-required`),不做计时判断。
+- 已经是 `granted` 时不重置;同时到达的重置请求在 main 进程合并为同一次,不并发执行 tccutil。

+ 5 - 1
packages/desktop/src/main/microphone-access/contract.ts

@@ -2,7 +2,7 @@
  * desktop-microphone-access 对外契约:Main 进程的麦克风系统权限与系统设置跳转。
  * Renderer 只经 preload 的两个 IPC 频道调用,见 docs/chat/composer-voice-input.md「麦克风权限」。
  */
-import type { MicrophoneAccessResult } from "@zcode/shared";
+import type { MicrophoneAccessResetResult, MicrophoneAccessResult } from "@zcode/shared";
 
 export interface DesktopMicrophoneAccessContract {
   /** 注册 MicrophoneAccess / OpenMicrophoneSettings 两个 IPC 处理器;只调用一次 */
@@ -12,4 +12,8 @@ export interface DesktopMicrophoneAccessContract {
   }): void;
   /** macOS 未询问过时弹出系统授权;Linux 及无法判定时返回 unsupported */
   ensureMicrophoneAccess(platform?: NodeJS.Platform): Promise<MicrophoneAccessResult>;
+  /** macOS:重置本 App 的麦克风授权记录并重新请求;开发版跳过 tccutil;其他系统返回 failed */
+  resetMicrophoneAccess(logger: {
+    warn: (...args: unknown[]) => void;
+  }): Promise<MicrophoneAccessResetResult>;
 }

+ 88 - 2
packages/desktop/src/main/microphone-access/desktopMicrophoneAccess.ts

@@ -1,6 +1,16 @@
-import type { MicrophoneAccessResult, MicrophoneSettingsTarget } from "@zcode/shared";
+import { execFile } from "node:child_process";
+import { dirname, join } from "node:path";
+import { promisify } from "node:util";
+import type {
+  MicrophoneAccessResetResult,
+  MicrophoneAccessResult,
+  MicrophoneSettingsTarget,
+} from "@zcode/shared";
 import { PlatformChannels } from "@zcode/shared";
-import { ipcMain, shell, systemPreferences } from "electron";
+import { app, ipcMain, shell, systemPreferences } from "electron";
+
+const execFileAsync = promisify(execFile);
+const SAFE_BUNDLE_ID = /^[A-Za-z0-9.-]+$/;
 
 // 只允许打开这里列出的固定地址,renderer 只能选 target,不能传任意 URL。
 // Linux 桌面环境没有统一的设置页地址,不提供跳转(docs/chat/composer-voice-input.md)。
@@ -30,6 +40,58 @@ export async function ensureMicrophoneAccess(
   return status === "denied" || status === "restricted" ? "denied" : "unsupported";
 }
 
+/** 当前 App 的 bundle id,读自运行中的 .app 的 Info.plist(TCC 按它记录授权) */
+async function readOwnBundleId(): Promise<string> {
+  // process.execPath = <App>.app/Contents/MacOS/<可执行文件>
+  const plist = join(dirname(dirname(process.execPath)), "Info.plist");
+  const { stdout } = await execFileAsync("/usr/libexec/PlistBuddy", [
+    "-c",
+    "Print :CFBundleIdentifier",
+    plist,
+  ]);
+  const bundleId = stdout.trim();
+  if (!SAFE_BUNDLE_ID.test(bundleId)) throw new Error(`invalid bundle id: ${bundleId}`);
+  return bundleId;
+}
+
+/**
+ * macOS「重新授权」(docs/chat/composer-voice-input.md「权限引导浮层」)。
+ * 原因:macOS 麦克风列表没有「+」,用户拒绝过或系统静默拒绝后,askForMediaAccess 不再弹框,
+ * 设置页里也可能找不到 ZCode。只重置 ZCode 自己的记录,让系统重新弹框,用户仍需点「允许」。
+ * 是否需要重启由重置后的状态决定,不做计时判断。
+ */
+export async function resetMicrophoneAccess(logger: {
+  warn: (...args: unknown[]) => void;
+}): Promise<MicrophoneAccessResetResult> {
+  if (process.platform !== "darwin") return "failed";
+  const before = systemPreferences.getMediaAccessStatus("microphone");
+  // 已允许(例如用户刚在系统设置里打开)时不重置,避免删掉有效授权。
+  if (before === "granted") return "granted";
+  // MDM 限制不能由用户解除,重置没有意义。
+  if (before === "restricted") return "failed";
+  // 开发版是所有未改名 Electron 共用的 com.github.Electron,TCC 按路径记录,按 bundle id 重置无效
+  // 且会影响其他项目,所以只在打包版执行 tccutil。
+  if (app.isPackaged) {
+    try {
+      await execFileAsync("/usr/bin/tccutil", ["reset", "Microphone", await readOwnBundleId()]);
+    } catch (error) {
+      logger.warn(
+        `[voice-input] reset microphone access failed error=${
+          error instanceof Error ? error.message : String(error)
+        }`,
+      );
+      return "failed";
+    }
+  }
+  const status = systemPreferences.getMediaAccessStatus("microphone");
+  if (status === "granted") return "granted";
+  if (status === "not-determined") {
+    return (await systemPreferences.askForMediaAccess("microphone")) ? "granted" : "denied";
+  }
+  // 重置后当前进程仍读到旧结果:重启后才会重新弹框。
+  return "restart-required";
+}
+
 export function registerDesktopMicrophoneIpcHandlers(logger: {
   info: (...args: unknown[]) => void;
   warn: (...args: unknown[]) => void;
@@ -39,6 +101,30 @@ export function registerDesktopMicrophoneIpcHandlers(logger: {
     logger.info(`[voice-input] microphone access platform=${process.platform} result=${result}`);
     return result;
   });
+  // 重置在 main 进程串行:多个输入框同时点「重新授权」时共用同一次结果,
+  // 不会并发执行 tccutil 和系统授权请求。
+  let pendingReset: Promise<MicrophoneAccessResetResult> | null = null;
+  ipcMain.handle(PlatformChannels.ResetMicrophoneAccess, () => {
+    pendingReset ??= resetMicrophoneAccess(logger)
+      .catch((error: unknown): MicrophoneAccessResetResult => {
+        logger.warn(
+          `[voice-input] reset microphone access error=${
+            error instanceof Error ? error.message : String(error)
+          }`,
+        );
+        return "failed";
+      })
+      .then((result) => {
+        logger.info(
+          `[voice-input] reset microphone access result=${result} packaged=${app.isPackaged}`,
+        );
+        return result;
+      })
+      .finally(() => {
+        pendingReset = null;
+      });
+    return pendingReset;
+  });
   ipcMain.handle(
     PlatformChannels.OpenMicrophoneSettings,
     async (_event, target: unknown): Promise<boolean> => {

+ 1 - 0
packages/desktop/src/main/microphone-access/index.ts

@@ -1,4 +1,5 @@
 export {
   ensureMicrophoneAccess,
   registerDesktopMicrophoneIpcHandlers,
+  resetMicrophoneAccess,
 } from "./desktopMicrophoneAccess.js";

+ 4 - 0
packages/desktop/src/preload/index.ts

@@ -90,6 +90,7 @@ import type {
   SaveFileRequest,
   SaveFileResult,
   PrintPageToPdfResult,
+  MicrophoneAccessResetResult,
   MicrophoneAccessResult,
   MicrophoneSettingsTarget,
   CaptureBrowserGuestPageRequest,
@@ -358,6 +359,9 @@ contextBridge.exposeInMainWorld("zcode", {
   /** 语音输入:检查并按需请求系统麦克风权限 */
   ensureMicrophoneAccess: (): Promise<MicrophoneAccessResult> =>
     ipcRenderer.invoke(PlatformChannels.MicrophoneAccess),
+  /** 语音输入:macOS 重置本 App 的麦克风授权记录并重新请求 */
+  resetMicrophoneAccess: (): Promise<MicrophoneAccessResetResult> =>
+    ipcRenderer.invoke(PlatformChannels.ResetMicrophoneAccess),
   /** 语音输入:打开系统麦克风权限 / 声音输入设置页 */
   openMicrophoneSettings: (target: MicrophoneSettingsTarget): Promise<boolean> =>
     ipcRenderer.invoke(PlatformChannels.OpenMicrophoneSettings, target),

+ 4 - 1
packages/desktop/src/renderer/src/desktopBrowserPlatformBridge.ts

@@ -39,9 +39,12 @@ export const desktopBrowserPlatformBridge = {
   printPageToPdf: window.zcode.printPageToPdf ? () => window.zcode.printPageToPdf!() : undefined,
   // 与 printPageToPdf 一样按 preload 是否提供决定能力是否存在,UI 据此决定是否显示语音输入。
   microphone:
-    window.zcode.ensureMicrophoneAccess && window.zcode.openMicrophoneSettings
+    window.zcode.ensureMicrophoneAccess &&
+    window.zcode.resetMicrophoneAccess &&
+    window.zcode.openMicrophoneSettings
       ? {
           ensureAccess: () => window.zcode.ensureMicrophoneAccess!(),
+          resetAccess: () => window.zcode.resetMicrophoneAccess!(),
           openSettings: (target) => window.zcode.openMicrophoneSettings!(target),
         }
       : undefined,

+ 90 - 6
packages/desktop/test/e2e/auth-config/login/oauth-completion-race.test.ts

@@ -109,11 +109,36 @@ describe("OAuth 双路径完成竞态", () => {
     expect(authState(await readCredentials())).toEqual(authState(before));
   });
 
-  it("区域切换选择实际登录渠道,并保留中国区服务端授权 URL", async () => {
+  it("区域切换选择实际登录渠道,中国区仅改写官网中转地址", async () => {
     const baseUrl = process.env.ZCODE_E2E_OAUTH_RACE_URL!;
     const openExternal = await browser.electron.mock("shell", "openExternal");
     await openExternal.mockClear();
     await openExternal.mockResolvedValue(undefined);
+    await browser.waitUntil(
+      async () =>
+        browser.execute(
+          (button, trigger) =>
+            Boolean(
+              document.querySelector(
+                `[data-testid="${button}"], [data-testid="${trigger}"], [data-testid="onboarding-page"]`,
+              ),
+            ),
+          TID_OAUTH_LOGIN_BUTTON,
+          TID_LOGIN_TRIGGER,
+        ),
+      { timeout: 60_000 },
+    );
+    await browser.keys("Escape");
+    if (!(await browser.$(`[data-testid="${TID_OAUTH_LOGIN_BUTTON}"]`).isExisting())) {
+      // 单独运行本例时从工作区打开登录面板;头像菜单依赖真实 pointerdown。
+      for (const trigger of await browser.$$(`[data-testid="${TID_LOGIN_TRIGGER}"]`)) {
+        if (await trigger.isDisplayed()) {
+          await trigger.click();
+          break;
+        }
+      }
+      await clickTestIdByDom(TID_LOGIN_MENU_ITEM);
+    }
     await waitForTestIdByDom(TID_OAUTH_LOGIN_BUTTON);
     const region = await browser.$(`[data-testid="${TID_LOGIN_REGION_SWITCH}"]`);
     if ((await region.getText()).includes("中国")) await region.click();
@@ -126,8 +151,27 @@ describe("OAuth 双路径完成竞态", () => {
       { timeout: 10_000 },
     );
     expect((await (await fetch(`${baseUrl}/__e2e/status`)).json()).activeProvider).toBe("zai_cn");
-    expect(openExternal.mock.calls[0]?.[0]).toBe(
-      "https://example.com/cn/authorize?state=e2e-race&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback%2Fzai_cn",
+    const openedUrl = String(openExternal.mock.calls[0]?.[0]);
+    const authorizeUrl = new URL(openedUrl);
+    expect(authorizeUrl.origin + authorizeUrl.pathname).toBe("https://example.com/cn/authorize");
+    expect(authorizeUrl.searchParams.get("state")).toBe("e2e-race");
+    expect(authorizeUrl.searchParams.get("client_id")).toBe("e2e-cn-client");
+    expect(authorizeUrl.searchParams.get("response_type")).toBe("code");
+    const bridgeUrl = new URL(authorizeUrl.searchParams.get("redirect_uri")!);
+    expect(bridgeUrl.origin).toBe(new URL(baseUrl).origin);
+    expect(bridgeUrl.pathname).toBe("/app/oauth/login");
+    expect(bridgeUrl.searchParams.get("provider")).toBe("zai_cn");
+    expect(bridgeUrl.searchParams.get("redirect")).toBe("zcode://oauth/callback");
+    // Mocha 直接导入的版本常量是 0.0.0-dev;桌面构建的注入值来自根 package.json。
+    const packageInfo = JSON.parse(
+      await readFile(new URL("../../../../../../package.json", import.meta.url), "utf8"),
+    ) as { version: string };
+    expect(bridgeUrl.searchParams.get("app_version")).toBe(packageInfo.version);
+    await clickTestIdByDom(TID_OAUTH_COPY_LOGIN_LINK);
+    await browser.waitUntil(
+      async () =>
+        (await browser.electron.execute((electron) => electron.clipboard.readText())) === openedUrl,
+      { timeout: 10_000, timeoutMsg: "复制的国内授权链接与浏览器打开地址不一致" },
     );
     await clickTestIdByDom(TID_OAUTH_CANCEL);
     await waitForTestIdByDom(TID_LOGIN_REGION_SWITCH);
@@ -691,8 +735,8 @@ describe("OAuth 双路径完成竞态", () => {
   it("中国区保存一个主体及关联 BigModel,不使用全球区业务换证", async () => {
     const baseUrl = process.env.ZCODE_E2E_OAUTH_RACE_URL!;
     const before = await (await fetch(`${baseUrl}/__e2e/status`)).json();
-    await fetch(`${baseUrl}/__e2e/cn-ready`, { method: "POST" });
-    const result = await browser.execute(async (id) => {
+    await fetch(`${baseUrl}/__e2e/cn-ready?ready=false`, { method: "POST" });
+    const callback = await browser.execute(async (id) => {
       const element = document.querySelector(`[data-testid="${id}"]`)!;
       let fiber = (element as any)[
         Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
@@ -703,12 +747,26 @@ describe("OAuth 双路径完成竞态", () => {
         if (services?.oauthService) {
           (window as any).__cnOAuth = services.oauthService;
           await services.oauthService.startOAuthWithPolling("zai_cn");
-          return services.oauthService.pollPendingOAuth();
+          // 中转先唤起 App,带授权码的回调也不能触发客户端二次兑换。
+          return services.oauthService.handleCallback(
+            "zcode://oauth/callback?code=cn-bridge-code&state=e2e-race&channel_id=e2e-cn-bridge",
+          );
         }
         fiber = fiber.return;
       }
       throw new Error("Missing OAuth RPC accessor");
     }, TID_LOGIN_TRIGGER);
+    expect(callback).toBeNull();
+    expect(
+      await browser.execute(async () =>
+        (window as any).__cnOAuth.handleCallback(
+          "zcode://oauth/callback?code=cn-bridge-code&state=e2e-race",
+        ),
+      ),
+    ).toBeNull();
+    expect((await (await fetch(`${baseUrl}/__e2e/status`)).json()).tokenRequests).toBe(0);
+    await fetch(`${baseUrl}/__e2e/cn-ready`, { method: "POST" });
+    const result = await browser.execute(async () => (window as any).__cnOAuth.pollPendingOAuth());
     expect(result).toMatchObject({
       kind: "session",
       provider: "zai_cn",
@@ -716,6 +774,15 @@ describe("OAuth 双路径完成竞态", () => {
     });
     const credentials = await readCredentials();
     expect(credentials["oauth:active_provider"]).toBe("zai_cn");
+    expect(JSON.parse(credentials["oauth:login_attribution"]!).channel_id).toBe("e2e-cn-bridge");
+    const lateCallback = await browser.execute(async () =>
+      (window as any).__cnOAuth.handleCallback(
+        "zcode://oauth/callback?code=cn-late-code&state=e2e-race&channel_id=e2e-cn-late",
+      ),
+    );
+    expect(lateCallback).toMatchObject({ kind: "duplicate", provider: "zai_cn" });
+    credentials["oauth:login_attribution"] = (await readCredentials())["oauth:login_attribution"]!;
+    expect(JSON.parse(credentials["oauth:login_attribution"]!).channel_id).toBe("e2e-cn-late");
     expect(credentials["oauth:zai_cn:access_token"]).toBe("e30.eyJleHAiOjF9.signature");
     expect(credentials["oauth:zai:access_token"]).toBeUndefined();
     expect(credentials["oauth:bigmodel:access_token"]).toBeUndefined();
@@ -727,6 +794,7 @@ describe("OAuth 双路径完成竞态", () => {
     expect((await (await fetch(`${baseUrl}/__e2e/status`)).json()).businessExchanges).toBe(
       before.businessExchanges,
     );
+    expect((await (await fetch(`${baseUrl}/__e2e/status`)).json()).tokenRequests).toBe(0);
     expect(
       await browser.execute(
         async () => (await (window as any).__cnOAuth.restoreCachedSessionState()).status,
@@ -757,6 +825,22 @@ describe("OAuth 双路径完成竞态", () => {
     const recovered = await readCredentials();
     expect(recovered["oauth:linked_bigmodel"]).toBeUndefined();
     expect(recovered["zcodejwttoken"]).toBe(credentials["zcodejwttoken"]);
+    const cancelledCallback = await browser.execute(async () => {
+      const service = (window as any).__cnOAuth;
+      await service.startOAuthWithPolling("zai_cn");
+      await service.cancelPending("zai_cn");
+      try {
+        await service.handleCallback(
+          "zcode://oauth/callback?code=cn-cancelled&state=e2e-race&channel_id=cancelled",
+        );
+        return false;
+      } catch {
+        return true;
+      }
+    });
+    expect(cancelledCallback).toBe(true);
+    expect(await readCredentials()).toEqual(recovered);
+    expect((await (await fetch(`${baseUrl}/__e2e/status`)).json()).tokenRequests).toBe(0);
     await browser.execute(() => {
       delete (window as any).__cnOAuth;
     });

+ 11 - 15
packages/desktop/test/e2e/browser/design/browser-design-mode.test.ts

@@ -14,7 +14,6 @@ import {
   TID_BROWSER_ELEMENT_PICKER_BUTTON,
   TID_BROWSER_REFRESH_BUTTON,
   TID_SIDE_PANE_FULL_VIEW_HOST,
-  TID_SIDE_PANE_FULL_VIEW_TOGGLE,
   TID_WEB_ELEMENT_CONTEXT_CHIP,
 } from "@zcode/shared/test-ids";
 import { clearAppData, clickTestIdByDom } from "#e2e/helpers/desktop-app";
@@ -132,7 +131,7 @@ describe("BU-E2E-021:内置浏览器设计工具", () => {
 
   // 首发后界面在新任务里,它的浏览器会常驻(隐藏):在这里关掉,后面用例的 $() 才不会拿到它的元素
   afterEach(async () => {
-    // 先在还开着的(完整视图的浮动)输入框里删掉引用,再关 tab:关掉后那份引用就看不到、删不着了
+    // 先在还开着的输入框里删掉引用,再关 tab:关掉后那份引用就看不到、删不着了
     await clearElementTokens().catch(() => undefined);
     await closeBrowserTabs().catch(() => undefined);
   });
@@ -185,17 +184,13 @@ describe("BU-E2E-021:内置浏览器设计工具", () => {
     // 点 #cta:属性面板打开,输入框出现 1 个元素引用 + element-1.png
     await selectGuestElement(fixtureOrigin, "#cta");
     await waitForElementTokens(1, "点选后输入框没有出现元素引用");
-    // 设计面板只在完整视图里出:半屏选中元素自动进完整视图;退出后面板收起;再选元素又进入(!3450 SG-01)
-    await waitForFullView(true, "半屏选中元素后应自动进完整视图");
-    await clickTestIdByDom(TID_SIDE_PANE_FULL_VIEW_TOGGLE);
-    await waitForFullView(false, "点完整视图开关应退出完整视图");
+    // 选中元素不把对话挤成浮窗:留在半屏,面板在画布右侧打开(11-11 用户反馈)
     await $(`[data-testid="${TID_BROWSER_DESIGN_INSPECTOR}"]`).waitForDisplayed({
-      reverse: true,
       timeout: 10_000,
-      timeoutMsg: "退出完整视图后设计面板应收起",
+      timeoutMsg: "设计稿选中元素后应打开调整面板",
     });
-    await selectGuestElement(fixtureOrigin, "#cta");
-    await waitForFullView(true, "退出后再选元素应再次进完整视图");
+    await browser.pause(1_000);
+    await waitForFullView(false, "选中元素后不应进完整视图");
     await waitForReadyAttachment("element-1.png");
     // http 页面不是本机文件:面板写明不能直接写回
     await browser.waitUntil(
@@ -919,7 +914,7 @@ describe("BU-E2E-021:内置浏览器设计工具", () => {
     await navigate(`${fixtureOrigin}/plain`, "E2E plain page");
     await browser.pause(1_000);
     const tokensBefore = await countElementTokens();
-    await selectGuestElement(fixtureOrigin, "#plain");
+    await selectGuestElement(fixtureOrigin, "#plain", { plainPage: true });
     await waitForElementTokens(tokensBefore + 1, "普通网页点选后元素应进输入框成 token");
     if ((await readDataCount(TID_WEB_ELEMENT_CONTEXT_CHIP)) !== null) {
       throw new Error("普通网页点选后不应再出原来的元素标签");
@@ -927,11 +922,12 @@ describe("BU-E2E-021:内置浏览器设计工具", () => {
     if (await $(`[data-testid="${TID_BROWSER_DESIGN_TOOLBAR}"]`).isExisting()) {
       throw new Error("普通网页不应出现设计工具行");
     }
-    await waitForWritable("false", "普通网页的调整面板应只读");
-    if (await $("[data-design-field=fontSize]").isEnabled()) {
-      throw new Error("普通网页的调整面板字段应不可编辑");
+    // 普通网页点选只为加进聊天:不进完整视图、不弹调整面板挡页面(11-11 用户反馈)
+    await browser.pause(1_000);
+    await waitForFullView(false, "普通网页点选后不应进完整视图");
+    if (await $(`[data-testid="${TID_BROWSER_DESIGN_INSPECTOR}"]`).isExisting()) {
+      throw new Error("普通网页点选后不应打开调整面板");
     }
-    await waitForFullView(true, "普通网页点选后同样进完整视图");
 
     // 点选开着换页:退出点选、面板收起,新页面不再拦截点击(!3548 CR-01)
     await navigate(fixtureUrl, "E2E design mode");

+ 16 - 0
packages/desktop/test/e2e/conversation-session/projects/conversation-session-project-composer.test.ts

@@ -28,6 +28,22 @@ describe("输入框项目选择器", () => {
     const menu = $('[data-testid="composer-project-menu"]');
     await menu.waitForDisplayed();
     expect(await menu.$('input[placeholder="搜索项目或设备"]').isExisting()).toBe(true);
+    // 原生拖拽命中不受 DOM 层级影响;CDP 点击可绕过它,必须同时检查菜单的 no-drag。
+    expect(
+      await browser.execute(() =>
+        getComputedStyle(
+          document.querySelector('[data-testid="composer-project-menu"]')!,
+        ).getPropertyValue("-webkit-app-region"),
+      ),
+    ).toBe("no-drag");
+    await menu.$("input").click();
+    expect(
+      await browser.execute(
+        () =>
+          document.activeElement ===
+          document.querySelector('[data-testid="composer-project-menu"] input'),
+      ),
+    ).toBe(true);
     const menuNames = () =>
       browser.execute(() =>
         [

+ 7 - 1
packages/desktop/test/e2e/helpers/browser-design-mode.ts

@@ -237,11 +237,16 @@ export async function releaseHeldCapture(): Promise<void> {
 /**
  * 地址栏「选择元素」= 展示设计工具并开始点选:没在点选就先点一下按钮、等页面进入选择状态,
  * 再对 guest 元素发真实点击(shift 时加进选中),等属性面板显示 selectedCount 个选中元素。
+ * 普通网页点选不自动开属性面板(11-11),传 plainPage 时只点不等面板,调用方自己等输入框里的引用。
  */
 export async function selectGuestElement(
   urlPrefix: string,
   selector: string,
-  { shift = false, selectedCount = "1" }: { shift?: boolean; selectedCount?: string } = {},
+  {
+    shift = false,
+    selectedCount = "1",
+    plainPage = false,
+  }: { shift?: boolean; selectedCount?: string; plainPage?: boolean } = {},
 ): Promise<void> {
   const picker = $(`[data-testid="${TID_BROWSER_ELEMENT_PICKER_BUTTON}"]`);
   if ((await picker.getAttribute("aria-pressed")) !== "true") {
@@ -253,6 +258,7 @@ export async function selectGuestElement(
     { timeout: 15_000, timeoutMsg: "点「选择元素」后页面没有进入选择状态" },
   );
   await clickGuestElement(urlPrefix, selector, shift);
+  if (plainPage) return;
   await browser.waitUntil(
     async () =>
       (await browser.execute(

+ 2 - 2
packages/desktop/test/e2e/helpers/oauth-completion-race-fixture.ts

@@ -82,7 +82,7 @@ export async function prepareOAuthCompletionRaceFixture(
         );
       }
     } else if (path === "/__e2e/cn-ready") {
-      cnReady = true;
+      cnReady = new URL(request.url!, "http://fixture").searchParams.get("ready") !== "false";
       response.end("{}");
     } else if (path === "/__e2e/hold-poll") {
       pollingEnabled = false;
@@ -143,7 +143,7 @@ export async function prepareOAuthCompletionRaceFixture(
           data: {
             authorize_url:
               activeProvider === "zai_cn"
-                ? "https://example.com/cn/authorize?state=e2e-race&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback%2Fzai_cn"
+                ? "https://example.com/cn/authorize?state=e2e-race&client_id=e2e-cn-client&response_type=code&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback%2Fzai_cn"
                 : "https://example.com/authorize?state=e2e-race&channel_id=desktop-launch",
             expires_at: expiresAt,
             flow_id: "e2e-race",

+ 42 - 0
packages/desktop/test/e2e/settings/appearance/manual-review/pending/macos-font-smoothing.test.ts

@@ -0,0 +1,42 @@
+import { join } from "node:path";
+import { TID_TASK_SETTINGS_BUTTON, TID_SETTINGS_SECTION_NAV, testId } from "@zcode/shared/test-ids";
+import { waitForWorkspaceApp, DEFAULT_WORKSPACE, clickTestIdByDom } from "#e2e/helpers/desktop-app";
+
+const toggle = () => $('[data-testid="font-smoothing-switch"]');
+const smoothing = () =>
+  browser.execute(() => getComputedStyle(document.body).getPropertyValue("-webkit-font-smoothing"));
+async function openAppearance() {
+  await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
+  await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "appearance"));
+}
+
+describe("macOS 字体平滑", () => {
+  it("默认灰度平滑,切换立即生效且重载保留", async function () {
+    this.timeout(90_000);
+    await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
+    await openAppearance();
+    if (process.platform !== "darwin") {
+      expect(await toggle().isExisting()).toBe(false);
+      return;
+    }
+    await clickTestIdByDom("settings-search-open");
+    await $('[data-testid="settings-search-input"]').setValue("Font smoothing");
+    await $('[data-settings-search-result="settings.fontSmoothing"]').click();
+    await toggle().waitForDisplayed();
+    expect(await toggle().getAttribute("aria-checked")).toBe("true");
+    expect(await smoothing()).toBe("antialiased");
+    await browser.refresh();
+    await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
+    expect(await smoothing()).toBe("antialiased");
+    await openAppearance();
+    expect(await toggle().getAttribute("aria-checked")).toBe("true");
+    await browser.saveScreenshot(
+      join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "font-smoothing-enabled.png"),
+    );
+    await toggle().click();
+    await browser.waitUntil(async () => (await smoothing()) === "auto");
+    await browser.refresh();
+    await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
+    expect(await smoothing()).toBe("auto");
+  });
+});

+ 110 - 12
packages/desktop/test/e2e/ui-shell/composer/composer-voice-input.test.ts

@@ -4,6 +4,10 @@ import {
   TID_V4_COMPOSER_INPUT,
   TID_V4_COMPOSER_SEND,
   TID_V4_COMPOSER_VOICE_INPUT,
+  TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE,
+  TID_V4_COMPOSER_VOICE_PERMISSION_OPEN_SETTINGS,
+  TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE,
+  TID_V4_COMPOSER_VOICE_PERMISSION_RELAUNCH,
   TID_V4_COMPOSER_VOICE_WAVEFORM,
 } from "@zcode/shared/test-ids";
 import { readSettings, seedSettings, waitForDefaultWorkspaceReady } from "#e2e/helpers/desktop-app";
@@ -147,6 +151,15 @@ async function mockMicrophonePermission(status: "granted" | "denied") {
   await mock.mockReturnValue(status);
 }
 
+/** 系统权限被拒时点击麦克风,等待引导浮层出现 */
+async function openPermissionGuide() {
+  await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
+  await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).waitForDisplayed({
+    timeout: 5_000,
+    timeoutMsg: "权限被拒后没有显示引导浮层",
+  });
+}
+
 async function startRecording() {
   await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
   await waitForVoiceState("recording", "点击麦克风后没有进入录音状态");
@@ -484,24 +497,33 @@ describe("Composer 语音输入", () => {
     expect(await editorText()).toBe(before);
   });
 
-  it("VI-05: 系统拒绝麦克风权限时,toast 按钮打开系统麦克风设置", async function () {
+  it("VI-05: 系统拒绝麦克风权限时显示引导浮层,按钮打开系统麦克风设置", async function () {
     if (process.platform === "linux") this.skip();
     await browser.electron.restoreAllMocks();
     await mockMicrophonePermission("denied");
     const openExternal = await browser.electron.mock("shell", "openExternal");
     await openExternal.mockResolvedValue(undefined);
 
-    await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
-    await waitForToastContaining("没有麦克风权限", "权限被拒后没有提示");
-    // 系统权限被拒时不申请 ticket。
+    await openPermissionGuide();
+    // 系统权限被拒时不申请 ticket,也不再用 toast 提示。
     expect((await mockState()).ticketRequests).toHaveLength(0);
-    await browser.execute(() => {
-      const host = document.querySelector("#zcode-toast-host");
-      const button = Array.from(host?.querySelectorAll("button") ?? []).find((element) =>
-        element.textContent?.includes("打开系统设置"),
-      );
-      (button as HTMLButtonElement | undefined)?.click();
-    });
+    expect((await getToastMessages()).some((message) => message.includes("没有麦克风权限"))).toBe(
+      false,
+    );
+    // 浮层打开不移动焦点:焦点仍在输入框(beforeEach 已聚焦输入框)。
+    expect(
+      await browser.execute(
+        (id) =>
+          document.querySelector(`[data-testid="${id}"]`)?.contains(document.activeElement) ??
+          false,
+        TID_V4_COMPOSER_INPUT,
+      ),
+    ).toBe(true);
+    // 「重新授权」只在 macOS 提供。
+    expect(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE).isExisting()).toBe(
+      process.platform === "darwin",
+    );
+    await (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_OPEN_SETTINGS)).click();
     const expectedUrl =
       process.platform === "darwin"
         ? "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"
@@ -515,8 +537,84 @@ describe("Composer 语音输入", () => {
           return false;
         }
       },
-      { timeout: 5_000, timeoutMsg: `没有打开 ${expectedUrl}; toasts=${await getToastMessages()}` },
+      { timeout: 5_000, timeoutMsg: `没有打开 ${expectedUrl}` },
+    );
+    // 打开设置后浮层保留,用户返回后还能继续操作。
+    expect(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).isDisplayed()).toBe(true);
+  });
+
+  // 打包版会真实执行 tccutil 重置本机 ZCode 的麦克风记录,只在开发版 Electron 上跑(开发版跳过 tccutil)。
+  describe("macOS 重新授权", () => {
+    before(function () {
+      if (process.platform !== "darwin" || process.env.ZCODE_E2E_PACKAGED_APP_PATH?.trim()) {
+        this.skip();
+      }
+    });
+
+    it("VI-15: 重置后状态变为未询问,系统弹框允许后关闭浮层并提示已开启", async () => {
+      await browser.electron.restoreAllMocks();
+      const status = await browser.electron.mock("systemPreferences", "getMediaAccessStatus");
+      await status.mockReturnValue("denied");
+      await openPermissionGuide();
+
+      // 模拟 tccutil 重置成功:之后读到未询问,系统弹框里用户点「允许」。
+      await status.mockReturnValue("not-determined");
+      const ask = await browser.electron.mock("systemPreferences", "askForMediaAccess");
+      await ask.mockResolvedValue(true);
+      await (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE)).click();
+
+      await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).waitForExist({
+        reverse: true,
+        timeout: 5_000,
+        timeoutMsg: "重新授权成功后浮层没有关闭",
+      });
+      await waitForToastContaining("已开启麦克风权限", "重新授权成功后没有提示");
+      await expect(ask).toHaveBeenCalledWith("microphone");
+      // 不自动开始录音。
+      expect(await voiceState()).toBe("idle");
+      expect((await mockState()).ticketRequests).toHaveLength(0);
+    });
+
+    it("VI-16: 重置后当前进程仍读到 denied,浮层改为需要重启", async () => {
+      await browser.electron.restoreAllMocks();
+      await mockMicrophonePermission("denied");
+      const ask = await browser.electron.mock("systemPreferences", "askForMediaAccess");
+      await ask.mockResolvedValue(false);
+      await openPermissionGuide();
+
+      await (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE)).click();
+      await browser.waitUntil(
+        async () =>
+          (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).getAttribute(
+            "data-voice-permission-phase",
+          )) === "restart-required",
+        { timeout: 5_000, timeoutMsg: "重置后仍是 denied 时没有提示需要重启" },
+      );
+      expect(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_RELAUNCH).isDisplayed()).toBe(true);
+      // 状态没有变成未询问时不调用系统弹框。
+      await expect(ask).not.toHaveBeenCalled();
+    });
+  });
+
+  it("VI-17: 浮层打开时窗口重新获得焦点,权限已开启则关闭浮层", async function () {
+    if (process.platform === "linux") this.skip();
+    await browser.electron.restoreAllMocks();
+    const status = await browser.electron.mock("systemPreferences", "getMediaAccessStatus");
+    await status.mockReturnValue("denied");
+    await openPermissionGuide();
+
+    // 用户在系统设置里打开开关后回到 ZCode。
+    await status.mockReturnValue("granted");
+    // 浮层的 focus 监听在 React effect 中挂上,比浮层出现晚一帧;重复发送 focus,直到浮层关闭。
+    await browser.waitUntil(
+      async () => {
+        await browser.execute(() => window.dispatchEvent(new Event("focus")));
+        return !(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).isExisting());
+      },
+      { timeout: 5_000, interval: 300, timeoutMsg: "权限开启后回到窗口,浮层没有关闭" },
     );
+    await waitForToastContaining("已开启麦克风权限", "权限开启后没有提示");
+    expect(await voiceState()).toBe("idle");
   });
 
   // Host 网络 transport 只在启动时读取代理设置,所以这组用例要重启应用;放在最后,结束时恢复原代理设置。

+ 5 - 1
packages/desktop/test/fixtures/installer-nsh-smoke.nsi

@@ -17,6 +17,7 @@ SilentInstall silent
 !define APP_DESCRIPTION "ZCode NSIS smoke fixture"
 !define APP_FILENAME "ZCode"
 !define APP_ID "dev.zcode.installer-nsh-smoke"
+!define UNINSTALL_REGISTRY_KEY "Software\\ZCodeInstallerSmoke\\{7C2A992D-72BB-4F8C-8DF0-0EA8A7B1F1C3}"
 ; This fixture invokes the cleanup macro from a normal section; electron-builder's real uninstaller uses un.*.
 !ifdef BUILD_UNINSTALLER
   !define ZCODE_UNINSTALLER_FUNCTION_PREFIX ""
@@ -43,7 +44,6 @@ Var keepShortcuts
 ; 普通场景使用真实 UAC 判据,避免恒假替身掩盖插件尚未可用的编译错误。
 !addplugindir /x86-unicode "${NSIS_PLUGIN_DIR}"
 !ifndef BUILD_UNINSTALLER
-  ; electron-builder inserts customHeader after assistedInstaller.nsh generated the directory page.
   !insertmacro customHeader
   !ifdef allowToChangeInstallationDirectory
     !error "customHeader must enable shortcut preservation for manual overwrite"
@@ -106,4 +106,8 @@ Section
     !insertmacro customRemoveFiles
   !endif
 
+  ; customInstall 会向夹具专属注册表键写入 InstallLocation,运行后必须清理,
+  ; 不能在测试机上留下残留(spec:夹具不得写入真实注册表)。
+  DeleteRegKey HKCU "Software\ZCodeInstallerSmoke"
+
 SectionEnd

+ 28 - 7
packages/desktop/test/fixtures/installer-preserve-files.nsi

@@ -11,7 +11,9 @@ SilentInstall silent
 !include "LogicLib.nsh"
 
 !define APP_FILENAME "ZCode"
+!define APP_EXECUTABLE_FILENAME "ZCode.exe"
 !define APP_ID "dev.zcode.preserve-files-smoke"
+!define UNINSTALL_REGISTRY_KEY "Software\\ZCode\\InstallerPreserveFilesSmoke"
 !define isUpdated `1 == 1`
 ; This fixture has no electron-builder uninstaller.nsh section; use a normal function for log smoke coverage.
 !ifdef BUILD_UNINSTALLER
@@ -20,7 +22,7 @@ SilentInstall silent
 
 Var appExe
 ; 仅恢复场景使用旧安装目录;普通清理夹具在 /WX 下不能留下未引用变量。
-!ifdef RECOVERY_TEST
+!ifndef BUILD_UNINSTALLER
   Var installationDir
 !endif
 
@@ -28,7 +30,13 @@ Var appExe
 ; 正式构建先加载自定义 include,再由 common.nsh 声明卸载器名称。
 !define UNINSTALL_FILENAME "uninstaller.exe"
 !ifndef BUILD_UNINSTALLER
-  !insertmacro ZCodeDefineCleanupSnapshot
+  ; customHeader 已包含 ZCodeDefineCleanupSnapshot 与日志初始化函数;
+  ; 单独再展开会导致宏重复定义。
+  !insertmacro customHeader
+
+  Function .onInit
+    !insertmacro preInit
+  FunctionEnd
 !endif
 
 Section
@@ -58,14 +66,21 @@ Section
   FileWrite $0 "keep me"
   FileClose $0
   !ifdef RECOVERY_TEST
+    FileOpen $0 "$INSTDIR\ZCode.exe" w
+    FileWrite $0 "old application payload"
+    FileClose $0
     InitPluginsDir
     File /oname=$PLUGINSDIR\old-cleanup.exe "${OLD_CLEANUP_EXE}"
     StrCpy $installationDir "$INSTDIR"
     !ifdef BACKUP_FAILURE
-      ; 独占源文件,让 CopyFileW 确定失败;原安装文件不能被旧卸载器删除。
-      System::Call 'kernel32::CreateFileW(w "$INSTDIR\ZCode.exe", i 0x80000000, i 0, p 0, i 3, i 0, p 0) p.R8'
+      ; 先备份主程序,再用独占句柄阻止下一项复制,验证半份备份不能用于恢复。
+      System::Call 'kernel32::CreateFileW(w "$INSTDIR\owned-by-zcode.txt", i 0x80000000, i 0, p 0, i 3, i 0, p 0) p.R8'
     !endif
     !insertmacro customOldUninstallPrepare
+    !ifdef BACKUP_FAILURE
+      ; 仅让备份失败;旧卸载和新文件写入不再受此故障句柄影响。
+      System::Call 'kernel32::CloseHandle(p R8)'
+    !endif
     FileOpen $8 "$INSTDIR\backup-dir.txt" w
     FileWrite $8 "$ZCodeCleanupBackup"
     FileClose $8
@@ -75,6 +90,12 @@ Section
       ; 同名目录阻止恢复主程序,必须保留备份,不能误报恢复成功。
       CreateDirectory "$INSTDIR\ZCode.exe"
     !endif
+    !ifdef BACKUP_DELETE_FAILURE
+      ; 句柄保持打开,阻止安装器删除备份目录;关闭会让 RMDir 成功,场景失效。
+      CreateDirectory "$ZCodeCleanupBackup\hold"
+      FileOpen $7 "$ZCodeCleanupBackup\hold\locked.txt" w
+      FileWrite $7 "keep backup"
+    !endif
     ${If} $R0 != 0
       !insertmacro customOldUninstallRetryFailed
     ${EndIf}
@@ -91,7 +112,7 @@ Section
   zcodeOwnedRemoved:
     StrCpy $1 "removed"
   zcodeWriteMarker:
-    FileOpen $0 "$INSTDIR\remove-result.txt" w
-    FileWrite $0 "$1"
-    FileClose $0
+  FileOpen $0 "$INSTDIR\remove-result.txt" w
+  FileWrite $0 "$1"
+  FileClose $0
 SectionEnd

+ 2 - 0
packages/desktop/test/nsis-install-section-patch.test.ts

@@ -116,6 +116,8 @@ describe("NSIS old uninstaller cleanup protection", () => {
     expect(patched.indexOf("!insertmacro customOldUninstallPrepare")).toBeLessThan(
       patched.indexOf("UninstallLoop:"),
     );
+    expect(patched).toContain("!ifmacrodef customOldUninstallPrepare\n  !insertmacro customOldUninstallPrepare\n!endif");
+    expect(patched).not.toContain("ZCodeStopPreviousInstallProcesses");
     expect(patched.indexOf("!insertmacro customOldUninstallRetryFailed")).toBeGreaterThan(
       patched.indexOf("UninstallLoop:"),
     );

+ 44 - 1
packages/desktop/test/windowsInstallerCompile.test.ts

@@ -1,5 +1,5 @@
 import { execFile } from "node:child_process";
-import { mkdtemp, rm, stat } from "node:fs/promises";
+import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
 import { createRequire } from "node:module";
 import { tmpdir } from "node:os";
 import { dirname, join, resolve } from "node:path";
@@ -53,6 +53,7 @@ it("compiles real UAC calls when the plugin directory follows the custom include
         `-DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${join(builderDir, "templates/nsis/include")}`,
         `-DNSIS_PLUGIN_DIR=${join(pluginsDir, "x86-unicode")}`,
         `-DZCODE_INSTALLER_NSH=${join(desktopDir, "build/installer.nsh")}`,
+        `-DZCODE_INSTALLER_PROCESS_HELPER=${import.meta.filename}`,
         `-DFIXTURE_EXE=${import.meta.filename}`,
         `-DOUTPUT_FILE=${output}`,
         `-DDEFAULT_LOG_PATH=${join(temp, "default.log")}`,
@@ -78,6 +79,7 @@ it("compiles real UAC calls when the plugin directory follows the custom include
           `-DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${join(builderDir, "templates/nsis/include")}`,
           `-DNSIS_PLUGIN_DIR=${join(pluginsDir, "x86-unicode")}`,
           `-DZCODE_INSTALLER_NSH=${join(desktopDir, "build/installer.nsh")}`,
+          `-DZCODE_INSTALLER_PROCESS_HELPER=${import.meta.filename}`,
           `-DFIXTURE_EXE=${import.meta.filename}`,
           `-DOUTPUT_FILE=${recoveryOutput}`,
           "-DRECOVERY_TEST",
@@ -89,6 +91,47 @@ it("compiles real UAC calls when the plugin directory follows the custom include
       );
       expect((await stat(recoveryOutput)).size).toBeGreaterThan(0);
     }
+
+    // CR-01 回归:普通 NSIS 没有 APP_DIR_*;不传测试专用 define 时,必须能从 afterPack
+    // 生成的按架构 define 文件解析 helper,缺失时明确失败而不是静默打出无收口的安装包。
+    const generatedDir = join(desktopDir, "build", "generated");
+    const generatedDefine = join(generatedDir, "zcode-process-helper-x64.nsh");
+    const officialDefineArgs = [
+      "-V2",
+      "-INPUTCHARSET",
+      "UTF8",
+      `-DNSIS_INCLUDE_DIR=${join(nsisDir, "Include")}`,
+      `-DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${join(builderDir, "templates/nsis/include")}`,
+      `-DNSIS_PLUGIN_DIR=${join(pluginsDir, "x86-unicode")}`,
+      `-DZCODE_INSTALLER_NSH=${join(desktopDir, "build/installer.nsh")}`,
+      `-DFIXTURE_EXE=${import.meta.filename}`,
+      `-DOUTPUT_FILE=${join(temp, "official-define.exe")}`,
+      "-DRECOVERY_TEST",
+      `-DOLD_CLEANUP_EXE=${join(temp, "uninstaller.exe")}`,
+      join(desktopDir, "test/fixtures/installer-preserve-files.nsi"),
+    ];
+    await mkdir(generatedDir, { recursive: true });
+    await writeFile(
+      generatedDefine,
+      `!define ZCODE_INSTALLER_PROCESS_HELPER "${import.meta.filename.replaceAll("$", "$$")}"\n`,
+      "utf8",
+    );
+    try {
+      const official = await execFileAsync(compiler, officialDefineArgs, {
+        env: { ...process.env, ...makeNsis.env },
+      });
+      expect(`${official.stdout}${official.stderr}`).not.toContain("warning 6000");
+      expect((await stat(join(temp, "official-define.exe"))).size).toBeGreaterThan(0);
+      // 生成文件缺失时必须命中明确 !error,而不是回退到 APP_64 压缩包宏。
+      await rm(generatedDefine, { force: true });
+      await expect(
+        execFileAsync(compiler, officialDefineArgs, {
+          env: { ...process.env, ...makeNsis.env },
+        }),
+      ).rejects.toThrow(/ZCODE_INSTALLER_PROCESS_HELPER or generated define/);
+    } finally {
+      await rm(generatedDir, { recursive: true, force: true });
+    }
   } finally {
     await rm(temp, { recursive: true, force: true });
   }

+ 11 - 1
packages/services/src/feedback/compactLogArchive.ts

@@ -1,5 +1,7 @@
 import { rm } from "node:fs/promises";
 import { join } from "node:path";
+import { homedir } from "node:os";
+import { CLI_MEMORY_DIAGNOSTIC_DIRECTORY } from "@zcode/shared";
 import { getAppConfigDir, getFeedbackLogArchiveDir } from "../paths.js";
 import { createFeedbackDiagnosticArchive } from "./feedbackLogArchive.js";
 
@@ -21,7 +23,15 @@ export async function prepareCompactLogArchive(options?: {
     return options.createFullArchive(sourceDir, { onProgress: options.onProgress });
   }
   return createFeedbackDiagnosticArchive({
-    sources: [{ directory: join(sourceDir, "logs"), archivePrefix: "logs" }],
+    sources: [
+      {
+        directory: join(homedir(), ".zcode", "cli", CLI_MEMORY_DIAGNOSTIC_DIRECTORY),
+        archivePrefix: ".zcode/cli/memory-diagnostics",
+        contentPolicy: "cli-memory",
+        onlyCurrentDay: false,
+      },
+      { directory: join(sourceDir, "logs"), archivePrefix: "logs" },
+    ],
     outputRootDir: getFeedbackLogArchiveDir(),
     ...(!options?.full ? { maxTotalBytes: 2 * 1024 * 1024 } : {}),
     onProgress: options?.onProgress,

+ 51 - 10
packages/services/src/feedback/feedbackLogArchive.ts

@@ -4,7 +4,15 @@ import { arch, platform, release } from "node:os";
 import { join, posix } from "node:path";
 import { pipeline } from "node:stream/promises";
 import { ZipFile } from "yazl";
-import { redactFeedbackText, ZCODE_VERSION, ZCODE_COMMIT } from "@zcode/shared";
+import {
+  redactFeedbackText,
+  ZCODE_VERSION,
+  ZCODE_COMMIT,
+  CLI_MEMORY_FILE_PATTERN,
+  CLI_MEMORY_MAX_FILE_BYTES,
+  CLI_MEMORY_MAX_FILES,
+  sanitizeCliMemoryDiagnostic,
+} from "@zcode/shared";
 
 const MAX_FILE_BYTES = 8 * 1024 * 1024;
 const MAX_TOTAL_BYTES = 32 * 1024 * 1024;
@@ -18,7 +26,7 @@ export interface FeedbackLogSource {
   /** 默认只收集本地当天修改的文件;配置文件可关闭该限制。 */
   onlyCurrentDay?: boolean;
   /** 配置文件使用结构化安全投影,避免把插件自定义敏感项上传。 */
-  contentPolicy?: "diagnostic" | "cli-config";
+  contentPolicy?: "diagnostic" | "cli-config" | "cli-memory";
 }
 
 function decodeDiagnosticLog(buffer: Buffer): string | null {
@@ -154,6 +162,15 @@ function sanitizeCliConfig(text: string): string | null {
   return redactFeedbackText(JSON.stringify(projection, null, 2), { diagnostic: true });
 }
 
+function sanitizeCliMemory(text: string): string | null {
+  try {
+    const record = sanitizeCliMemoryDiagnostic(JSON.parse(text));
+    return record ? JSON.stringify(record) + "\n" : null;
+  } catch {
+    return null;
+  }
+}
+
 /** 反馈上传唯一归档入口:白名单来源、有界读取、无法安全解码时禁止原文兜底。 */
 export async function createFeedbackDiagnosticArchive(options: {
   sources: readonly FeedbackLogSource[];
@@ -181,6 +198,7 @@ export async function createFeedbackDiagnosticArchive(options: {
   try {
     options.onProgress?.({ processedBytes: 0, totalBytes: 0 });
     for (const source of options.sources) {
+      let memoryFiles = 0;
       // 不跟随诊断根目录本身的链接;规范化系统目录别名(如 macOS /var)。
       const root = await realpath(source.directory).catch(() => null);
       if (!root || !(await lstat(source.directory).catch(() => null))?.isDirectory()) continue;
@@ -193,7 +211,12 @@ export async function createFeedbackDiagnosticArchive(options: {
           const absolutePath = join(directory, entry.name);
           const name = posix.join(prefix, entry.name);
           const isExplicitFileSource = source.includeFileNames !== undefined;
-          if (entry.isDirectory() && !source.exitLogsOnly && !isExplicitFileSource) {
+          if (
+            entry.isDirectory() &&
+            !source.exitLogsOnly &&
+            !isExplicitFileSource &&
+            source.contentPolicy !== "cli-memory"
+          ) {
             await walk(absolutePath, name, depth + 1);
             continue;
           }
@@ -206,6 +229,11 @@ export async function createFeedbackDiagnosticArchive(options: {
                   : /(?:\.log(?:\.\d+)?|\.jsonl|\.ndjson)$/i.test(entry.name)))
           )
             continue;
+          if (
+            source.contentPolicy === "cli-memory" &&
+            (!CLI_MEMORY_FILE_PATTERN.test(entry.name) || memoryFiles >= CLI_MEMORY_MAX_FILES)
+          )
+            continue;
           if ((await realpath(absolutePath).catch(() => null)) !== absolutePath) {
             skipLogFile("unsafe-path");
             continue;
@@ -214,7 +242,10 @@ export async function createFeedbackDiagnosticArchive(options: {
           if (
             !info?.isFile() ||
             info.nlink !== 1 ||
-            info.size > MAX_FILE_BYTES ||
+            info.size >
+              (source.contentPolicy === "cli-memory"
+                ? CLI_MEMORY_MAX_FILE_BYTES
+                : MAX_FILE_BYTES) ||
             totalBytes + info.size > budget ||
             (source.onlyCurrentDay !== false && !isToday(info.mtimeMs))
           ) {
@@ -238,7 +269,10 @@ export async function createFeedbackDiagnosticArchive(options: {
               opened.ino !== info.ino ||
               opened.dev !== info.dev ||
               (source.onlyCurrentDay !== false && !isToday(opened.mtimeMs)) ||
-              opened.size > MAX_FILE_BYTES ||
+              opened.size >
+                (source.contentPolicy === "cli-memory"
+                  ? CLI_MEMORY_MAX_FILE_BYTES
+                  : MAX_FILE_BYTES) ||
               totalBytes + opened.size > budget
             ) {
               skipLogFile("opened-file-policy");
@@ -263,13 +297,20 @@ export async function createFeedbackDiagnosticArchive(options: {
               continue;
             }
             const sanitizedText =
-              source.contentPolicy === "cli-config"
-                ? sanitizeCliConfig(text)
-                : redactFeedbackText(text, { diagnostic: true });
+              source.contentPolicy === "cli-memory"
+                ? sanitizeCliMemory(text)
+                : source.contentPolicy === "cli-config"
+                  ? sanitizeCliConfig(text)
+                  : redactFeedbackText(text, { diagnostic: true });
             if (sanitizedText === null) {
-              skipLogFile("invalid-config");
+              skipLogFile(
+                source.contentPolicy === "cli-memory"
+                  ? "invalid-memory-diagnostic"
+                  : "invalid-config",
+              );
               continue;
             }
+            if (source.contentPolicy === "cli-memory") memoryFiles += 1;
             const data = Buffer.from(sanitizedText);
             if (data.length > MAX_FILE_BYTES || totalBytes + data.length > budget) {
               skipLogFile("redacted-size-limit");
@@ -301,7 +342,7 @@ export async function createFeedbackDiagnosticArchive(options: {
           `includedLogFiles: ${entries.length}`,
           `skippedLogFiles: ${Object.values(skippedLogFilesByReason).reduce((sum, count) => sum + count, 0)}`,
           `skippedLogFilesByReason: ${JSON.stringify(skippedLogFilesByReason)}`,
-          "Scope: diagnostic text log files modified today (local time), plus an explicit non-sensitive CLI config projection; credentials and structured payloads redacted.",
+          "Scope: diagnostic text logs modified today, bounded CLI memory evidence and a non-sensitive CLI config projection; credentials and payloads redacted.",
         ].join("\n"),
       ),
       "about.txt",

+ 27 - 4
packages/services/src/oauth/oauthService.ts

@@ -804,10 +804,12 @@ export class OAuthService implements IOAuthService {
       // BigModel CLI callback 的失败页会截断原有 Desktop deep link 回调体验。
       // flow 仍由 Host 轮询,但浏览器回调恢复到官网中转页,再透传到 zcode://oauth/callback。
       authorizeUrl.searchParams.set("redirect", buildDesktopOAuthRedirectUriFromEnv(this.env));
-    } else if (provider === ZAI_PROVIDER_ID) {
-      // Z.AI 后端 init 仍可能返回 provider-specific callback,导致回跳行为与 BigModel 不一致。
-      // Desktop 统一改写为官网中转页,再由官网透传到 zcode://oauth/callback。
-      authorizeUrl.searchParams.set("redirect_uri", buildDesktopOAuthRedirectUriFromEnv(this.env));
+    } else if (isZaiOAuthProvider(provider)) {
+      // 国内渠道曾漏过中转改写;显式传渠道,避免官网把国内授权码送往海外回调。
+      // 只改回调地址,授权站、client_id 和 state 仍由服务端决定。
+      const redirectUri = new URL(buildDesktopOAuthRedirectUriFromEnv(this.env));
+      if (provider === ZAI_CN_PROVIDER_ID) redirectUri.searchParams.set("provider", provider);
+      authorizeUrl.searchParams.set("redirect_uri", redirectUri.toString());
     }
     const state = authorizeUrl.searchParams.get("state")?.trim();
     const remainingLifetimeMs = expiresAt - this.now();
@@ -1129,6 +1131,27 @@ export class OAuthService implements IOAuthService {
       };
     }
 
+    if (pending.provider === ZAI_CN_PROVIDER_ID && pending.polling) {
+      // 官网已把国内授权码交给后端;客户端再次兑换会争抢一次性 code。
+      // 唤起只补归因,登录仍由同一 flow 的 polling 提交;旧回调不能写入新会话。
+      const generation = this.oauthFlowStartGeneration;
+      return this.runSessionMutation(async () => {
+        const completed = this.recentlyCompletedPollingState;
+        const sameFlow =
+          this.oauthFlowStartGeneration === generation &&
+          (this.pendingState === pending ||
+            (!this.pendingState &&
+              completed?.state === pending.state &&
+              completed.generation === generation &&
+              this.now() < completed.expiresAt));
+        if (sameFlow && attribution) {
+          const save = () => this.repo.saveLoginAttribution(attribution);
+          await (pending.credentialGuard ? pending.credentialGuard(save) : save());
+        }
+        return null;
+      });
+    }
+
     const adapter = this.getAdapter(pending.provider);
     const fallbackProfile: OAuthUserProfile = {
       id: "unknown",

+ 7 - 0
packages/shared/src/channels.ts

@@ -74,6 +74,7 @@ import type {
   SaveFileRequest,
   SaveFileResult,
   PrintPageToPdfResult,
+  MicrophoneAccessResetResult,
   MicrophoneAccessResult,
   MicrophoneSettingsTarget,
   CaptureBrowserGuestPageRequest,
@@ -254,6 +255,8 @@ export const PlatformChannels = {
   PrintToPdf: "zcode:print-to-pdf",
   /** Renderer → Main:检查并按需请求系统麦克风权限 */
   MicrophoneAccess: "zcode:microphone-access",
+  /** Renderer → Main:macOS 重置本 App 的麦克风授权记录并重新请求 */
+  ResetMicrophoneAccess: "zcode:reset-microphone-access",
   /** Renderer → Main:打开系统麦克风权限 / 声音输入设置页 */
   OpenMicrophoneSettings: "zcode:open-microphone-settings",
   /** Renderer → Main:在 main 截取内置浏览器 guest 当前视口为 PNG(renderer 侧 capturePage 会崩溃) */
@@ -888,6 +891,10 @@ export interface PlatformChannelMap {
     request: void;
     response: MicrophoneAccessResult;
   };
+  [PlatformChannels.ResetMicrophoneAccess]: {
+    request: void;
+    response: MicrophoneAccessResetResult;
+  };
   [PlatformChannels.OpenMicrophoneSettings]: {
     request: MicrophoneSettingsTarget;
     response: boolean;

+ 1 - 1
packages/shared/src/index.ts

@@ -164,7 +164,6 @@ export {
   BROWSER_VIEW_RESTORE_BOOTSTRAP_URL,
   LOCAL_MEDIA_PREVIEW_SCHEME,
   BROWSER_VIEW_DRAFT_SESSION_ID,
-
   BROWSER_LOCAL_PREVIEW_SCHEME,
   browserPreviewSourceUrl,
   DesktopCommandIds,
@@ -245,6 +244,7 @@ export type {
   SaveFileRequest,
   SaveFileResult,
   PrintPageToPdfResult,
+  MicrophoneAccessResetResult,
   MicrophoneAccessResult,
   MicrophoneSettingsTarget,
   CaptureBrowserGuestPageClip,

+ 151 - 0
packages/shared/src/memoryDiagnostics.ts

@@ -7,6 +7,157 @@
 
 export type MemorySampleRole = "main" | "renderer" | "utility_host" | "agent_node";
 
+export const CLI_MEMORY_DIAGNOSTIC_DIRECTORY = "memory-diagnostics";
+export const CLI_MEMORY_MAX_FILES = 16;
+export const CLI_MEMORY_MAX_FILE_BYTES = 64 * 1024;
+export const CLI_MEMORY_MAX_SAMPLES = 8;
+export const CLI_MEMORY_MAX_ALLOCATIONS = 32;
+export const CLI_MEMORY_MAX_STACK_DEPTH = 8;
+export const CLI_MEMORY_FILE_PATTERN = /^memory-[0-9]+-[a-f0-9-]{36}\.jsonl$/;
+const CLI_MEMORY_COUNTER_KEYS = [
+  "sessions",
+  "eventRows",
+  "eventEvicted",
+  "eventTransientRetained",
+  "v4.publishers",
+  "v4.detachedLive",
+  "v4.detachedTerminal",
+  "v4.rawSeqStates",
+  "v4.hydrations",
+  "v4.historyOpenings",
+  "v4.binaryCacheEntries",
+  "v4.binaryCacheBytes",
+] as const;
+const CLI_MEMORY_FIELDS = [
+  "rss",
+  "heapUsed",
+  "heapTotal",
+  "external",
+  "arrayBuffers",
+  "heapLimit",
+] as const;
+
+export interface CliMemoryReading {
+  at: number;
+  rss: number;
+  heapUsed: number;
+  heapTotal: number;
+  external: number;
+  arrayBuffers: number;
+  heapLimit: number;
+  counters: Record<string, number>;
+}
+
+export interface CliMemoryAllocation {
+  bytes: number;
+  stack: Array<{ name: string; line: number; column: number }>;
+}
+
+export interface CliMemoryDiagnostic {
+  format: "zcode-cli-memory-v1";
+  timestamp: number;
+  instanceId: string;
+  pid: number;
+  version: string;
+  commit: string;
+  node: string;
+  v8: string;
+  bundleSha256: string;
+  sampler: {
+    state: "active" | "unsupported" | "budget-exceeded" | "error";
+    intervalBytes: number;
+    windowStartedAt: number;
+    profileCapturedAt: number;
+    durationMs: number;
+  };
+  samples: CliMemoryReading[];
+  allocations: CliMemoryAllocation[];
+}
+
+/**
+ * 诊断上传只投影计数与打包位置,不能用通用 stack/body 脱敏把有效分配证据整段抹掉。
+ * 未知字段全部丢弃;不信任磁盘文件里的路径、源码、消息或环境变量。
+ */
+export function sanitizeCliMemoryDiagnostic(value: unknown): CliMemoryDiagnostic | null {
+  const record = (candidate: unknown): Record<string, unknown> | null =>
+    candidate !== null && typeof candidate === "object" && !Array.isArray(candidate)
+      ? (candidate as Record<string, unknown>)
+      : null;
+  const number = (candidate: unknown): number =>
+    typeof candidate === "number" && Number.isFinite(candidate) && candidate >= 0 ? candidate : 0;
+  const token = (candidate: unknown): string =>
+    typeof candidate === "string" && /^[a-zA-Z0-9._-]{1,80}$/.test(candidate) ? candidate : "";
+  const raw = record(value);
+  if (!raw || raw.format !== "zcode-cli-memory-v1" || !Array.isArray(raw.samples)) return null;
+  const sampler = record(raw.sampler);
+  if (
+    !sampler ||
+    !["active", "unsupported", "budget-exceeded", "error"].includes(String(sampler.state))
+  )
+    return null;
+  const samples: CliMemoryReading[] = [];
+  for (const item of raw.samples.slice(-CLI_MEMORY_MAX_SAMPLES)) {
+    const row = record(item);
+    if (!row) continue;
+    const counters: Record<string, number> = {};
+    const rawCounters = record(row.counters);
+    for (const key of CLI_MEMORY_COUNTER_KEYS) {
+      if (rawCounters && typeof rawCounters[key] === "number")
+        counters[key] = number(rawCounters[key]);
+    }
+    const sample = { at: number(row.at), counters } as CliMemoryReading;
+    for (const key of CLI_MEMORY_FIELDS) sample[key] = number(row[key]);
+    samples.push(sample);
+  }
+  const allocations: CliMemoryAllocation[] = [];
+  if (Array.isArray(raw.allocations)) {
+    for (const item of raw.allocations.slice(0, CLI_MEMORY_MAX_ALLOCATIONS)) {
+      const row = record(item);
+      if (!row || !Array.isArray(row.stack)) continue;
+      const stack: CliMemoryAllocation["stack"] = [];
+      for (const itemFrame of row.stack.slice(-CLI_MEMORY_MAX_STACK_DEPTH)) {
+        const frame = record(itemFrame);
+        if (!frame) continue;
+        stack.push({
+          name:
+            typeof frame.name === "string" && /^[a-zA-Z0-9_$.[\]<>-]{0,64}$/.test(frame.name)
+              ? frame.name
+              : "",
+          line: number(frame.line),
+          column: number(frame.column),
+        });
+      }
+      allocations.push({ bytes: number(row.bytes), stack });
+    }
+  }
+  return {
+    format: "zcode-cli-memory-v1",
+    timestamp: number(raw.timestamp),
+    instanceId:
+      typeof raw.instanceId === "string" && /^[a-f0-9-]{36}$/.test(raw.instanceId)
+        ? raw.instanceId
+        : "",
+    pid: number(raw.pid),
+    version: token(raw.version),
+    commit: token(raw.commit),
+    node: token(raw.node),
+    v8: token(raw.v8),
+    bundleSha256:
+      typeof raw.bundleSha256 === "string" && /^[a-f0-9]{64}$/.test(raw.bundleSha256)
+        ? raw.bundleSha256
+        : "",
+    sampler: {
+      state: sampler.state as CliMemoryDiagnostic["sampler"]["state"],
+      intervalBytes: number(sampler.intervalBytes),
+      windowStartedAt: number(sampler.windowStartedAt),
+      profileCapturedAt: number(sampler.profileCapturedAt),
+      durationMs: number(sampler.durationMs),
+    },
+    samples,
+    allocations,
+  };
+}
+
 export type MemorySampleWriteReason = "first" | "changed" | "heartbeat";
 
 export interface MemorySampleFields {

+ 11 - 0
packages/shared/src/platform.ts

@@ -384,6 +384,15 @@ export interface PrintPageToPdfResult {
  */
 export type MicrophoneAccessResult = "granted" | "denied" | "unsupported";
 
+/**
+ * macOS「重新授权」结果(docs/chat/composer-voice-input.md「权限引导浮层」)。
+ * - granted:已获得权限
+ * - denied:重置后系统弹框中用户仍选择拒绝
+ * - restart-required:重置后当前进程仍读到 denied,重启 ZCode 后才会弹框
+ * - failed:不能重置(非 macOS、MDM 限制、tccutil 失败),改由系统设置页开启
+ */
+export type MicrophoneAccessResetResult = "granted" | "denied" | "restart-required" | "failed";
+
 /** privacy:系统麦克风隐私页;sound:系统声音输入设备页 */
 export type MicrophoneSettingsTarget = "privacy" | "sound";
 
@@ -842,6 +851,8 @@ export interface IPlatformService {
    */
   microphone?: {
     ensureAccess(): Promise<MicrophoneAccessResult>;
+    /** macOS:重置 ZCode 自己的麦克风授权记录并重新请求;其他系统返回 failed */
+    resetAccess(): Promise<MicrophoneAccessResetResult>;
     openSettings(target: MicrophoneSettingsTarget): Promise<boolean>;
   };
 

+ 10 - 0
packages/shared/src/test-ids.ts

@@ -637,6 +637,16 @@ export const TID_V4_COMPOSER_SEND = "v4-composer-send";
 export const TID_V4_COMPOSER_VOICE_INPUT = "v4-composer-voice-input";
 /** v4 composer 语音输入音量点阵(data-voice-active-dots 为当前有音量的点数) */
 export const TID_V4_COMPOSER_VOICE_WAVEFORM = "v4-composer-voice-waveform";
+/** v4 composer 麦克风权限引导浮层(data-voice-permission-phase 为 denied / restart-required) */
+export const TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE = "v4-composer-voice-permission-guide";
+/** 麦克风权限引导浮层:重新授权(仅 macOS) */
+export const TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE =
+  "v4-composer-voice-permission-reauthorize";
+/** 麦克风权限引导浮层:打开系统设置 */
+export const TID_V4_COMPOSER_VOICE_PERMISSION_OPEN_SETTINGS =
+  "v4-composer-voice-permission-open-settings";
+/** 麦克风权限引导浮层:重启 ZCode */
+export const TID_V4_COMPOSER_VOICE_PERMISSION_RELAUNCH = "v4-composer-voice-permission-relaunch";
 /** v4 暂停队列发送确认:清空队列并发送 */
 export const TID_V4_COMPOSER_CLEAR_QUEUE_SEND = "v4-composer-clear-queue-send";
 /** v4 暂停队列发送确认:保留队列并发送 */

+ 1 - 17
packages/ui/src/App.tsx

@@ -10,11 +10,7 @@ import { useAppPanels } from "@/hooks/useAppPanels.js";
 import { useGitAutoRefresh } from "@/hooks/useGitAutoRefresh.js";
 import { useGitRepository } from "@/hooks/useGitRepository.js";
 import { useAppKeyboard } from "@/hooks/useAppKeyboard.js";
-import {
-  setSidePaneFullViewActive,
-  SIDE_PANE_FULL_VIEW_ENTER_REQUEST_EVENT,
-  useSidePaneFullView,
-} from "@/side-pane-full-view/index.js";
+import { useSidePaneFullView } from "@/side-pane-full-view/index.js";
 import { usePlatform } from "@/hooks/usePlatform.js";
 import { useWorkspaceProviderConfigFile } from "@/hooks/useWorkspaceProviderConfigFile.js";
 import { useWorkspaceActiveTaskState } from "@/hooks/useWorkspaceActiveTaskState.js";
@@ -604,18 +600,6 @@ export function App({
     },
     [markSidePaneDraftPromotion, workspaceAbsPath, workspaceIdentity],
   );
-  // 面板里的内容(设计稿点选打开设计面板)请求铺满:只在面板开着、还不在完整视图时进,enter 自己也会兜住
-  const enterSidePaneFullView = sidePaneFullView.enter;
-  const isSidePaneFullViewActive = sidePaneFullView.fullView !== null;
-  useEffect(() => {
-    setSidePaneFullViewActive(isSidePaneFullViewActive);
-  }, [isSidePaneFullViewActive]);
-  useEffect(() => {
-    if (!supportsSidePaneFullView || !isSidePaneOpen) return;
-    window.addEventListener(SIDE_PANE_FULL_VIEW_ENTER_REQUEST_EVENT, enterSidePaneFullView);
-    return () =>
-      window.removeEventListener(SIDE_PANE_FULL_VIEW_ENTER_REQUEST_EVENT, enterSidePaneFullView);
-  }, [enterSidePaneFullView, isSidePaneOpen, supportsSidePaneFullView]);
   const handleToggleSidePaneFullView = useCallback(() => {
     // 面板关闭时快捷键先打开面板再进入完整视图;记录先写入,面板展开后即生效。
     if (!sidePaneFullView.fullView && !isSidePaneOpen) {

+ 1 - 1
packages/ui/src/ElicitationDialog.tsx

@@ -981,7 +981,6 @@ function ElicitationDialogContent({
           >
             <div className="flex items-start justify-between gap-3">
               <div className="min-w-0 flex-1 text-ui-base font-medium leading-5">
-                <InteractionRequestOriginBadge origin={request.origin} className="mr-2" />
                 {titleHeader ? (
                   <Badge
                     variant="outline"
@@ -1002,6 +1001,7 @@ function ElicitationDialogContent({
                 >
                   {titleQuestion}
                 </span>
+                <InteractionRequestOriginBadge origin={request.origin} className="mt-2" />
                 {shouldOfferQuestionCollapse ? (
                   <Button
                     type="button"

+ 8 - 6
packages/ui/src/InteractionRequestOriginBadge.tsx

@@ -1,6 +1,5 @@
 import type { ZCodeInteractionRequestOrigin } from "@zcode/shared";
 import { cn } from "@/components/lib/utils.js";
-import { Badge } from "@/components/ui/badge.js";
 import { useZCodeIntl } from "@/i18n/IntlProvider.js";
 
 export function InteractionRequestOriginBadge({
@@ -16,7 +15,7 @@ export function InteractionRequestOriginBadge({
   }
 
   // description 点名是哪个子代理在问(动态工作流子代理为 `<名字> (<siteId>@<ordinal>)`,
-  // docs/dynamic-workflow/launch.md「Permissions inside a run」);徽标截断,完整文本留在 tooltip。
+  // docs/dynamic-workflow/launch.md「Permissions inside a run」);来源描述完整换行显示。
   const description = origin.description?.trim();
   const label = description
     ? intl.formatMessage({ id: "chat.interactionOrigin.subagent.named" }, { description })
@@ -34,13 +33,16 @@ export function InteractionRequestOriginBadge({
         );
 
   return (
-    <Badge
-      variant="outline"
+    <span
       title={title}
       data-interaction-origin-badge="subagent"
-      className={cn("max-w-40 align-baseline text-ui-base truncate", className)}
+      className={cn(
+        "block w-full min-w-0 basis-full whitespace-normal [overflow-wrap:anywhere] text-ui-base font-normal text-foreground-subtle",
+        className,
+      )}
     >
+      {/* 完整换行避免长名称被裁切,连续的实例标识也不能撑出窄屏容器。 */}
       {label}
-    </Badge>
+    </span>
   );
 }

+ 6 - 0
packages/ui/src/SettingsPage.tsx

@@ -451,6 +451,8 @@ export function SettingsPage({
   const setTheme = useZCodeStore((state) => state.setTheme);
   const codePreviewSettings = useZCodeStore((state) => state.codePreviewSettings);
   const setCodePreviewSettings = useZCodeStore((state) => state.setCodePreviewSettings);
+  const fontSmoothingEnabled = useZCodeStore((state) => state.fontSmoothingEnabled);
+  const setFontSmoothingEnabled = useZCodeStore((state) => state.setFontSmoothingEnabled);
   const uiFontSizePx = useZCodeStore((state) => state.uiFontSizePx);
   const setUiFontSizePx = useZCodeStore((state) => state.setUiFontSizePx);
   const hideProjectDeviceNames = useZCodeStore((state) => state.hideProjectDeviceNames);
@@ -1569,6 +1571,7 @@ export function SettingsPage({
                     windowsHost: hostPlatform === "win32",
                     tray: Boolean(isWindowsDesktop || isLinuxDesktop),
                     notWindows: !isWindowsDesktop,
+                    macDesktop: Boolean(isDesktop && isMacDesktop),
                     computerUse: resolveComputerUseAvailability({
                       isDesktop: Boolean(isDesktop),
                       isMacDesktop: Boolean(isMacDesktop),
@@ -2037,6 +2040,9 @@ export function SettingsPage({
                             )
                           ) : activeSection === "appearance" ? (
                             <AppearanceSectionContent
+                              isMacDesktop={Boolean(isDesktop && isMacDesktop)}
+                              fontSmoothingEnabled={fontSmoothingEnabled}
+                              setFontSmoothingEnabled={setFontSmoothingEnabled}
                               codePreviewSettings={codePreviewSettings}
                               setCodePreviewSettings={handleCodePreviewSettingsChange}
                               theme={theme}

+ 40 - 54
packages/ui/src/ToolCallBlocks/QueuedSummaryContent.tsx

@@ -48,16 +48,6 @@ interface SummaryContentSnapshot {
   trailingText?: ReactNode;
 }
 
-export function shouldRefreshQueuedSummaryContent(
-  current: Pick<SummaryContentSnapshot, "key" | "refreshVersion" | "trailingText">,
-  next: Pick<SummaryContentSnapshot, "key" | "refreshVersion" | "trailingText">,
-) {
-  return (
-    current.key === next.key &&
-    (current.trailingText !== next.trailingText || current.refreshVersion !== next.refreshVersion)
-  );
-}
-
 function usePrefersReducedMotion() {
   const [prefersReducedMotion, setPrefersReducedMotion] = useState(false);
 
@@ -111,23 +101,38 @@ export function QueuedSummaryContent({
     disableAnimation,
     reducedMotion,
   });
-  const createSnapshot = (): SummaryContentSnapshot => ({
-    key: contentKey,
-    refreshVersion: contentRefreshVersion,
-    primaryText,
-    secondaryText,
-    trailingText,
-  });
-  const [displayedContent, setDisplayedContent] = useState(createSnapshot);
-  const displayedContentRef = useRef(displayedContent);
+  if (!shouldAnimate) {
+    // #185:禁用动画时逐 token 在 effect 里复制 state,会在连续同步提交中积累嵌套更新。
+    // 静态路径直接显示输入;卸载播放 owner 同时释放旧队列,重新启用从当前内容开始。
+    return (
+      <>
+        {primaryText}
+        {secondaryText}
+        {trailingText}
+      </>
+    );
+  }
+
+  return (
+    <AnimatedSummaryContent
+      content={{
+        key: contentKey,
+        refreshVersion: contentRefreshVersion,
+        primaryText,
+        secondaryText,
+        trailingText,
+      }}
+    />
+  );
+}
+
+function AnimatedSummaryContent({ content }: { content: SummaryContentSnapshot }) {
+  const [displayedContent, setDisplayedContent] = useState(content);
+  const displayedContentRef = useRef(content);
   const queuedContentRef = useRef<SummaryContentSnapshot[]>([]);
   const animationTimerRef = useRef<number | null>(null);
   const isAnimatingRef = useRef(false);
 
-  useEffect(() => {
-    displayedContentRef.current = displayedContent;
-  }, [displayedContent]);
-
   useEffect(() => {
     const clearAnimationTimer = () => {
       if (animationTimerRef.current !== null) {
@@ -179,24 +184,11 @@ export function QueuedSummaryContent({
         promote(nextQueued);
       }, SUMMARY_ROLL_TOTAL_MS);
     };
-    const nextContent = createSnapshot();
-
-    if (!shouldAnimate) {
-      clearAnimationTimer();
-      isAnimatingRef.current = false;
-      queuedContentRef.current = [];
-      displayedContentRef.current = nextContent;
-      setDisplayedContent(nextContent);
-      return;
-    }
-
+    const nextContent = content;
     if (displayedContentRef.current.key === nextContent.key) {
-      // 同一 Changes child 的 diff 和同一 streaming Assistant message 都不能重播整条摘要;
-      // 前者更新尾部计数,后者用显式 version 原位刷新正文。
-      if (shouldRefreshQueuedSummaryContent(displayedContentRef.current, nextContent)) {
-        displayedContentRef.current = nextContent;
-        setDisplayedContent(nextContent);
-      }
+      // 同一摘要的正文与计数直接由输入派生,不能再 setState;外层组头也会逐 token 更新。
+      // 仅在提交后保存最后显示的快照,下一项排队时仍能冻结当前项的最新内容。
+      displayedContentRef.current = nextContent;
       return;
     }
 
@@ -211,7 +203,7 @@ export function QueuedSummaryContent({
     }
 
     promote(nextContent);
-  }, [contentKey, contentRefreshVersion, shouldAnimate, trailingText]);
+  }, [content]);
 
   useEffect(() => {
     return () => {
@@ -221,34 +213,28 @@ export function QueuedSummaryContent({
     };
   }, []);
 
-  if (!shouldAnimate) {
-    return (
-      <>
-        {primaryText}
-        {secondaryText}
-        {trailingText}
-      </>
-    );
-  }
+  // state 只推进播放项;ref 保存该项的最新已提交输入,不在 render 中写入。
+  const renderedContent =
+    content.key === displayedContent.key ? content : displayedContentRef.current;
 
   return (
     <span className="relative inline-flex min-w-0 items-center gap-2 overflow-hidden align-middle">
       <AnimatePresence initial={false} mode="popLayout">
         <motion.span
-          key={displayedContent.key}
+          key={renderedContent.key}
           className="inline-flex min-w-0 items-center gap-2"
           initial={{ y: "0.8em", opacity: 0 }}
           animate={{ y: 0, opacity: 1 }}
           exit={{ y: "-0.8em", opacity: 0 }}
           transition={SUMMARY_ROLL_TRANSITION}
         >
-          {displayedContent.primaryText}
-          {displayedContent.secondaryText}
+          {renderedContent.primaryText}
+          {renderedContent.secondaryText}
         </motion.span>
       </AnimatePresence>
       {/* 修复原因:Changes 的 diff count 必须与文件摘要属于同一排队快照,
           但数字自身继续用 FlipMetricValue 独立翻动,不能跟整条摘要一起纵向滚走。 */}
-      {displayedContent.trailingText}
+      {renderedContent.trailingText}
     </span>
   );
 }

+ 23 - 27
packages/ui/src/WebRemoteControlMobileShell.tsx

@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useLayoutEffect, useState, type ReactNode } from "react";
 import { ArrowLeft, LoaderCircle } from "lucide-react";
 import { type WebRemoteControlMobileNavigationIntent } from "@zcode/shared";
 import { Button } from "@/components/ui/button.js";
@@ -11,30 +11,33 @@ import { useWebRemoteControlTerminalTransportState } from "@/webRemoteControlTer
 
 type WebRemoteControlMobilePage = "home" | "chat";
 
-interface WebRemoteControlMobileHistoryState {
-  zcodeMobilePage?: WebRemoteControlMobilePage;
-}
-
-export function isWebRemoteControlMobileChatHistoryState(
+function hasMobileHistoryPage(
   state: unknown,
-): state is WebRemoteControlMobileHistoryState {
+  page: WebRemoteControlMobilePage,
+): state is { zcodeMobilePage: WebRemoteControlMobilePage } {
   return (
     typeof state === "object" &&
     state !== null &&
-    (state as WebRemoteControlMobileHistoryState).zcodeMobilePage === "chat"
+    "zcodeMobilePage" in state &&
+    state.zcodeMobilePage === page
   );
 }
 
-function pushWebRemoteControlMobileChatHistory() {
+function recordMobileChatHistory() {
   if (typeof window === "undefined") {
     return;
   }
 
-  if (isWebRemoteControlMobileChatHistoryState(window.history.state)) {
+  const state: unknown = window.history.state;
+  if (hasMobileHistoryPage(state, "chat")) {
     return;
   }
 
-  window.history.pushState({ zcodeMobilePage: "chat" }, "");
+  if (hasMobileHistoryPage(state, "home")) {
+    window.history.replaceState({ ...state, zcodeMobilePage: "chat" }, "");
+  } else {
+    window.history.pushState({ zcodeMobilePage: "chat" }, "");
+  }
 }
 
 function resolveInitialWebRemoteControlMobilePage(
@@ -46,10 +49,7 @@ function resolveInitialWebRemoteControlMobilePage(
 
   // Bugfix: 手机端在聊天页刷新时,React 内存状态会丢失,但浏览器会保留当前 history.state。
   // 这里复用点击进入聊天页时写入的 history state,避免刷新后只恢复 task 选中态却回到任务首页。
-  if (
-    typeof window !== "undefined" &&
-    isWebRemoteControlMobileChatHistoryState(window.history.state)
-  ) {
+  if (typeof window !== "undefined" && hasMobileHistoryPage(window.history.state, "chat")) {
     return "chat";
   }
 
@@ -106,19 +106,15 @@ export function WebRemoteControlMobileShell({
 
   const navigateToChat = useCallback(() => {
     setCurrentPage("chat");
-    pushWebRemoteControlMobileChatHistory();
   }, []);
 
   const navigateHome = useCallback(() => {
-    if (
-      typeof window !== "undefined" &&
-      isWebRemoteControlMobileChatHistoryState(window.history.state)
-    ) {
-      window.history.back();
-      return;
-    }
-
+    // 聊天可能是历史首项,浏览器无法后退。箭头直接回列表,并同步历史供刷新恢复。
     setCurrentPage("home");
+    const state: unknown = window.history.state;
+    if (hasMobileHistoryPage(state, "chat")) {
+      window.history.replaceState({ ...state, zcodeMobilePage: "home" }, "");
+    }
   }, []);
 
   useEffect(() => {
@@ -126,8 +122,8 @@ export function WebRemoteControlMobileShell({
     if (initialNavigationIntent === "chat") setCurrentPage("chat");
   }, [initialNavigationIntent]);
 
-  useEffect(() => {
-    if (isMobileViewport && currentPage === "chat") pushWebRemoteControlMobileChatHistory();
+  useLayoutEffect(() => {
+    if (isMobileViewport && currentPage === "chat") recordMobileChatHistory();
   }, [isMobileViewport, currentPage]);
 
   useEffect(() => {
@@ -136,7 +132,7 @@ export function WebRemoteControlMobileShell({
     }
 
     const handlePopState = (event: PopStateEvent) => {
-      const nextPage = isWebRemoteControlMobileChatHistoryState(event.state) ? "chat" : "home";
+      const nextPage = hasMobileHistoryPage(event.state, "chat") ? "chat" : "home";
       setCurrentPage(nextPage);
     };
 

+ 2 - 1
packages/ui/src/app-shell/WorkspaceShellLayout.tsx

@@ -2781,7 +2781,8 @@ const WorkspaceShellLayoutContent = memo(function WorkspaceShellLayoutComponent(
           >
             <ResizablePanel
               id="conversation-column"
-              minSize={isWebRemoteControlShell ? "0px" : "35%"}
+              // 对话列给浏览器、预览让位:按能放下输入框的宽度兜底,不按窗口比例卡死(11-11 用户反馈 35% 拖不动)
+              minSize={isWebRemoteControlShell ? "0px" : "360px"}
               defaultSize={isSidePaneVisible ? "52%" : undefined}
               className={
                 isWebRemoteControlShell

+ 2 - 1
packages/ui/src/app-shell/animatedSidePanePanelModel.ts

@@ -79,7 +79,8 @@ export function resolveAnimatedSidePanePanelLayout({ mobileOverlay }: { mobileOv
   return {
     collapsedSize: "0px",
     defaultSize: "0px",
-    maxSize: "65%",
+    // 上限由对话列的最小宽度兜住,这里不再按比例卡(11-11 用户反馈拖不动)
+    maxSize: "100%",
     minSize: "240px",
     useResizablePanel: true,
   };

+ 0 - 21
packages/ui/src/browser-use/UnifiedBrowserView.tsx

@@ -5,7 +5,6 @@ import type {
   EmbeddedBrowserViewportPreference,
 } from "@zcode/shared";
 import { browserPreviewSourceUrl, EmbeddedBrowserWebviewChannels } from "@zcode/shared";
-import { requestSidePaneFullView, useSidePaneFullViewActive } from "@/side-pane-full-view/index.js";
 import { cn } from "@/components/lib/utils.js";
 import { usePlatform } from "@/hooks/usePlatform.js";
 import { useWebElementPicker } from "@/hooks/useWebElementPicker.js";
@@ -1164,26 +1163,6 @@ export function UnifiedBrowserView({
   const isDesignToolsVisible = design.toolsVisible;
   // 调整面板:设计稿页面,或任何页面上正在点选(人类 tab 的「选择元素」统一成这套点选,11-06)
   const isDesignPanelAvailable = isDesignToolsVisible || design.mode !== "off";
-  // 设计面板只在完整视图里出(11-05 反馈:半屏放不下原型 + 面板,不缩小原型):
-  // 半屏里面板要出来(选中了元素)就请求进完整视图;退出完整视图时面板收起。
-  // 不支持完整视图(Web 端等)时请求会被忽略,面板照常盖在画布右侧。
-  const fullViewActive = useSidePaneFullViewActive();
-  const designPanelShown =
-    isDesignPanelAvailable && design.panelOpen && design.selections.length > 0;
-  const wasFullViewActiveRef = useRef(fullViewActive);
-  const { setPanelOpen: setDesignPanelOpen } = design;
-  useEffect(() => {
-    const wasActive = wasFullViewActiveRef.current;
-    wasFullViewActiveRef.current = fullViewActive;
-    // 退出完整视图时 tab 可能不在前台:不管可不可见都收起面板,切回来才不会没选元素就又被拉进完整视图(!3450 需要确认)
-    if (wasActive && !fullViewActive) {
-      setDesignPanelOpen(false);
-      return;
-    }
-    if (!isVisible || !isDesignPanelAvailable) return;
-    if (designPanelShown && !fullViewActive) requestSidePaneFullView();
-  }, [designPanelShown, fullViewActive, isDesignPanelAvailable, isVisible, setDesignPanelOpen]);
-
   // 人类 tab:地址栏「选择元素」在任何页面上都是同一套点选(再点一次或页面里 Esc 退出),取代原来的元素选择器(11-06);
   // 能不能改由页面决定:本机 HTML 在调整面板里直接改,其他页面面板只读、交给 Agent。Agent tab 仍是元素 chip 选择器。
   const handleTogglePicker = useCallback(() => {

+ 5 - 4
packages/ui/src/browser-use/useBrowserDesignMode.ts

@@ -192,8 +192,8 @@ export function useBrowserDesignMode({
   const runtimeActive = pluginEnabled && (toolsVisible || (probeEnabled && mode !== "off"));
 
   // 异步回调(注入完成、截图回来、写回完成)读最新值,不依赖闭包里的旧 state
-  const latest = useRef({ mode, selections, variablePreview, variant, pageKey });
-  latest.current = { mode, selections, variablePreview, variant, pageKey };
+  const latest = useRef({ mode, selections, variablePreview, variant, pageKey, toolsVisible });
+  latest.current = { mode, selections, variablePreview, variant, pageKey, toolsVisible };
   const runRef = useRef<((command: DesignRuntimeCommand) => Promise<unknown>) | null>(null);
   const runLatest = useCallback(
     (command: DesignRuntimeCommand) => runRef.current?.(command) ?? Promise.resolve(null),
@@ -393,8 +393,9 @@ export function useBrowserDesignMode({
     (items: readonly DesignSelectedElement[]) => {
       latest.current.selections = items;
       setSelections(items);
-      // 点中元素就打开属性面板显示它(关过面板也一样,11-05 反馈)
-      if (items.length > 0) setPanelOpen(true);
+      // 设计稿页面点中元素就打开属性面板显示它(关过面板也一样,11-05 反馈);
+      // 普通网页点选是为了把元素加进聊天,不自动弹面板挡住页面,要改再点「调整面板」(11-11 用户反馈)
+      if (items.length > 0 && latest.current.toolsVisible) setPanelOpen(true);
       refreshWritable(items);
       reconcileChips();
     },

+ 11 - 7
packages/ui/src/components/ai-elements/reasoning.tsx

@@ -206,7 +206,8 @@ export const Reasoning = memo(
     return (
       <ReasoningContext.Provider value={contextValue}>
         <Collapsible
-          className={cn("not-prose flex flex-col", className)}
+          // 分组预览把思考块放进 flex 摘要,默认 min-width:auto 会撑开视口,令溢出测量失效。
+          className={cn("not-prose min-w-0 flex flex-col", className)}
           onOpenChange={handleOpenChange}
           open={isOpen}
           {...props}
@@ -282,18 +283,21 @@ export const ReasoningTrigger = memo(
     const streamingSummaryRef = useRef<HTMLSpanElement | null>(null);
     const streamingSummaryTextRef = useRef<HTMLSpanElement | null>(null);
     const [isStreamingSummaryOverflowing, setIsStreamingSummaryOverflowing] = useState(false);
+    const streamingSummaryText = streamingSummary?.text;
 
     useEffect(() => {
       const viewport = streamingSummaryRef.current;
-      if (!viewport || !streamingSummary) {
+      if (!viewport || !streamingSummaryText) {
         return;
       }
 
       const syncSummaryViewport = () => {
-        setIsStreamingSummaryOverflowing((current) => {
-          const next = isReasoningSummaryOverflowing(viewport);
-          return current === next ? current : next;
-        });
+        const next = isReasoningSummaryOverflowing(viewport);
+        // #185:连续同步更新时,函数 updater 即使返回旧值也可能留下待处理更新。
+        // 溢出状态未变就不 dispatch;只有遮罩实际切换时才更新 React state。
+        if (next !== isStreamingSummaryOverflowing) {
+          setIsStreamingSummaryOverflowing(next);
+        }
         // 流式摘要超过可用宽度后,普通 overflow-hidden 会固定显示旧前缀,
         // 最新 token 被裁在右侧。每次内容增长后把单行视口推到末尾,让旧内容向左移。
         scrollReasoningSummaryToEnd(viewport);
@@ -309,7 +313,7 @@ export const ReasoningTrigger = memo(
         resizeObserver.observe(streamingSummaryTextRef.current);
       }
       return () => resizeObserver.disconnect();
-    }, [streamingSummary?.text]);
+    }, [streamingSummaryText, isStreamingSummaryOverflowing]);
 
     // 末尾思考完成后,未闭合的收起组头仍需扫光;保留真实完成文案和耗时。
     const thoughtLabelClassName = cn(

+ 15 - 4
packages/ui/src/i18n/locales/en-US.ts

@@ -3795,6 +3795,9 @@ const enUS: Record<string, string> = {
   "settings.appearance.codeTitle": "Code settings",
   "settings.appearance.codeDescription":
     "Choose code themes, font size, and display options independently from the interface font size.",
+  "settings.fontSmoothing": "Font smoothing",
+  "settings.fontSmoothingDescription":
+    "Use grayscale smoothing. Text may look thinner; results vary by display.",
   "settings.uiFontSize": "UI font size",
   "settings.uiFontSizeDescription":
     "Adjust interface text without changing icons or layout dimensions.",
@@ -9043,10 +9046,18 @@ const enUS: Record<string, string> = {
   "voiceInput.button.recognizing": "Recognizing…",
   "voiceInput.action.openPrivacySettings": "Open System Settings",
   "voiceInput.action.openSoundSettings": "Open Sound Settings",
-  "voiceInput.error.permissionDenied.mac":
-    "ZCode cannot use the microphone. Allow ZCode in System Settings › Privacy & Security › Microphone. On some macOS versions, restart the app after you change it.",
-  "voiceInput.error.permissionDenied.windows":
-    'ZCode cannot use the microphone. In Settings › Privacy & security › Microphone, turn on both "Microphone access" and "Let desktop apps access your microphone".',
+  "voiceInput.permission.title": "Microphone access needed",
+  "voiceInput.permission.description.mac":
+    'Click "Request again", then choose "Allow" in the system dialog. You can also turn on ZCode in System Settings › Privacy & Security › Microphone.',
+  "voiceInput.permission.reauthorize": "Request again",
+  "voiceInput.permission.restartTitle": "Restart ZCode",
+  "voiceInput.permission.restartDescription":
+    'The microphone permission was reset. Restart ZCode, click the microphone, then choose "Allow" in the system dialog.',
+  "voiceInput.permission.relaunch": "Restart ZCode",
+  "voiceInput.permission.granted":
+    "Microphone access is on. Click the microphone to start voice input.",
+  "voiceInput.permission.description.windows":
+    'In Settings › Privacy & security › Microphone, turn on both "Microphone access" and "Let desktop apps access your microphone".',
   "voiceInput.error.permissionDenied.linux":
     "Cannot access the microphone. Check the system microphone permission and the PulseAudio / PipeWire input device.",
   "voiceInput.error.silent":

+ 3 - 0
packages/ui/src/i18n/locales/ja-JP.ts

@@ -3539,6 +3539,9 @@ const jaJP: Record<string, string> = {
   "settings.appearance.codeTitle": "コードの設定",
   "settings.appearance.codeDescription":
     "インターフェースのフォントサイズとは別に、コードのテーマ、フォントサイズ、表示オプションを選択します。",
+  "settings.fontSmoothing": "フォントの平滑化",
+  "settings.fontSmoothingDescription":
+    "グレースケールで文字を滑らかにします。文字が細く見える場合があり、効果はディスプレイによって異なります。",
   "settings.uiFontSize": "UI のフォントサイズ",
   "settings.uiFontSizeDescription":
     "アイコンやレイアウトのサイズを変えずに、インターフェースの文字サイズを調整します。",

+ 3 - 0
packages/ui/src/i18n/locales/ko-KR.ts

@@ -3447,6 +3447,9 @@ const koKR: Record<string, string> = {
   "settings.appearance.codeTitle": "코드 설정",
   "settings.appearance.codeDescription":
     "인터페이스 글꼴 크기와 별도로 코드 테마, 글꼴 크기, 표시 옵션을 선택합니다.",
+  "settings.fontSmoothing": "글꼴 다듬기",
+  "settings.fontSmoothingDescription":
+    "회색조로 글꼴을 다듬습니다. 글자가 더 가늘게 보일 수 있으며 효과는 디스플레이에 따라 다릅니다.",
   "settings.uiFontSize": "UI 글꼴 크기",
   "settings.uiFontSizeDescription":
     "아이콘이나 레이아웃 크기를 바꾸지 않고 인터페이스 텍스트를 조정합니다.",

+ 3 - 0
packages/ui/src/i18n/locales/ru-RU.ts

@@ -3512,6 +3512,9 @@ const ruRU: Record<string, string> = {
   "settings.appearance.codeTitle": "Настройки кода",
   "settings.appearance.codeDescription":
     "Темы кода, размер шрифта и параметры отображения настраиваются отдельно от шрифта интерфейса.",
+  "settings.fontSmoothing": "Сглаживание шрифта",
+  "settings.fontSmoothingDescription":
+    "Сглаживание в оттенках серого. Текст может выглядеть тоньше; результат зависит от дисплея.",
   "settings.uiFontSize": "Размер шрифта интерфейса",
   "settings.uiFontSizeDescription":
     "Меняет размер текста интерфейса без изменения значков и размеров макета.",

+ 13 - 4
packages/ui/src/i18n/locales/zh-CN.ts

@@ -3549,6 +3549,8 @@ const zhCN: Record<string, string> = {
   "settings.appearance.interfaceDescription": "设置应用主题和界面文字大小。",
   "settings.appearance.codeTitle": "代码设置",
   "settings.appearance.codeDescription": "设置代码内容的主题、字号和显示方式,不受界面字号影响。",
+  "settings.fontSmoothing": "字体平滑",
+  "settings.fontSmoothingDescription": "开启后使用灰度平滑,文字可能显得更细。效果因显示器而异。",
   "settings.uiFontSize": "界面字号",
   "settings.uiFontSizeDescription": "调整应用界面的文字大小,图标和布局尺寸不受影响。",
   "settings.agentBehavior.title": "行为与工具",
@@ -8563,10 +8565,17 @@ const zhCN: Record<string, string> = {
   "voiceInput.button.recognizing": "正在识别…",
   "voiceInput.action.openPrivacySettings": "打开系统设置",
   "voiceInput.action.openSoundSettings": "打开声音设置",
-  "voiceInput.error.permissionDenied.mac":
-    "ZCode 没有麦克风权限。请在「系统设置 › 隐私与安全性 › 麦克风」中允许 ZCode,部分系统版本需要重启应用后生效。",
-  "voiceInput.error.permissionDenied.windows":
-    "ZCode 没有麦克风权限。请在「设置 › 隐私和安全性 › 麦克风」中同时打开「麦克风访问权限」和「允许桌面应用访问麦克风」。",
+  "voiceInput.permission.title": "需要麦克风权限",
+  "voiceInput.permission.description.mac":
+    "点击「重新授权」,然后在系统弹框中选择「允许」。也可以在「系统设置 › 隐私与安全性 › 麦克风」中打开 ZCode。",
+  "voiceInput.permission.reauthorize": "重新授权",
+  "voiceInput.permission.restartTitle": "需要重启 ZCode",
+  "voiceInput.permission.restartDescription":
+    "已重置麦克风授权。重启 ZCode 后点击麦克风,在系统弹框中选择「允许」。",
+  "voiceInput.permission.relaunch": "重启 ZCode",
+  "voiceInput.permission.granted": "已开启麦克风权限,点击麦克风开始语音输入。",
+  "voiceInput.permission.description.windows":
+    "请在「设置 › 隐私和安全性 › 麦克风」中同时打开「麦克风访问权限」和「允许桌面应用访问麦克风」。",
   "voiceInput.error.permissionDenied.linux":
     "无法访问麦克风。请检查系统的麦克风权限和 PulseAudio / PipeWire 输入设备。",
   "voiceInput.error.silent": "没有收到麦克风声音。通常是系统麦克风权限未开启或选错了输入设备。",

+ 2 - 1
packages/ui/src/project-sidebar/ProjectComposerMenu.tsx

@@ -362,7 +362,8 @@ export function ProjectComposerMenu({
         data-testid="composer-project-menu"
         align="start"
         side="top"
-        className="flex w-72 max-w-[calc(100vw-2rem)] flex-col p-0"
+        // 菜单向上展开会覆盖标题栏;原生拖拽区会吞掉点击,需将整个菜单排除拖拽命中。
+        className="flex w-72 max-w-[calc(100vw-2rem)] flex-col p-0 [app-region:no-drag]"
       >
         <div
           data-slot="command-input-wrapper"

+ 7 - 0
packages/ui/src/settings-search/settingsSearchIndex.ts

@@ -2,6 +2,7 @@ import type { SettingsSectionId } from "@/lib/settingsNavigation.js";
 
 export interface SettingsSearchAvailability {
   desktop: boolean;
+  macDesktop: boolean;
   windowsHost: boolean;
   tray: boolean;
   notWindows: boolean;
@@ -179,6 +180,12 @@ export const SETTINGS_SEARCH_ITEMS = [
     description: "settings.themeModeDescription",
     visibility: "all",
   },
+  {
+    id: "settings.fontSmoothing",
+    section: "appearance",
+    description: "settings.fontSmoothingDescription",
+    visibility: "macDesktop",
+  },
   {
     id: "settings.uiFontSize",
     section: "appearance",

+ 21 - 0
packages/ui/src/settingsCodePreview.tsx

@@ -85,11 +85,17 @@ export function AppearanceSectionContent({
   setTheme,
   uiFontSizePx,
   setUiFontSizePx,
+  isMacDesktop,
+  fontSmoothingEnabled,
+  setFontSmoothingEnabled,
 }: {
   codePreviewSettings: CodePreviewSettings;
   setCodePreviewSettings: (settings: Partial<CodePreviewSettings>) => void;
   theme: Theme;
   setTheme: (theme: Theme) => void;
+  isMacDesktop: boolean;
+  fontSmoothingEnabled: boolean;
+  setFontSmoothingEnabled: (enabled: boolean) => void;
   uiFontSizePx: number;
   setUiFontSizePx: (fontSizePx: number) => void;
 }) {
@@ -154,6 +160,21 @@ export function AppearanceSectionContent({
                 />
               }
             />
+            {isMacDesktop ? (
+              <SettingsRow
+                searchId="settings.fontSmoothing"
+                label={intl.formatMessage({ id: "settings.fontSmoothing" })}
+                description={intl.formatMessage({ id: "settings.fontSmoothingDescription" })}
+                control={
+                  <Switch
+                    data-testid="font-smoothing-switch"
+                    aria-label={intl.formatMessage({ id: "settings.fontSmoothing" })}
+                    checked={fontSmoothingEnabled}
+                    onCheckedChange={setFontSmoothingEnabled}
+                  />
+                }
+              />
+            ) : null}
           </CardContent>
         </Card>
       </div>

+ 0 - 32
packages/ui/src/side-pane-full-view/enterRequest.ts

@@ -1,32 +0,0 @@
-// 工作区里的内容和完整视图之间的两条线(spec:docs/ui/side-pane-full-view.md)。
-// 浏览器、设计工具等在面板深处,拿不到 App 层的完整视图控制器:
-// - 请求进入:发一个 window 事件,由 App 判断能不能进(支持完整视图、面板开着、还不在完整视图),不能就忽略;
-// - 当前是否在完整视图:App 写入、内容侧订阅(设计面板只在完整视图里出,退出时收起)。
-import { useSyncExternalStore } from "react";
-
-export const SIDE_PANE_FULL_VIEW_ENTER_REQUEST_EVENT = "zcode:side-pane-full-view-enter-request";
-
-export function requestSidePaneFullView(): void {
-  window.dispatchEvent(new Event(SIDE_PANE_FULL_VIEW_ENTER_REQUEST_EVENT));
-}
-
-let fullViewActive = false;
-const listeners = new Set<() => void>();
-
-/** App 在完整视图开关变化时写入 */
-export function setSidePaneFullViewActive(active: boolean): void {
-  if (fullViewActive === active) return;
-  fullViewActive = active;
-  for (const listener of listeners) listener();
-}
-
-export function useSidePaneFullViewActive(): boolean {
-  return useSyncExternalStore(
-    (listener) => {
-      listeners.add(listener);
-      return () => listeners.delete(listener);
-    },
-    () => fullViewActive,
-    () => false,
-  );
-}

+ 0 - 6
packages/ui/src/side-pane-full-view/index.ts

@@ -7,12 +7,6 @@ export {
 } from "@/side-pane-full-view/ConversationTab.js";
 export { SidePaneFullViewToggleButton } from "@/side-pane-full-view/ToggleButton.js";
 export { useSidePaneFullView } from "@/side-pane-full-view/useSidePaneFullView.js";
-export {
-  requestSidePaneFullView,
-  setSidePaneFullViewActive,
-  SIDE_PANE_FULL_VIEW_ENTER_REQUEST_EVENT,
-  useSidePaneFullViewActive,
-} from "@/side-pane-full-view/enterRequest.js";
 export {
   readFloatingAnchorPreference,
   writeFloatingAnchorPreference,

+ 23 - 1
packages/ui/src/store/index.ts

@@ -68,6 +68,13 @@ export interface LoginEntryAttempt {
 }
 
 const CODE_PREVIEW_SETTINGS_KEY = "zcode-code-preview-settings";
+const FONT_SMOOTHING_STORAGE_KEY = "zcode-macos-font-smoothing";
+
+function applyFontSmoothing(enabled: boolean): void {
+  // 仅设置展示标记;CSS 以本机 macOS desktop 为边界,远端设备与 Web 不受影响。
+  document.documentElement.classList.toggle("font-smoothing-enabled", enabled);
+}
+
 const PERFORMANCE_MODE_STORAGE_KEY = "zcode-performance-mode";
 const HIDE_PROJECT_DEVICE_NAMES_STORAGE_KEY = "zcode-hide-project-device-names";
 export const FILE_MANAGER_NAVIGATION_PREFERENCES_STORAGE_KEY =
@@ -141,7 +148,10 @@ export interface ZCodeState {
   fileManagerNavigationOpenByWorkspace: Record<string, boolean>;
   setFileManagerNavigationOpen: (workspaceKey: string, open: boolean) => void;
 
-  /** UI 根 rem 字号(px) */
+  /** 本机 macOS 灰度字体平滑偏好。 */
+  fontSmoothingEnabled: boolean;
+  setFontSmoothingEnabled: (enabled: boolean) => void;
+  /** UI 字号 token 的基准值(px),不改变根 rem。 */
   uiFontSizePx: number;
   setUiFontSizePx: (fontSizePx: number) => void;
 
@@ -245,6 +255,7 @@ const BROADCAST_FIELDS = new Set([
   "theme",
   "locale",
   "uiFontSizePx",
+  "fontSmoothingEnabled",
   "interfaceMode",
   "notificationEnabled",
   "hideProjectDeviceNames",
@@ -254,6 +265,7 @@ type BroadcastField =
   | "theme"
   | "locale"
   | "uiFontSizePx"
+  | "fontSmoothingEnabled"
   | "interfaceMode"
   | "hideProjectDeviceNames"
   // 任务通知开关跨窗口同步:角标是应用级表面,A 窗口关通知而 B 窗口仍上报未读时,
@@ -347,6 +359,13 @@ export function createZCodeStore(
       });
     },
 
+    fontSmoothingEnabled: readSafeLocalStorage(FONT_SMOOTHING_STORAGE_KEY) !== "false",
+    setFontSmoothingEnabled: (enabled) => {
+      writeSafeLocalStorage(FONT_SMOOTHING_STORAGE_KEY, String(enabled));
+      applyFontSmoothing(enabled);
+      set({ fontSmoothingEnabled: enabled });
+    },
+
     uiFontSizePx: loadUiFontSizePx(),
     setUiFontSizePx: (fontSizePx: number) => {
       const normalizedFontSizePx = normalizeUiFontSizePx(fontSizePx);
@@ -548,6 +567,8 @@ export function createZCodeStore(
         (msg.payload === "office" || msg.payload === "coding")
       ) {
         state.setInterfaceMode(normalizeInterfaceMode(msg.payload));
+      } else if (field === "fontSmoothingEnabled" && typeof msg.payload === "boolean") {
+        state.setFontSmoothingEnabled(msg.payload);
       } else if (field === "uiFontSizePx" && typeof msg.payload === "number") {
         state.setUiFontSizePx(msg.payload);
       } else if (field === "notificationEnabled" && typeof msg.payload === "boolean") {
@@ -563,6 +584,7 @@ export function createZCodeStore(
   syncSystemThemeListener(useStore.getState().theme);
   applyTheme(useStore.getState().theme);
   applyUiFontSizePx(useStore.getState().uiFontSizePx);
+  applyFontSmoothing(useStore.getState().fontSmoothingEnabled);
   document.documentElement.classList.toggle(
     "dark",
     resolveTheme(useStore.getState().theme) === "dark",

+ 4 - 0
packages/ui/src/styles.css

@@ -98,6 +98,10 @@ body,
 body {
   margin: 0;
   overflow: hidden;
+}
+
+/* 本机 macOS 专属偏好:关闭时不覆盖系统默认,Web/远控不继承桌面渲染策略。 */
+:root.platform-mac-desktop.font-smoothing-enabled {
   -webkit-font-smoothing: antialiased;
 }
 

+ 2 - 0
packages/ui/src/v4/ConversationComposer.tsx

@@ -2706,6 +2706,7 @@ function ConversationComposerImpl({
             state={voiceInput.state}
             onToggle={voiceInput.toggle}
             subscribeLevel={voiceInput.subscribeLevel}
+            permissionGuide={voiceInput.permissionGuide}
           />
         ) : null}
         {showStopControl ? (
@@ -2754,6 +2755,7 @@ function ConversationComposerImpl({
       voiceInput.state,
       voiceInput.toggle,
       voiceInput.subscribeLevel,
+      voiceInput.permissionGuide,
       composerUsage,
       disabled,
       modelSelectionPending,

+ 1 - 0
packages/ui/src/voice-input/CONTRACT.md

@@ -4,6 +4,7 @@ Composer 语音输入的 UI 模块(`docs/chat/composer-voice-input.md`)。
 
 - `useComposerVoiceInput({ inputApiRef, sessionId, enabled })`:状态机唯一 owner,返回 `available`、`state`、`toggle`、`settle(reason)`。
 - `VoiceInputButton`:纯展示组件;按下时不抢输入框焦点。
+- `ui/useMicrophonePermissionGuide.ts`:macOS / Windows 权限被拒时的引导浮层状态(重新授权、打开系统设置、重启 ZCode、窗口获焦时重查一次权限);浮层由 `VoiceInputButton` 渲染。
 - `adapters/pcmCapture.ts`:getUserMedia + AudioWorklet,输出 16kHz 单声道 PCM16,每 100ms 一块。
 - `domain/voiceInputFailure.ts`:失败分类、静音判定和提示文案选择,纯函数。
 

+ 22 - 0
packages/ui/src/voice-input/contract.ts

@@ -6,6 +6,26 @@ export type VoiceInputState = "idle" | "requesting" | "recording" | "finishing";
 /** Composer 触发的结束原因:发送消息、用户修改输入框。两者都与点击停止一致,等待最终结果。 */
 export type VoiceInputStopReason = "submit" | "user-input";
 
+/** 权限引导浮层阶段:denied 提供重新授权 / 打开设置;restart-required 提示重启 ZCode */
+export type MicrophonePermissionGuidePhase = "denied" | "restart-required";
+
+/** 麦克风权限引导浮层(docs/chat/composer-voice-input.md「权限引导浮层」) */
+export interface MicrophonePermissionGuide {
+  /** null 表示浮层关闭 */
+  phase: MicrophonePermissionGuidePhase | null;
+  /** 决定文案和是否提供「重新授权」(仅 mac) */
+  os: "mac" | "windows";
+  /** Linux 不使用浮层 */
+  available: boolean;
+  /** 重新授权进行中 */
+  busy: boolean;
+  show: () => void;
+  close: () => void;
+  openSettings: () => void;
+  reauthorize: () => void;
+  relaunch: () => void;
+}
+
 export interface ComposerVoiceInput {
   /** 当前环境可用(桌面、已登录、Host 提供服务) */
   available: boolean;
@@ -17,6 +37,8 @@ export interface ComposerVoiceInput {
    * 等待可能跨越会话切换:恢复后调用方必须自行校验目标是否仍有效。
    */
   settle: (reason: VoiceInputStopReason) => Promise<void> | undefined;
+  /** 系统权限被拒时的引导浮层,由 VoiceInputButton 渲染 */
+  permissionGuide: MicrophonePermissionGuide;
   /** 订阅录音中每个 100ms 音频块的峰值电平(满量程 1);返回取消订阅函数。引用稳定 */
   subscribeLevel: (listener: (peak: number) => void) => () => void;
 }

+ 4 - 2
packages/ui/src/voice-input/domain/voiceInputFailure.ts

@@ -20,6 +20,8 @@ export interface VoiceInputFailureNotice {
   messageId?: string;
   /** 带「打开系统设置」按钮时打开的页面 */
   settingsTarget?: "privacy" | "sound";
+  /** macOS / Windows 权限被拒:不用 toast,显示权限引导浮层 */
+  permissionGuide?: true;
 }
 
 export function resolveVoiceInputOs(userAgent: string): VoiceInputOs {
@@ -70,10 +72,10 @@ export function resolveVoiceInputFailureNotice(
     os === "linux" ? { messageId: `${messageId}.linux` } : { messageId, settingsTarget };
   switch (failure) {
     case "permission_denied":
-      // mac / Windows 的开启步骤不同,文案按系统区分。
+      // mac / Windows 用引导浮层(docs/chat/composer-voice-input.md「权限引导浮层」);Linux 没有设置页,只提示文字。
       return os === "linux"
         ? { messageId: "voiceInput.error.permissionDenied.linux" }
-        : { messageId: `voiceInput.error.permissionDenied.${os}`, settingsTarget: "privacy" };
+        : { permissionGuide: true };
     case "silent":
       return withSettings("voiceInput.error.silent", "privacy");
     case "no_device":

+ 150 - 48
packages/ui/src/voice-input/ui/VoiceInputControls.tsx

@@ -2,13 +2,29 @@ import { memo, useEffect, useState } from "react";
 import { MicIcon } from "lucide-react";
 import {
   TID_V4_COMPOSER_VOICE_INPUT,
+  TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE,
+  TID_V4_COMPOSER_VOICE_PERMISSION_OPEN_SETTINGS,
+  TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE,
+  TID_V4_COMPOSER_VOICE_PERMISSION_RELAUNCH,
   TID_V4_COMPOSER_VOICE_WAVEFORM,
 } from "@zcode/shared/test-ids";
 import { Button } from "@/components/ui/button.js";
+import {
+  Popover,
+  PopoverAnchor,
+  PopoverContent,
+  PopoverDescription,
+  PopoverHeader,
+  PopoverTitle,
+} from "@/components/ui/popover.js";
 import { Spinner } from "@/components/ui/spinner.js";
 import { ControlHintTooltip } from "@/ControlHintTooltip.js";
 import { useZCodeIntl } from "@/i18n/IntlProvider.js";
-import type { ComposerVoiceInput, VoiceInputState } from "@/voice-input/contract.js";
+import type {
+  ComposerVoiceInput,
+  MicrophonePermissionGuide,
+  VoiceInputState,
+} from "@/voice-input/contract.js";
 
 const TITLE_IDS: Record<VoiceInputState, string> = {
   idle: "voiceInput.button.start",
@@ -66,6 +82,80 @@ const VoiceInputWaveform = memo(function VoiceInputWaveform(props: {
   );
 });
 
+/**
+ * 麦克风权限引导浮层内容(docs/chat/composer-voice-input.md「权限引导浮层」)。
+ * mac:打开系统设置 + 重新授权;重置后仍需重启时只提供重启 ZCode。Windows:只有打开系统设置。
+ */
+function MicrophonePermissionGuideContent(props: { guide: MicrophonePermissionGuide }) {
+  const { guide } = props;
+  const { intl } = useZCodeIntl();
+  const restart = guide.phase === "restart-required";
+  const mac = guide.os === "mac";
+  return (
+    <PopoverContent
+      side="top"
+      align="end"
+      className="w-80 gap-3"
+      data-testid={TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE}
+      data-voice-permission-phase={guide.phase ?? undefined}
+      // 打开和关闭都不移动焦点:焦点和光标留在输入框,与麦克风按钮不抢焦点一致。
+      onOpenAutoFocus={(event) => event.preventDefault()}
+      onCloseAutoFocus={(event) => event.preventDefault()}
+    >
+      <PopoverHeader>
+        <PopoverTitle>
+          {intl.formatMessage({
+            id: restart ? "voiceInput.permission.restartTitle" : "voiceInput.permission.title",
+          })}
+        </PopoverTitle>
+        <PopoverDescription className="text-ui-sm">
+          {intl.formatMessage({
+            id: restart
+              ? "voiceInput.permission.restartDescription"
+              : `voiceInput.permission.description.${guide.os}`,
+          })}
+        </PopoverDescription>
+      </PopoverHeader>
+      <div className="flex flex-wrap justify-end gap-2">
+        {restart ? (
+          <Button
+            type="button"
+            size="sm"
+            data-testid={TID_V4_COMPOSER_VOICE_PERMISSION_RELAUNCH}
+            onClick={guide.relaunch}
+          >
+            {intl.formatMessage({ id: "voiceInput.permission.relaunch" })}
+          </Button>
+        ) : (
+          <>
+            <Button
+              type="button"
+              size="sm"
+              variant={mac ? "outline" : "default"}
+              data-testid={TID_V4_COMPOSER_VOICE_PERMISSION_OPEN_SETTINGS}
+              onClick={guide.openSettings}
+            >
+              {intl.formatMessage({ id: "voiceInput.action.openPrivacySettings" })}
+            </Button>
+            {mac ? (
+              <Button
+                type="button"
+                size="sm"
+                disabled={guide.busy}
+                data-testid={TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE}
+                onClick={guide.reauthorize}
+              >
+                {guide.busy ? <Spinner className="size-3.5" /> : null}
+                {intl.formatMessage({ id: "voiceInput.permission.reauthorize" })}
+              </Button>
+            ) : null}
+          </>
+        )}
+      </div>
+    </PopoverContent>
+  );
+}
+
 /**
  * Composer 右侧工具栏的语音输入入口,位于发送 / 停止按钮左侧。
  * 空闲时是麦克风按钮;录音中扩展为浅蓝胶囊:左侧蓝色波形,右侧蓝色停止方块(sky 色系 token)。
@@ -77,59 +167,71 @@ export const VoiceInputButton = memo(function VoiceInputButton(props: {
   state: VoiceInputState;
   onToggle: () => void;
   subscribeLevel: ComposerVoiceInput["subscribeLevel"];
+  permissionGuide: MicrophonePermissionGuide;
 }) {
   const { intl } = useZCodeIntl();
   const title = intl.formatMessage({ id: TITLE_IDS[props.state] });
   const active = props.state !== "idle";
+  const guide = props.permissionGuide;
   return (
-    <span
-      className={
-        "flex shrink-0 items-center rounded-full transition-colors duration-200 ease-out motion-reduce:transition-none " +
-        (active ? "bg-voice-input-surface" : "")
-      }
+    <Popover
+      open={guide.available && guide.phase !== null}
+      onOpenChange={(open) => {
+        if (!open) guide.close();
+      }}
     >
-      <span
-        data-voice-pill-expanded={active}
-        className={
-          "grid transition-[grid-template-columns,opacity] duration-200 ease-out motion-reduce:transition-none " +
-          (active ? "grid-cols-[1fr] opacity-100" : "grid-cols-[0fr] opacity-0")
-        }
-      >
-        <span className="min-w-0 overflow-hidden">
-          {active ? (
-            <VoiceInputWaveform
-              active={props.state === "recording"}
-              subscribeLevel={props.subscribeLevel}
-            />
-          ) : null}
-        </span>
-      </span>
-      <ControlHintTooltip title={title}>
-        <Button
-          type="button"
-          variant="ghost"
-          size="icon-md"
-          data-testid={TID_V4_COMPOSER_VOICE_INPUT}
-          data-voice-state={props.state}
-          aria-label={title}
-          aria-pressed={active}
-          // 识别中等待服务端结果,不响应点击;用 aria-disabled 保留 hover 提示。
-          aria-disabled={props.state === "finishing" || undefined}
-          // 按下按钮不抢走输入框焦点:语音文字写在原光标处,用户也能直接继续打字来停止语音输入。
-          onMouseDown={(event) => event.preventDefault()}
-          onClick={props.state === "finishing" ? undefined : props.onToggle}
-          className="shrink-0 rounded-full"
+      <PopoverAnchor asChild>
+        <span
+          className={
+            "flex shrink-0 items-center rounded-full transition-colors duration-200 ease-out motion-reduce:transition-none " +
+            (active ? "bg-voice-input-surface" : "")
+          }
         >
-          {props.state === "idle" ? (
-            <MicIcon className="size-4" />
-          ) : props.state === "recording" ? (
-            <span className="size-2.5 rounded-[3px] bg-voice-input-wave" />
-          ) : (
-            <Spinner className="size-4" />
-          )}
-          <span className="sr-only">{title}</span>
-        </Button>
-      </ControlHintTooltip>
-    </span>
+          <span
+            data-voice-pill-expanded={active}
+            className={
+              "grid transition-[grid-template-columns,opacity] duration-200 ease-out motion-reduce:transition-none " +
+              (active ? "grid-cols-[1fr] opacity-100" : "grid-cols-[0fr] opacity-0")
+            }
+          >
+            <span className="min-w-0 overflow-hidden">
+              {active ? (
+                <VoiceInputWaveform
+                  active={props.state === "recording"}
+                  subscribeLevel={props.subscribeLevel}
+                />
+              ) : null}
+            </span>
+          </span>
+          <ControlHintTooltip title={title}>
+            <Button
+              type="button"
+              variant="ghost"
+              size="icon-md"
+              data-testid={TID_V4_COMPOSER_VOICE_INPUT}
+              data-voice-state={props.state}
+              aria-label={title}
+              aria-pressed={active}
+              // 识别中等待服务端结果,不响应点击;用 aria-disabled 保留 hover 提示。
+              aria-disabled={props.state === "finishing" || undefined}
+              // 按下按钮不抢走输入框焦点:语音文字写在原光标处,用户也能直接继续打字来停止语音输入。
+              onMouseDown={(event) => event.preventDefault()}
+              onClick={props.state === "finishing" ? undefined : props.onToggle}
+              className="shrink-0 rounded-full"
+            >
+              {props.state === "idle" ? (
+                <MicIcon className="size-4" />
+              ) : props.state === "recording" ? (
+                <span className="size-2.5 rounded-[3px] bg-voice-input-wave" />
+              ) : (
+                <Spinner className="size-4" />
+              )}
+              <span className="sr-only">{title}</span>
+            </Button>
+          </ControlHintTooltip>
+        </span>
+      </PopoverAnchor>
+      <MicrophonePermissionGuideContent guide={guide} />
+    </Popover>
   );
 });

+ 9 - 2
packages/ui/src/voice-input/ui/useComposerVoiceInput.ts

@@ -31,6 +31,7 @@ import type {
   VoiceInputStopReason,
 } from "@/voice-input/contract.js";
 import { startPcmCapture, type PcmCapture } from "@/voice-input/adapters/pcmCapture.js";
+import { useMicrophonePermissionGuide } from "@/voice-input/ui/useMicrophonePermissionGuide.js";
 import {
   classifyCapturedAudio,
   classifyGetUserMediaError,
@@ -64,6 +65,8 @@ export function useComposerVoiceInput(options: {
   const isLoggedIn = useZCodeStore((state) => state.user !== null);
   const { intl, locale } = useZCodeIntl();
   const available = Boolean(options.enabled && microphone && voiceInputService && isLoggedIn);
+  const permissionGuide = useMicrophonePermissionGuide();
+  const showPermissionGuide = permissionGuide.show;
 
   const [state, setState] = useState<VoiceInputState>("idle");
   const attemptRef = useRef<Attempt | null>(null);
@@ -94,6 +97,10 @@ export function useComposerVoiceInput(options: {
         failure,
         resolveVoiceInputOs(typeof navigator === "undefined" ? "" : navigator.userAgent),
       );
+      if (notice.permissionGuide) {
+        showPermissionGuide();
+        return;
+      }
       if (!notice.messageId) return;
       const target = notice.settingsTarget;
       toast(intl.formatMessage({ id: notice.messageId }), {
@@ -113,7 +120,7 @@ export function useComposerVoiceInput(options: {
           : {}),
       });
     },
-    [intl, microphone],
+    [intl, microphone, showPermissionGuide],
   );
 
   const fail = useCallback(
@@ -316,5 +323,5 @@ export function useComposerVoiceInput(options: {
     return () => window.removeEventListener("keydown", handleKeyDown, true);
   }, [stopAttempt, state]);
 
-  return { available, state, toggle, settle, subscribeLevel };
+  return { available, state, toggle, settle, subscribeLevel, permissionGuide };
 }

+ 119 - 0
packages/ui/src/voice-input/ui/useMicrophonePermissionGuide.ts

@@ -0,0 +1,119 @@
+/**
+ * 麦克风权限引导浮层的状态(docs/chat/composer-voice-input.md「权限引导浮层」)。
+ *
+ * ```text
+ * closed ─show()─▶ denied ─重新授权─┬─ granted ──────────▶ closed(toast 已开启)
+ *                    ▲              ├─ denied ───────────▶ denied
+ *                    │              ├─ restart-required ─▶ restart-required ─重启 ZCode─▶ 应用重启
+ *                    │              └─ failed ───────────▶ denied(打开系统设置)
+ *                    └─ 窗口 focus:ensureAccess 为 granted ─▶ closed(toast 已开启)
+ * ```
+ *
+ * - 浮层只在 macOS / Windows 打开;Linux 没有系统设置页,仍用 toast。
+ * - 窗口重新获得焦点时检查一次权限,事件触发,不轮询。
+ * - 重新授权进行中(系统弹框打开时窗口会失焦再获焦)跳过焦点检查,
+ *   避免同时调用 askForMediaAccess;结果以重新授权的返回值为准。
+ */
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { DesktopCommandIds } from "@zcode/shared";
+import { toast } from "@/components/ui/toast.js";
+import { useOptionalPlatform } from "@/hooks/usePlatform.js";
+import { useZCodeIntl } from "@/i18n/IntlProvider.js";
+import { logger } from "@/logger.js";
+import type {
+  MicrophonePermissionGuide,
+  MicrophonePermissionGuidePhase,
+} from "@/voice-input/contract.js";
+import { resolveVoiceInputOs } from "@/voice-input/domain/voiceInputFailure.js";
+
+export function useMicrophonePermissionGuide(): MicrophonePermissionGuide {
+  const platform = useOptionalPlatform();
+  const microphone = platform?.microphone;
+  const { intl } = useZCodeIntl();
+  const os = resolveVoiceInputOs(typeof navigator === "undefined" ? "" : navigator.userAgent);
+  const [phase, setPhase] = useState<MicrophonePermissionGuidePhase | null>(null);
+  const [busy, setBusy] = useState(false);
+  const busyRef = useRef(false);
+
+  const close = useCallback(() => setPhase(null), []);
+
+  const closeGranted = useCallback(() => {
+    setPhase(null);
+    toast(intl.formatMessage({ id: "voiceInput.permission.granted" }), {
+      variant: "success",
+      dedupeKey: "voice-input-permission-granted",
+    });
+  }, [intl]);
+
+  const show = useCallback(() => setPhase("denied"), []);
+
+  const openSettings = useCallback(() => {
+    void microphone?.openSettings("privacy");
+  }, [microphone]);
+
+  const reauthorize = useCallback(async () => {
+    if (!microphone || busyRef.current) return;
+    busyRef.current = true;
+    setBusy(true);
+    const result = await microphone.resetAccess().catch(() => "failed" as const);
+    busyRef.current = false;
+    setBusy(false);
+    logger.lifecycle.info("[voice-input] reauthorize", { result });
+    switch (result) {
+      case "granted":
+        closeGranted();
+        return;
+      case "restart-required":
+        setPhase((current) => (current ? "restart-required" : current));
+        return;
+      case "failed":
+        void microphone.openSettings("privacy");
+        return;
+      case "denied":
+        return;
+    }
+  }, [closeGranted, microphone]);
+
+  const relaunch = useCallback(() => {
+    if (typeof platform?.executeDesktopCommand !== "function") return;
+    logger.lifecycle.info("[voice-input] relaunch for microphone permission");
+    platform.executeDesktopCommand(DesktopCommandIds.RelaunchApp).catch((error: unknown) => {
+      logger.lifecycle.warn("[voice-input] relaunch failed", {
+        message: error instanceof Error ? error.message : String(error),
+      });
+    });
+  }, [platform]);
+
+  // 用户在系统设置里打开开关后回到 ZCode:检查一次,已允许就关闭浮层。
+  const open = phase !== null;
+  useEffect(() => {
+    if (!open || !microphone) return;
+    const onFocus = () => {
+      if (busyRef.current) return;
+      void microphone
+        .ensureAccess()
+        .catch(() => "unsupported" as const)
+        .then((access) => {
+          if (access === "granted" && !busyRef.current) closeGranted();
+        });
+    };
+    window.addEventListener("focus", onFocus);
+    return () => window.removeEventListener("focus", onFocus);
+  }, [closeGranted, microphone, open]);
+
+  // 引用随状态变化,VoiceInputButton(memo)不随 Composer 的其他渲染重绘。
+  return useMemo(
+    () => ({
+      phase,
+      os: os === "windows" ? ("windows" as const) : ("mac" as const),
+      available: os !== "linux",
+      busy,
+      show,
+      close,
+      openSettings,
+      reauthorize,
+      relaunch,
+    }),
+    [busy, close, openSettings, os, phase, reauthorize, relaunch, show],
+  );
+}

+ 153 - 0
packages/ui/test/browser/manual-review/pending/font-smoothing.test.mjs

@@ -0,0 +1,153 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+import { mkdir } from "node:fs/promises";
+import { join } from "node:path";
+import { createServer } from "vite";
+import react from "@vitejs/plugin-react";
+import tailwindcss from "@tailwindcss/vite";
+import { chromium } from "playwright-core";
+
+const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
+const entry = join(root, "font-smoothing-preview.tsx");
+const artifacts = join(root, "packages/desktop/.e2e-artifacts/font-smoothing");
+const fixture = `
+import { createRoot } from "react-dom/client";
+import { useStore } from "zustand";
+import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
+import { AppearanceSectionContent } from "@/settingsCodePreview.js";
+import { createZCodeStore } from "@/store/index.js";
+import "@/styles.css";
+const query = new URLSearchParams(location.search);
+const platform = query.get("platform");
+document.documentElement.classList.toggle("platform-mac-desktop", platform === "mac");
+const channel = new BroadcastChannel("font-smoothing-test");
+window.sent = 0;
+const store = createZCodeStore({send(message) { window.sent++; channel.postMessage(message); }, onMessage(callback) {channel.onmessage = event => callback(event.data); return () => {channel.onmessage = null;};}});
+store.getState().setTheme("zai-" + query.get("theme"));
+window.store = store;
+function Fixture() {
+ const state = useStore(store);
+ return <ZCodeIntlProvider initialLocale={query.get("locale")}>
+ <main className="bg-background text-foreground p-4" style={{height:"100vh",overflow:"auto"}}>
+ <AppearanceSectionContent isMacDesktop={platform === "mac"}
+ fontSmoothingEnabled={state.fontSmoothingEnabled} setFontSmoothingEnabled={state.setFontSmoothingEnabled}
+ theme={state.theme} setTheme={state.setTheme} uiFontSizePx={state.uiFontSizePx} setUiFontSizePx={state.setUiFontSizePx}
+ codePreviewSettings={state.codePreviewSettings} setCodePreviewSettings={state.setCodePreviewSettings} />
+ </main></ZCodeIntlProvider>;
+}
+createRoot(document.getElementById("root")).render(<Fixture />);
+`;
+
+test("macOS 字体平滑:切换、重载、多窗口与平台隔离", async () => {
+  await mkdir(artifacts, { recursive: true });
+  const server = await createServer({
+    root,
+    configFile: false,
+    plugins: [
+      {
+        name: "font-smoothing-preview",
+        resolveId(id) {
+          if (id === "/font-smoothing-preview.tsx") return entry;
+        },
+        load(id) {
+          if (id === entry) return fixture;
+        },
+        configureServer(vite) {
+          vite.middlewares.use(async (req, res, next) => {
+            if (!req.url?.startsWith("/fixture?")) return next();
+            res.setHeader("Content-Type", "text/html");
+            res.end(
+              await vite.transformIndexHtml(
+                req.url,
+                '<html><head><meta name="viewport" content="width=device-width, initial-scale=1" /></head><body><div id="root"></div><script type="module" src="/font-smoothing-preview.tsx"></script></body></html>',
+              ),
+            );
+          });
+        },
+      },
+      react(),
+      tailwindcss(),
+    ],
+    resolve: { dedupe: ["react", "react-dom"], alias: { "@": join(root, "packages/ui/src") } },
+    optimizeDeps: {
+      entries: [],
+      include: [
+        "react",
+        "react-dom/client",
+        "react/jsx-runtime",
+        "class-variance-authority",
+        "clsx",
+        "radix-ui",
+        "tailwind-merge",
+        "zod",
+        "zustand",
+        "lucide-react",
+        "@pierre/diffs/react",
+        "@streamdown/mermaid",
+      ],
+    },
+    server: { host: "127.0.0.1", port: 0, hmr: false },
+  });
+  let browser;
+  try {
+    await server.listen();
+    browser = await chromium.launch({ channel: "chrome", headless: true });
+    const context = await browser.newContext();
+    const url = (platform, theme = "light", locale = "zh-CN") =>
+      `${server.resolvedUrls.local[0]}fixture?platform=${platform}&theme=${theme}&locale=${locale}`;
+    const page = await context.newPage();
+    page.on("pageerror", (error) => process.stderr.write(String(error) + "\n"));
+    await page.goto(url("mac"));
+    const toggle = page.getByTestId("font-smoothing-switch");
+    await toggle.waitFor();
+    assert.equal(await toggle.getAttribute("aria-checked"), "true");
+    const read = (p) =>
+      p.evaluate(() => getComputedStyle(document.body).getPropertyValue("-webkit-font-smoothing"));
+    assert.equal(await read(page), "antialiased");
+    await toggle.click();
+    assert.equal(await read(page), "auto");
+    const other = await context.newPage();
+    await other.goto(url("mac"));
+    await other.getByTestId("font-smoothing-switch").waitFor();
+    const sentBefore = await other.evaluate(() => window.sent);
+    await toggle.click();
+    await other.waitForFunction(() => window.store.getState().fontSmoothingEnabled === true);
+    assert.equal(await read(other), "antialiased");
+    assert.equal(await other.evaluate(() => window.sent), sentBefore);
+    await page.reload();
+    await toggle.waitFor();
+    assert.equal(await toggle.getAttribute("aria-checked"), "true");
+    assert.equal(await read(page), "antialiased");
+    for (const width of [1200, 390])
+      for (const theme of ["light", "dark"])
+        for (const locale of ["zh-CN", "en-US"]) {
+          await page.setViewportSize({ width, height: 900 });
+          await page.goto(url("mac", theme, locale));
+          await toggle.waitFor();
+          assert.equal(await read(page), "antialiased");
+          const row = page.locator('[data-settings-search-id="settings.fontSmoothing"]');
+          await row.scrollIntoViewIfNeeded();
+          assert.ok(await row.evaluate((e) => e.scrollWidth <= e.clientWidth));
+          await page.screenshot({ path: join(artifacts, `${width}-${theme}-${locale}.png`) });
+        }
+    for (const platform of ["windows", "linux", "web"]) {
+      await page.goto(url(platform));
+      await page.locator('[data-settings-search-id="settings.uiFontSize"]').waitFor();
+      assert.equal(await toggle.count(), 0);
+      assert.equal(await read(page), "auto");
+    }
+    await page.goto(url("mac"));
+    await toggle.waitFor();
+    await toggle.click();
+    await other.waitForFunction(() => window.store.getState().fontSmoothingEnabled === false);
+    assert.equal(await read(other), "auto");
+    await page.reload();
+    await toggle.waitFor();
+    assert.equal(await toggle.getAttribute("aria-checked"), "false");
+    await context.close();
+  } finally {
+    await browser?.close();
+    await server.close();
+  }
+});

Някои файлове не бяха показани, защото твърде много файлове са промени