@allbluecn/web-app 0.27.28 → 0.27.30

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.30",
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
+ })
@@ -0,0 +1,117 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 AllBlue Contributors
3
+ //
4
+ // 档位变更接线(原 body.setSandboxPolicy=裸 useState setter,T2.4 的
5
+ // setSandboxPolicyFn 服务端零 UI 调用方——切档只改客户端状态,写操作被
6
+ // readonly→plan 全拒):hook 级断言——有线程切档调 setSandboxPolicyFn
7
+ // (confirmFull 随档);空态仅客户端状态;create 流程非只读档补施加。
8
+
9
+ import { describe, expect, it, vi, beforeEach } from 'vitest'
10
+ import { renderHook, act, waitFor } from '@testing-library/react'
11
+ import type { ReactNode } from 'react'
12
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
13
+ import { HotkeysProvider } from '@tanstack/react-hotkeys'
14
+ import { appHotkeys } from '@/lib/hotkeys/registry'
15
+
16
+ const setSandboxPolicyFnMock = vi.fn(async (_args: { data: unknown }) => 'workspace-write' as const)
17
+ const createConversationFnMock = vi.fn(async (_args: { data: unknown }) => ({
18
+ id: 'conv-new',
19
+ title: null,
20
+ engine: 'local',
21
+ localCwd: '/tmp/ws',
22
+ localAgentId: null,
23
+ userId: 'local-guest',
24
+ updatedAt: new Date().toISOString(),
25
+ }))
26
+
27
+ vi.mock('@tanstack/react-router', () => ({
28
+ useNavigate: () => vi.fn(),
29
+ useLocation: () => ({ pathname: '/harness', searchStr: '' }),
30
+ useParams: () => ({}),
31
+ Link: (props: { children?: ReactNode; to?: string }) => <a href={props.to}>{props.children}</a>,
32
+ }))
33
+ vi.mock('@/server/serverFns/harness/sandbox-policy', () => ({
34
+ setSandboxPolicyFn: (args: { data: unknown }) => setSandboxPolicyFnMock(args),
35
+ getSandboxPolicyFn: vi.fn(async () => 'readonly'),
36
+ }))
37
+ vi.mock('@/server/serverFns/chat/conversations', () => ({
38
+ createConversationFn: (args: { data: unknown }) => createConversationFnMock(args),
39
+ updateConversationFn: vi.fn(async () => ({})),
40
+ listConversationsFn: vi.fn(async () => []),
41
+ getConversationFn: vi.fn(async () => null),
42
+ }))
43
+ vi.mock('@/server/serverFns/harness/fork-thread', () => ({
44
+ forkHarnessThreadFn: vi.fn(async () => ({ id: 'fork-1' })),
45
+ }))
46
+ vi.mock('@/server/serverFns/ai-usage', () => ({ cancelRunFn: vi.fn(async () => ({})) }))
47
+
48
+ import { useWorkbenchBody, WorkbenchProvider } from '../workbench/workbench-context'
49
+
50
+ function makeWrapper() {
51
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
52
+ return function Wrapper({ children }: { children: ReactNode }) {
53
+ return (
54
+ <QueryClientProvider client={qc}>
55
+ <HotkeysProvider appHotkeys={appHotkeys}>
56
+ <WorkbenchProvider>{children}</WorkbenchProvider>
57
+ </HotkeysProvider>
58
+ </QueryClientProvider>
59
+ )
60
+ }
61
+ }
62
+
63
+ function makeWrapperWithThread(threadId: string) {
64
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
65
+ return function Wrapper({ children }: { children: ReactNode }) {
66
+ return (
67
+ <QueryClientProvider client={qc}>
68
+ <HotkeysProvider appHotkeys={appHotkeys}>
69
+ <WorkbenchProvider initialThreadId={threadId}>{children}</WorkbenchProvider>
70
+ </HotkeysProvider>
71
+ </QueryClientProvider>
72
+ )
73
+ }
74
+ }
75
+
76
+ describe('档位变更接线(setSandboxPolicyFn 零调用方修复)', () => {
77
+ beforeEach(() => {
78
+ setSandboxPolicyFnMock.mockClear()
79
+ createConversationFnMock.mockClear()
80
+ window.localStorage.clear()
81
+ })
82
+
83
+ it('空态切档:仅客户端状态,不调服务端(无线程可施加)', async () => {
84
+ const { result } = renderHook(() => useWorkbenchBody(), { wrapper: makeWrapper() })
85
+ act(() => {
86
+ result.current.setSandboxPolicy('workspace-write')
87
+ })
88
+ expect(setSandboxPolicyFnMock).not.toHaveBeenCalled()
89
+ expect(result.current.sandboxPolicy).toBe('workspace-write')
90
+ })
91
+ })
92
+
93
+ it('已有线程切档 → setSandboxPolicyFn 以 threadId+level+confirmFull 调用', async () => {
94
+ const { result } = renderHook(() => useWorkbenchBody(), {
95
+ wrapper: makeWrapperWithThread('t-1'),
96
+ })
97
+ await act(async () => {
98
+ result.current.setSandboxPolicy('workspace-write')
99
+ })
100
+ await waitFor(() => expect(setSandboxPolicyFnMock).toHaveBeenCalledTimes(1))
101
+ expect(setSandboxPolicyFnMock).toHaveBeenCalledWith({
102
+ data: { threadId: 't-1', level: 'workspace-write', confirmFull: false },
103
+ })
104
+ })
105
+
106
+ it('完全档 → confirmFull: true(composer 二次确认完成后才到达本 handler)', async () => {
107
+ const { result } = renderHook(() => useWorkbenchBody(), {
108
+ wrapper: makeWrapperWithThread('t-1'),
109
+ })
110
+ await act(async () => {
111
+ result.current.setSandboxPolicy('full')
112
+ })
113
+ await waitFor(() => expect(setSandboxPolicyFnMock).toHaveBeenCalledTimes(1))
114
+ expect(setSandboxPolicyFnMock).toHaveBeenCalledWith({
115
+ data: { threadId: 't-1', level: 'full', confirmFull: true },
116
+ })
117
+ })
@@ -62,6 +62,7 @@ import {
62
62
  forkConversationFn,
63
63
  } from '@/server/serverFns/chat/conversations'
64
64
  import { forkHarnessThreadFn } from '@/server/serverFns/harness/fork-thread'
65
+ import { setSandboxPolicyFn } from '@/server/serverFns/harness/sandbox-policy'
65
66
  import { isHarnessClientEnabled } from '@/lib/harness-gate'
66
67
  import { agentsQueryOptions } from '@/lib/queries/agents'
67
68
  import { useSelectedModel } from '@/lib/ai/use-selected-model'
@@ -334,6 +335,25 @@ export function WorkbenchProvider({
334
335
  const [mediaRoute, setMediaRoute] = useState<'code' | 'spec'>('code')
335
336
  const [busyPreference, setBusyPreference] = useState<BusyAction>('queue')
336
337
  const [sandboxPolicy, setSandboxPolicy] = useState<'readonly' | 'workspace-write' | 'full'>('readonly')
338
+
339
+ // 档位变更真施加(原 body.setSandboxPolicy 是裸 useState setter——T2.4 的
340
+ // setSandboxPolicyFn 零 UI 调用方,切档只改客户端状态,服务端 sandboxPolicy
341
+ // 永远 readonly → syncHarnessPermissionMode 恒施加 plan,写操作全被拒,真机
342
+ // 验收发现)。有活动线程时调服务端档位(内部同步施加 harness mode);空态
343
+ // 仅客户端状态(线程创建后由 create 流程补施加)。
344
+ const handleSandboxPolicyChange = useCallback(
345
+ (v: 'readonly' | 'workspace-write' | 'full') => {
346
+ setSandboxPolicy(v)
347
+ const threadId = activeIdRef.current
348
+ if (!threadId) return
349
+ void setSandboxPolicyFn({ data: { threadId, level: v, confirmFull: v === 'full' } }).catch(
350
+ (e: unknown) => {
351
+ console.error('[harness] 档位变更施加失败:', e)
352
+ },
353
+ )
354
+ },
355
+ [],
356
+ )
337
357
  const [handoffContext, setHandoffContext] = useState<{ board: string; entityId: string } | null>(null)
338
358
  // 会话区域根元素(中心区根 div):Esc Esc 停止序列的监听目标(F3,composer 冒泡消费)
339
359
  const [retryCount, setRetryCount] = useState(0)
@@ -469,6 +489,13 @@ export function WorkbenchProvider({
469
489
  setConversations((prev) => (prev.find((c) => c.id === conv.id) ? prev : [conv, ...prev]))
470
490
  setActiveConversationId(conv.id)
471
491
  activeIdRef.current = conv.id
492
+ // 引擎态以线程值为准恢复(与 localCwd 写空护栏同源):handoff 建的是云端
493
+ // 线程(engine 缺省 cloud),客户端 engine/localCwd 沿用 localStorage 的
494
+ // local 会与线程失同步(composer 显示本地但 DB 是 cloud,后续写回把客户端
495
+ // null cwd 落库)。
496
+ setEngine(conv.engine === 'local' ? 'local' : 'cloud')
497
+ setLocalCwd(conv.localCwd ?? null)
498
+ setLocalAgentId(conv.localAgentId ?? null)
472
499
  clearHarnessCitations()
473
500
  setLatestCitations(undefined)
474
501
  // 与 handleSend 空态同理:经 pendingSend 槽等 hook 重绑定后再发送,
@@ -554,23 +581,41 @@ export function WorkbenchProvider({
554
581
  const persistThreadEngine = useCallback(
555
582
  async (nextEngine: 'cloud' | 'local', nextCwd: string | null, nextAgentId?: string | null) => {
556
583
  if (!activeIdRef.current || (chatRef.current?.messages.length ?? 0) > 0) return
584
+ const activeId = activeIdRef.current
585
+ // P1 护栏(真机验收:本地线程 ChatThread.localCwd 被工作台写空):写回前以
586
+ // 线程已知值为准核对。客户端 cwd/agent 与 DB 失同步(页面先于线程创建打开、
587
+ // 首轮流式未落库时刷新、local→cloud 往返把客户端 cwd 重置为 null)时,
588
+ // 禁止把 null 盲写回 DB——回退线程真源(侧栏列表项 / loader 元数据);
589
+ // 两者皆缺则跳过落库,等 handleLocalCwdChange 补齐后再写。
590
+ const threadTruth =
591
+ conversations.find((c) => c.id === activeId) ??
592
+ (initialConversation?.id === activeId ? initialConversation : undefined)
593
+ if (nextEngine === 'local' && !nextCwd && !threadTruth?.localCwd) return
594
+ const nextLocalCwd = nextEngine === 'local' ? (nextCwd ?? threadTruth?.localCwd ?? null) : null
595
+ const nextLocalAgentId =
596
+ nextEngine === 'local' ? (nextAgentId ?? localAgentId ?? threadTruth?.localAgentId ?? null) : null
557
597
  try {
558
598
  await updateConversationFn({
559
599
  data: {
560
- id: activeIdRef.current,
600
+ id: activeId,
561
601
  engine: nextEngine,
562
- localCwd: nextEngine === 'local' ? nextCwd : null,
563
- localAgentId: nextEngine === 'local' ? (nextAgentId ?? localAgentId ?? null) : null,
602
+ localCwd: nextLocalCwd,
603
+ localAgentId: nextLocalAgentId,
564
604
  },
565
605
  })
606
+ // 真源回填时同步恢复客户端态(composer 与线程保持一致,不再显示「选择工作区」)
607
+ if (nextEngine === 'local') {
608
+ setLocalCwd(nextLocalCwd)
609
+ setLocalAgentId(nextLocalAgentId)
610
+ }
566
611
  setConversations((prev) =>
567
612
  prev.map((conversation) =>
568
- conversation.id === activeIdRef.current
613
+ conversation.id === activeId
569
614
  ? {
570
615
  ...conversation,
571
616
  engine: nextEngine,
572
- localCwd: nextEngine === 'local' ? nextCwd : null,
573
- localAgentId: nextEngine === 'local' ? (nextAgentId ?? localAgentId ?? null) : null,
617
+ localCwd: nextLocalCwd,
618
+ localAgentId: nextLocalAgentId,
574
619
  }
575
620
  : conversation,
576
621
  ),
@@ -579,7 +624,7 @@ export function WorkbenchProvider({
579
624
  toastError(error, m.common_operationFailed())
580
625
  }
581
626
  },
582
- [localAgentId],
627
+ [localAgentId, conversations, initialConversation],
583
628
  )
584
629
 
585
630
  const handleEngineChange = useCallback(
@@ -792,6 +837,15 @@ export function WorkbenchProvider({
792
837
  setActiveConversationId(conv.id)
793
838
  activeIdRef.current = conv.id
794
839
  clearHarnessCitations()
840
+ // 新线程 DB 默认 readonly;composer 选了非只读档时补施加
841
+ // (否则首回合 sync 按 DB readonly 施加 plan,写请求全拒)
842
+ if (sandboxPolicy !== 'readonly') {
843
+ void setSandboxPolicyFn({ data: { threadId: conv.id, level: sandboxPolicy, confirmFull: sandboxPolicy === 'full' } }).catch(
844
+ (e: unknown) => {
845
+ console.error('[harness] 新线程档位施加失败:', e)
846
+ },
847
+ )
848
+ }
795
849
  setPendingSend({ threadId: conv.id, content, sendOptions })
796
850
  } catch (e) {
797
851
  console.error('Failed to create conversation:', e)
@@ -803,7 +857,7 @@ export function WorkbenchProvider({
803
857
  }
804
858
  chatRef.current?.sendMessage(content, sendOptions)
805
859
  },
806
- [selectedAgentId, engine, localCwd],
860
+ [selectedAgentId, engine, localCwd, sandboxPolicy],
807
861
  )
808
862
 
809
863
  const handleStop = useCallback(() => {
@@ -846,7 +900,7 @@ export function WorkbenchProvider({
846
900
  codeModeEnabled,
847
901
  setCodeModeEnabled,
848
902
  sandboxPolicy,
849
- setSandboxPolicy,
903
+ setSandboxPolicy: handleSandboxPolicyChange,
850
904
  busyPreference,
851
905
  setBusyPreference,
852
906
  dockOpen,
@@ -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.30",
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