@allbluecn/web-app 0.27.28 → 0.27.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allbluecn/web-app",
3
- "version": "0.27.28",
3
+ "version": "0.27.29",
4
4
  "license": "AGPL-3.0-or-later",
5
5
  "type": "module",
6
6
  "files": [
@@ -0,0 +1,303 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+ /**
19
+ * 本地线程 localCwd 写空护栏回归(真机验收 P1)。
20
+ *
21
+ * 根因:persistThreadEngine 把客户端 engine/localCwd/localAgentId 盲写回 DB——
22
+ * 页面先于线程创建打开(loader conversation=null → 客户端 cwd=null、engine 走
23
+ * localStorage)或 local→cloud 往返把客户端 cwd 重置为 null 后,任何引擎/agent
24
+ * 触发的持久化都会把 (engine=local, localCwd=null) 落库(服务端消息计数守卫对
25
+ * 未落库首轮流 / harness transcript 线程恒为 0,拦不住)。
26
+ *
27
+ * 修复口径(客户端):persistThreadEngine 写回前以线程真源(侧栏列表项 /
28
+ * loader initialConversation)回填 cwd/agent——客户端态缺失时恢复真源值而非写
29
+ * null;两者皆缺跳过落库,等 handleLocalCwdChange 补齐。handoff 建会话后引擎态
30
+ * 同步以线程值为准(applyConv)。
31
+ *
32
+ * mock 面与 harness-workbench-first-send.test.tsx 同构;composer 桩暴露引擎/
33
+ * 目录/agent 回调按钮并镜像 props 供断言。
34
+ */
35
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
36
+ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"
37
+ import type { ReactNode } from "react"
38
+ import HarnessWorkbenchPage from "../harness-workbench-page"
39
+ import { stashPendingWorkspaceMessage } from "@/lib/ai/chat-handoff"
40
+ import type { HarnessInitialConversation } from "../workbench/workbench-context"
41
+
42
+ const h = vi.hoisted(() => {
43
+ return {
44
+ messages: [] as Array<{ id: string; role: string; parts: unknown[] }>,
45
+ // updateConversationFn 收到的 data 载荷(按序)
46
+ updates: [] as Array<Record<string, unknown>>,
47
+ // composer 最近一次渲染的 props 镜像(engine/localCwd/localAgentId 断言用)
48
+ composerProps: null as null | Record<string, unknown>,
49
+ }
50
+ })
51
+
52
+ vi.mock("@/components/harness/chat-ui", () => ({
53
+ useHarnessChat: () => ({
54
+ messages: h.messages,
55
+ isLoading: false,
56
+ status: "idle",
57
+ connectionStatus: "connected",
58
+ error: undefined,
59
+ runId: undefined,
60
+ interrupts: [],
61
+ sendMessage: () => Promise.resolve(),
62
+ reload: () => Promise.resolve(),
63
+ stop: () => {},
64
+ clear: () => {},
65
+ AppChat: () => null,
66
+ }),
67
+ useHarnessChatContext: () => ({}),
68
+ }))
69
+
70
+ vi.mock("@tanstack/react-router", () => ({
71
+ useNavigate: () => vi.fn(),
72
+ Link: (props: { to: string; children?: ReactNode }) => (
73
+ <a href={props.to}>{props.children}</a>
74
+ ),
75
+ }))
76
+
77
+ vi.mock("@tanstack/react-query", async (importOriginal) => ({
78
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
79
+ useQuery: () => ({ data: undefined }),
80
+ }))
81
+
82
+ vi.mock("@/lib/auth/auth-client", () => ({
83
+ useSession: () => ({ data: { user: { hasAiKey: true } } }),
84
+ }))
85
+
86
+ vi.mock("@/server/serverFns/chat/conversations", () => ({
87
+ listConversationsFn: vi.fn(() => Promise.resolve([])),
88
+ createConversationFn: vi.fn(async () => ({
89
+ id: "conv-handoff-1",
90
+ title: null,
91
+ engine: "cloud",
92
+ localCwd: null,
93
+ localAgentId: null,
94
+ })),
95
+ updateConversationFn: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
96
+ h.updates.push(data)
97
+ return { success: true }
98
+ }),
99
+ deleteConversationFn: vi.fn(() => Promise.resolve({})),
100
+ forkConversationFn: vi.fn(() => Promise.resolve({})),
101
+ }))
102
+
103
+ vi.mock("@/server/serverFns/agents/agent-crud", () => ({
104
+ listAgentsFn: vi.fn(() => Promise.resolve([])),
105
+ }))
106
+
107
+ vi.mock("@/server/serverFns/design/ai/providers", () => ({
108
+ listAiProvidersFn: vi.fn(() => Promise.resolve([])),
109
+ }))
110
+
111
+ vi.mock("@/server/serverFns/harness/cancel-run", () => ({
112
+ cancelRunFn: vi.fn(() => Promise.resolve({})),
113
+ }))
114
+
115
+ vi.mock("@/lib/ai/use-selected-model", () => ({
116
+ useSelectedModel: () => ["", vi.fn()] as const,
117
+ }))
118
+
119
+ vi.mock("@/lib/ai/use-search-capability", () => ({
120
+ useSearchCapability: () => ({
121
+ enabled: false,
122
+ adapterKind: "openrouter",
123
+ hasNative: true,
124
+ searxngEnabled: false,
125
+ }),
126
+ }))
127
+
128
+ vi.mock("@/lib/ai/use-code-mode-readiness", () => ({
129
+ useCodeModeReadiness: () => ({ enabled: false }),
130
+ }))
131
+
132
+ vi.mock("@/components/harness/composer/harness-composer", () => ({
133
+ HarnessComposer: (props: Record<string, unknown>) => {
134
+ h.composerProps = props
135
+ return (
136
+ <>
137
+ <button type="button" onClick={() => (props.onEngineChange as (e: string) => void)?.("cloud")}>
138
+ set-engine-cloud
139
+ </button>
140
+ <button type="button" onClick={() => (props.onEngineChange as (e: string) => void)?.("local")}>
141
+ set-engine-local
142
+ </button>
143
+ <button type="button" onClick={() => (props.onLocalCwdChange as (p: string) => void)?.("/tmp/other")}>
144
+ set-cwd-other
145
+ </button>
146
+ <button type="button" onClick={() => (props.onLocalAgentIdChange as (a: string) => void)?.("acp:two")}>
147
+ set-agent-two
148
+ </button>
149
+ </>
150
+ )
151
+ },
152
+ }))
153
+
154
+ vi.mock("@/components/harness/ai-chat-history", () => ({ default: () => null }))
155
+ vi.mock("@/components/harness/agent-preset-picker", () => ({ AgentPresetPicker: () => null }))
156
+ vi.mock("@/components/harness/dock/dock-panel-container", () => ({ DockPanelContainer: () => null }))
157
+ vi.mock("@/components/harness/workbench/workbench-shell", () => ({
158
+ WorkbenchShell: ({ center }: { center: ReactNode }) => <div>{center}</div>,
159
+ }))
160
+ vi.mock("@/components/harness/code/code-workspace-sidebar", () => ({
161
+ CodeWorkspaceSidebar: () => null,
162
+ }))
163
+ vi.mock("@/components/confirm-dialog", () => ({ ConfirmDialog: () => null }))
164
+
165
+ /** 打开既有线程($threadId 路由 loader 形状) */
166
+ function renderThread(
167
+ conversation: HarnessInitialConversation | null,
168
+ threadId = "t1",
169
+ ) {
170
+ return render(
171
+ <HarnessWorkbenchPage
172
+ key={threadId}
173
+ initialThreadId={threadId}
174
+ initialMessages={[]}
175
+ initialConversation={conversation}
176
+ />,
177
+ )
178
+ }
179
+
180
+ function localThread(): HarnessInitialConversation {
181
+ return {
182
+ id: "t1",
183
+ title: null,
184
+ agentId: null,
185
+ engine: "local",
186
+ localCwd: "/tmp/ws",
187
+ localAgentId: "acp:one",
188
+ isArchived: false,
189
+ }
190
+ }
191
+
192
+ beforeEach(() => {
193
+ h.messages = []
194
+ h.updates = []
195
+ h.composerProps = null
196
+ window.localStorage.clear()
197
+ sessionStorage.clear()
198
+ })
199
+
200
+ afterEach(cleanup)
201
+
202
+ describe("persistThreadEngine 本地线程 cwd 写空护栏", () => {
203
+ it("local→cloud→local 往返:切回本地时以线程真源回填 cwd/agent,不写 null", async () => {
204
+ renderThread(localThread())
205
+ // 用户切到云端(合法切换:cwd/agent 按云端语义清空)
206
+ fireEvent.click(screen.getByRole("button", { name: "set-engine-cloud" }))
207
+ await waitFor(() => {
208
+ expect(h.updates).toEqual([
209
+ { id: "t1", engine: "cloud", localCwd: null, localAgentId: null },
210
+ ])
211
+ })
212
+ // 切回本地:客户端 cwd 已被云端分支重置为 null——修复前此处把 localCwd:null
213
+ // 落库(P1 数据破坏);修复后以线程真源回填
214
+ fireEvent.click(screen.getByRole("button", { name: "set-engine-local" }))
215
+ await waitFor(() => {
216
+ expect(h.updates[1]).toEqual({
217
+ id: "t1",
218
+ engine: "local",
219
+ localCwd: "/tmp/ws",
220
+ localAgentId: "acp:one",
221
+ })
222
+ })
223
+ // 客户端态同步恢复:composer 不再停留在「选择工作区」空 cwd
224
+ await waitFor(() => {
225
+ expect(h.composerProps?.engine).toBe("local")
226
+ expect(h.composerProps?.localCwd).toBe("/tmp/ws")
227
+ expect(h.composerProps?.localAgentId).toBe("acp:one")
228
+ })
229
+ })
230
+
231
+ it("线程真源缺失(页面先于线程创建打开)时跳过落库,不产生 (local, null) 写入", async () => {
232
+ // 模拟脚本先开 URL 后建线程:loader conversation=null,客户端 cwd/agent 皆空
233
+ renderThread(null, "t-fresh")
234
+ fireEvent.click(screen.getByRole("button", { name: "set-engine-local" }))
235
+ // 引擎选择是纯客户端态(composer 立即生效),但不落库——等用户补选目录
236
+ await waitFor(() => {
237
+ expect(h.composerProps?.engine).toBe("local")
238
+ })
239
+ expect(h.updates).toEqual([])
240
+ // 用户经目录选择器补齐后正常落库
241
+ fireEvent.click(screen.getByRole("button", { name: "set-cwd-other" }))
242
+ await waitFor(() => {
243
+ expect(h.updates).toEqual([
244
+ { id: "t-fresh", engine: "local", localCwd: "/tmp/other", localAgentId: null },
245
+ ])
246
+ })
247
+ })
248
+
249
+ it("agent 切换在客户端 cwd 缺失时以线程真源回填 cwd,agent 显式值生效", async () => {
250
+ renderThread(localThread())
251
+ // 先切云端把客户端 cwd 重置为 null,再切回本地目录态由真源恢复
252
+ fireEvent.click(screen.getByRole("button", { name: "set-engine-cloud" }))
253
+ await waitFor(() => {
254
+ expect(h.updates).toHaveLength(1)
255
+ })
256
+ fireEvent.click(screen.getByRole("button", { name: "set-agent-two" }))
257
+ await waitFor(() => {
258
+ expect(h.updates[1]).toEqual({
259
+ id: "t1",
260
+ engine: "local",
261
+ localCwd: "/tmp/ws",
262
+ localAgentId: "acp:two",
263
+ })
264
+ })
265
+ })
266
+
267
+ it("显式目录切换照常落库(用户选择优先于真源)", async () => {
268
+ renderThread(localThread())
269
+ fireEvent.click(screen.getByRole("button", { name: "set-cwd-other" }))
270
+ await waitFor(() => {
271
+ expect(h.updates).toEqual([
272
+ { id: "t1", engine: "local", localCwd: "/tmp/other", localAgentId: "acp:one" },
273
+ ])
274
+ })
275
+ })
276
+
277
+ it("线程已有消息时引擎/目录/agent 全部 no-op(既有客户端守卫不回归)", async () => {
278
+ h.messages = [{ id: "m1", role: "user", parts: [] }]
279
+ renderThread(localThread())
280
+ fireEvent.click(screen.getByRole("button", { name: "set-engine-cloud" }))
281
+ fireEvent.click(screen.getByRole("button", { name: "set-cwd-other" }))
282
+ fireEvent.click(screen.getByRole("button", { name: "set-agent-two" }))
283
+ await waitFor(() => {
284
+ expect(h.composerProps?.engine).toBe("local")
285
+ })
286
+ expect(h.updates).toEqual([])
287
+ })
288
+ })
289
+
290
+ describe("handoff 建会话后引擎态以线程值为准", () => {
291
+ it("localStorage 记忆为 local 时,handoff 云端线程把 composer 恢复为 cloud", async () => {
292
+ window.localStorage.setItem("allblue:harness:engine", "local")
293
+ stashPendingWorkspaceMessage("handoff hello")
294
+ render(<HarnessWorkbenchPage />)
295
+ await waitFor(() => {
296
+ // handoff 线程 engine=cloud(createConversationFn 缺省),composer 不再
297
+ // 显示本地(修复前沿用 localStorage 的 local,与线程失同步)
298
+ expect(h.composerProps?.engine).toBe("cloud")
299
+ })
300
+ expect(h.composerProps?.localCwd).toBeNull()
301
+ expect(h.composerProps?.localAgentId).toBeNull()
302
+ })
303
+ })
@@ -469,6 +469,13 @@ export function WorkbenchProvider({
469
469
  setConversations((prev) => (prev.find((c) => c.id === conv.id) ? prev : [conv, ...prev]))
470
470
  setActiveConversationId(conv.id)
471
471
  activeIdRef.current = conv.id
472
+ // 引擎态以线程值为准恢复(与 localCwd 写空护栏同源):handoff 建的是云端
473
+ // 线程(engine 缺省 cloud),客户端 engine/localCwd 沿用 localStorage 的
474
+ // local 会与线程失同步(composer 显示本地但 DB 是 cloud,后续写回把客户端
475
+ // null cwd 落库)。
476
+ setEngine(conv.engine === 'local' ? 'local' : 'cloud')
477
+ setLocalCwd(conv.localCwd ?? null)
478
+ setLocalAgentId(conv.localAgentId ?? null)
472
479
  clearHarnessCitations()
473
480
  setLatestCitations(undefined)
474
481
  // 与 handleSend 空态同理:经 pendingSend 槽等 hook 重绑定后再发送,
@@ -554,23 +561,41 @@ export function WorkbenchProvider({
554
561
  const persistThreadEngine = useCallback(
555
562
  async (nextEngine: 'cloud' | 'local', nextCwd: string | null, nextAgentId?: string | null) => {
556
563
  if (!activeIdRef.current || (chatRef.current?.messages.length ?? 0) > 0) return
564
+ const activeId = activeIdRef.current
565
+ // P1 护栏(真机验收:本地线程 ChatThread.localCwd 被工作台写空):写回前以
566
+ // 线程已知值为准核对。客户端 cwd/agent 与 DB 失同步(页面先于线程创建打开、
567
+ // 首轮流式未落库时刷新、local→cloud 往返把客户端 cwd 重置为 null)时,
568
+ // 禁止把 null 盲写回 DB——回退线程真源(侧栏列表项 / loader 元数据);
569
+ // 两者皆缺则跳过落库,等 handleLocalCwdChange 补齐后再写。
570
+ const threadTruth =
571
+ conversations.find((c) => c.id === activeId) ??
572
+ (initialConversation?.id === activeId ? initialConversation : undefined)
573
+ if (nextEngine === 'local' && !nextCwd && !threadTruth?.localCwd) return
574
+ const nextLocalCwd = nextEngine === 'local' ? (nextCwd ?? threadTruth?.localCwd ?? null) : null
575
+ const nextLocalAgentId =
576
+ nextEngine === 'local' ? (nextAgentId ?? localAgentId ?? threadTruth?.localAgentId ?? null) : null
557
577
  try {
558
578
  await updateConversationFn({
559
579
  data: {
560
- id: activeIdRef.current,
580
+ id: activeId,
561
581
  engine: nextEngine,
562
- localCwd: nextEngine === 'local' ? nextCwd : null,
563
- localAgentId: nextEngine === 'local' ? (nextAgentId ?? localAgentId ?? null) : null,
582
+ localCwd: nextLocalCwd,
583
+ localAgentId: nextLocalAgentId,
564
584
  },
565
585
  })
586
+ // 真源回填时同步恢复客户端态(composer 与线程保持一致,不再显示「选择工作区」)
587
+ if (nextEngine === 'local') {
588
+ setLocalCwd(nextLocalCwd)
589
+ setLocalAgentId(nextLocalAgentId)
590
+ }
566
591
  setConversations((prev) =>
567
592
  prev.map((conversation) =>
568
- conversation.id === activeIdRef.current
593
+ conversation.id === activeId
569
594
  ? {
570
595
  ...conversation,
571
596
  engine: nextEngine,
572
- localCwd: nextEngine === 'local' ? nextCwd : null,
573
- localAgentId: nextEngine === 'local' ? (nextAgentId ?? localAgentId ?? null) : null,
597
+ localCwd: nextLocalCwd,
598
+ localAgentId: nextLocalAgentId,
574
599
  }
575
600
  : conversation,
576
601
  ),
@@ -579,7 +604,7 @@ export function WorkbenchProvider({
579
604
  toastError(error, m.common_operationFailed())
580
605
  }
581
606
  },
582
- [localAgentId],
607
+ [localAgentId, conversations, initialConversation],
583
608
  )
584
609
 
585
610
  const handleEngineChange = useCallback(
@@ -112,7 +112,7 @@ export const SDK_GROUPS: SdkGroup[] = [
112
112
  "items": [
113
113
  {
114
114
  "name": "@allbluecn/web-app",
115
- "version": "v0.27.28",
115
+ "version": "v0.27.29",
116
116
  "lastUpdate": "Nov 10, 2026",
117
117
  "source": "apps/web/package.json",
118
118
  "docsUrl": "https://github.com/allbluecn/allblue"
@@ -0,0 +1,213 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+ // updateConversationFn × 本地线程 localCwd 写空护栏(真机验收 P1):
19
+ //
20
+ // 工作台 persistThreadEngine 把客户端 engine/localCwd/localAgentId 写回 DB;客户端
21
+ // 态与线程失同步(页面先于线程创建打开、首轮流式未落库时刷新、local→cloud 往返
22
+ // 重置客户端 cwd)时会传来 (engine=local, localCwd=null)——修复前 update 直接落库
23
+ // null,本地线程的授权工作目录被静默清空(workspace-binder 报「localCwd 为空」)。
24
+ // 服务端消息计数守卫(messages>0 拒绝)对 ChatMessage 行为 0 的线程(harness
25
+ // transcript / 本地 agent 会话文件持有转录)恒放行,拦不住该写法。
26
+ //
27
+ // 护栏语义:engine=local 时 cwd/agent 以 DB 现值回填(客户端 null 不清空),
28
+ // 两者皆空才拒绝(与 createConversationFn fail-closed 同口径);engine=cloud 仍
29
+ // 清空 cwd/agent(合法切换,schema 语义不变);title-only 更新不触碰引擎字段。
30
+
31
+ import { beforeEach, describe, expect, it, vi } from "vitest";
32
+
33
+ vi.mock("@tanstack/react-start", () => ({
34
+ createServerFn: (config: any) => {
35
+ const api: any = {
36
+ _validator: undefined,
37
+ _middlewares: [] as any[],
38
+ middleware(mws: any[]) {
39
+ this._middlewares.push(...mws);
40
+ return this;
41
+ },
42
+ validator(schema: any) {
43
+ this._validator = schema;
44
+ return this;
45
+ },
46
+ handler(fn: Function) {
47
+ const wrapped = async (args: any) => {
48
+ let data = args?.data;
49
+ if (this._validator && data !== undefined) {
50
+ data = this._validator.parse ? this._validator.parse(data) : data;
51
+ }
52
+ let context: any = {};
53
+ for (const mw of this._middlewares) {
54
+ const serverFn = mw?.options?.server;
55
+ if (!serverFn) continue;
56
+ const result = await serverFn({
57
+ data,
58
+ context,
59
+ method: "POST",
60
+ serverFnMeta: {},
61
+ signal: new AbortController().signal,
62
+ next: async (inner: any) => ({ context: { ...context, ...(inner?.context ?? {}) } }),
63
+ });
64
+ context = result.context;
65
+ }
66
+ return fn({ data, context });
67
+ };
68
+ return wrapped;
69
+ },
70
+ };
71
+ return api;
72
+ },
73
+ }));
74
+
75
+ const M = vi.hoisted(() => {
76
+ const f = () => vi.fn();
77
+ return {
78
+ chatThread: {
79
+ findFirst: f(),
80
+ findUnique: f(),
81
+ update: f(),
82
+ delete: f(),
83
+ create: f(),
84
+ },
85
+ chatMessage: { findMany: f(), deleteMany: f(), createMany: f() },
86
+ transaction: f(),
87
+ };
88
+ });
89
+
90
+ vi.mock("@allbluecn/database/get-prisma", () => ({
91
+ getPrisma: async () => M,
92
+ }));
93
+ vi.mock("@allbluecn/database", () => ({
94
+ prisma: M,
95
+ Prisma: { JsonNull: { prisma__DatabaseNull: true } },
96
+ }));
97
+ vi.mock("@/server/middlewares/auth-context", () => ({
98
+ authContextMiddleware: {
99
+ options: {
100
+ server: async ({ context, next }: { context: any; next: (inner: any) => any }) =>
101
+ next({ context: { ...context, user: { id: USER } } }),
102
+ },
103
+ },
104
+ }));
105
+ vi.mock("@/server/desktop-guest", () => ({
106
+ isDesktopServer: () => true,
107
+ }));
108
+
109
+ import { updateConversationFn } from "../chat/conversations";
110
+
111
+ const USER = "u-owner";
112
+
113
+ /** updateConversationFn 归属 + 消息计数查询返回的线程行 */
114
+ function ownedThread(overrides: {
115
+ engine?: string;
116
+ localCwd?: string | null;
117
+ localAgentId?: string | null;
118
+ messages?: number;
119
+ }) {
120
+ return {
121
+ id: "t1",
122
+ userId: USER,
123
+ engine: overrides.engine ?? "local",
124
+ localCwd: overrides.localCwd ?? null,
125
+ localAgentId: overrides.localAgentId ?? null,
126
+ _count: { messages: overrides.messages ?? 0 },
127
+ };
128
+ }
129
+
130
+ beforeEach(() => {
131
+ vi.clearAllMocks();
132
+ M.chatThread.update.mockResolvedValue({ sandboxPolicy: null });
133
+ });
134
+
135
+ describe("updateConversationFn × 本地线程 localCwd 写空护栏", () => {
136
+ it("本地线程 + 客户端失同步传 (local, null cwd) → 以 DB 现值回填,不清空", async () => {
137
+ M.chatThread.findFirst.mockResolvedValue(
138
+ ownedThread({ engine: "local", localCwd: "/tmp/ws", localAgentId: "acp:one" }),
139
+ );
140
+ await updateConversationFn({
141
+ data: { id: "t1", engine: "local", localCwd: null, localAgentId: null },
142
+ });
143
+ expect(M.chatThread.update).toHaveBeenCalledWith({
144
+ where: { id: "t1", userId: USER },
145
+ data: expect.objectContaining({
146
+ engine: "local",
147
+ localCwd: "/tmp/ws",
148
+ localAgentId: "acp:one",
149
+ }),
150
+ });
151
+ });
152
+
153
+ it("本地引擎且 DB/客户端皆无 cwd → 拒绝(fail-closed,与 createConversationFn 同口径)", async () => {
154
+ M.chatThread.findFirst.mockResolvedValue(
155
+ ownedThread({ engine: "cloud", localCwd: null, localAgentId: null }),
156
+ );
157
+ await expect(
158
+ updateConversationFn({ data: { id: "t1", engine: "local", localCwd: null } }),
159
+ ).rejects.toThrow("本地 Agent 需要先选择授权工作目录");
160
+ expect(M.chatThread.update).not.toHaveBeenCalled();
161
+ });
162
+
163
+ it("显式 cwd/agent 切换照常生效(用户选择优先于 DB 现值)", async () => {
164
+ M.chatThread.findFirst.mockResolvedValue(
165
+ ownedThread({ engine: "local", localCwd: "/tmp/ws", localAgentId: "acp:one" }),
166
+ );
167
+ await updateConversationFn({
168
+ data: { id: "t1", engine: "local", localCwd: "/tmp/new", localAgentId: "acp:two" },
169
+ });
170
+ expect(M.chatThread.update).toHaveBeenCalledWith({
171
+ where: { id: "t1", userId: USER },
172
+ data: expect.objectContaining({
173
+ engine: "local",
174
+ localCwd: "/tmp/new",
175
+ localAgentId: "acp:two",
176
+ }),
177
+ });
178
+ });
179
+
180
+ it("local→cloud 合法切换仍清空 cwd/agent(schema 语义不变)", async () => {
181
+ M.chatThread.findFirst.mockResolvedValue(
182
+ ownedThread({ engine: "local", localCwd: "/tmp/ws", localAgentId: "acp:one" }),
183
+ );
184
+ await updateConversationFn({ data: { id: "t1", engine: "cloud" } });
185
+ expect(M.chatThread.update).toHaveBeenCalledWith({
186
+ where: { id: "t1", userId: USER },
187
+ data: expect.objectContaining({
188
+ engine: "cloud",
189
+ localCwd: null,
190
+ localAgentId: null,
191
+ }),
192
+ });
193
+ });
194
+
195
+ it("已有消息的线程拒绝引擎写回(既有守卫不回归)", async () => {
196
+ M.chatThread.findFirst.mockResolvedValue(
197
+ ownedThread({ engine: "local", localCwd: "/tmp/ws", messages: 2 }),
198
+ );
199
+ await expect(
200
+ updateConversationFn({ data: { id: "t1", engine: "cloud" } }),
201
+ ).rejects.toThrow("该会话已有消息");
202
+ expect(M.chatThread.update).not.toHaveBeenCalled();
203
+ });
204
+
205
+ it("title-only 更新不触碰引擎字段(部分更新语义不回归)", async () => {
206
+ await updateConversationFn({ data: { id: "t1", title: "改名" } });
207
+ expect(M.chatThread.findFirst).not.toHaveBeenCalled();
208
+ expect(M.chatThread.update).toHaveBeenCalledWith({
209
+ where: { id: "t1", userId: USER },
210
+ data: { title: "改名" },
211
+ });
212
+ });
213
+ });
@@ -221,17 +221,21 @@ export const updateConversationFn = createServerFn({ method: "POST" })
221
221
  throw new Error("本地 Agent 仅在桌面客户端可用")
222
222
  }
223
223
  update.engine = nextEngine
224
- update.localCwd =
225
- nextEngine === "local"
226
- ? (data.localCwd !== undefined ? data.localCwd : thread.localCwd)
227
- : null
228
- update.localAgentId =
229
- nextEngine === "local"
230
- ? (data.localAgentId !== undefined ? data.localAgentId : thread.localAgentId)
231
- : null
232
224
  if (nextEngine === "local") {
225
+ // P1 护栏(真机验收:工作台把本地线程 ChatThread.localCwd 写空):本地引擎
226
+ // 不可静默清空已授权目录/agent——客户端态失同步传 null 时以 DB 现值为准回填,
227
+ // 两者皆空才拒绝(与 createConversationFn 的 fail-closed 同口径)。
228
+ const nextCwd = data.localCwd ?? thread.localCwd
229
+ if (!nextCwd) {
230
+ throw new Error("本地 Agent 需要先选择授权工作目录")
231
+ }
232
+ update.localCwd = nextCwd
233
+ update.localAgentId = data.localAgentId ?? thread.localAgentId
233
234
  // 本地 Agent 不绑定云端 Agent 预设
234
235
  update.agentId = null
236
+ } else {
237
+ update.localCwd = null
238
+ update.localAgentId = null
235
239
  }
236
240
  }
237
241