@allbluecn/web-app 0.27.27 → 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 +1 -1
- package/src/components/harness/__tests__/workbench-localcwd-persist.test.tsx +303 -0
- package/src/components/harness/workbench/workbench-context.tsx +32 -7
- package/src/lib/changelog/sdk-versions.ts +1 -1
- package/src/routes/api/harness/$.ts +3 -4
- package/src/server/harness/__tests__/model-catalog.test.ts +64 -0
- package/src/server/harness/define.server.ts +15 -1
- package/src/server/harness/host.server.ts +30 -4
- package/src/server/harness/model-catalog.server.ts +46 -1
- package/src/server/harness/permission-mode.server.ts +1 -1
- package/src/server/serverFns/__tests__/update-conversation-localcwd-guard.test.ts +213 -0
- package/src/server/serverFns/chat/conversations.ts +13 -9
- package/src/server/serverFns/design/ai/providers.ts +48 -0
- package/src/server/serverFns/harness/fork-thread.ts +1 -1
package/package.json
CHANGED
|
@@ -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:
|
|
580
|
+
id: activeId,
|
|
561
581
|
engine: nextEngine,
|
|
562
|
-
localCwd:
|
|
563
|
-
localAgentId:
|
|
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 ===
|
|
593
|
+
conversation.id === activeId
|
|
569
594
|
? {
|
|
570
595
|
...conversation,
|
|
571
596
|
engine: nextEngine,
|
|
572
|
-
localCwd:
|
|
573
|
-
localAgentId:
|
|
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.
|
|
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"
|
|
@@ -48,9 +48,8 @@ async function handleHarnessRequest(request: Request): Promise<Response> {
|
|
|
48
48
|
// describe/snapshot/transcript 三个 GET 全部 `Harness * failed (500)` 且 SSE 重连
|
|
49
49
|
// 退避耗尽 → 「重试次数已达上限」。收敛为结构化 503,不再让装配期故障裸奔。
|
|
50
50
|
try {
|
|
51
|
-
const [{
|
|
51
|
+
const [{ getHarnessRuntime, harnessMediaSecret }, { createHarnessHandler }, { getCurrentSession }, { checkAiRateLimit, RateLimitExceededError }] = await Promise.all([
|
|
52
52
|
import('@/server/harness/host.server'),
|
|
53
|
-
import('@/server/harness/define.server'),
|
|
54
53
|
import('@tanstack/ai-harness/server'),
|
|
55
54
|
import('@/lib/session'),
|
|
56
55
|
import('@/server/lib/rate-limit'),
|
|
@@ -84,8 +83,8 @@ async function handleHarnessRequest(request: Request): Promise<Response> {
|
|
|
84
83
|
// 可信上下文覆写)。access/acceptInput 已在 getHarnessHost 单例内装配。
|
|
85
84
|
// media 签名密钥:host 带 ownership(Prisma LogStore)时官方强制,缺失即抛错
|
|
86
85
|
// (桌面真机 Bug#1 根因,详见 harnessMediaSecret 注释)。
|
|
87
|
-
const host =
|
|
88
|
-
const handler = createHarnessHandler({ host, harness
|
|
86
|
+
const { host, harness } = await getHarnessRuntime()
|
|
87
|
+
const handler = createHarnessHandler({ host, harness, media: { secret: harnessMediaSecret() } })
|
|
89
88
|
return await handler(request)
|
|
90
89
|
} catch (error) {
|
|
91
90
|
console.error('[harness] 请求处理失败(host 装配或 handler 异常):', error)
|
|
@@ -63,3 +63,67 @@ describe('buildModelCatalog(多 provider 目录)', () => {
|
|
|
63
63
|
}
|
|
64
64
|
})
|
|
65
65
|
})
|
|
66
|
+
|
|
67
|
+
// ============ 桌面动态目录(buildDesktopModelCatalog) ============
|
|
68
|
+
import { beforeEach, vi } from 'vitest'
|
|
69
|
+
|
|
70
|
+
const prismaState = {
|
|
71
|
+
configs: [] as Array<{ providerId: string; models: unknown; baseUrl: string | null }>,
|
|
72
|
+
}
|
|
73
|
+
vi.mock('@allbluecn/database', () => ({
|
|
74
|
+
prisma: {
|
|
75
|
+
aiProviderConfig: {
|
|
76
|
+
findMany: vi.fn(async () => prismaState.configs),
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
}))
|
|
80
|
+
|
|
81
|
+
// gate:桌面态(动态目录仅桌面派生)
|
|
82
|
+
vi.mock('@/server/harness/gate.server', () => ({
|
|
83
|
+
isHarnessHostEnabled: () => true,
|
|
84
|
+
}))
|
|
85
|
+
vi.mock('@/server/desktop-guest', () => ({
|
|
86
|
+
isDesktopServer: () => true,
|
|
87
|
+
GUEST_USER_ID: 'local-guest',
|
|
88
|
+
buildGuestSession: () => ({}),
|
|
89
|
+
}))
|
|
90
|
+
|
|
91
|
+
describe('buildDesktopModelCatalog(用户配置动态派生)', () => {
|
|
92
|
+
beforeEach(() => {
|
|
93
|
+
prismaState.configs = []
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
it('刷新模型拿回的 models 进目录(裸 id + 别名,baseUrl 用户值优先)', async () => {
|
|
97
|
+
const { buildDesktopModelCatalog } = await import('../model-catalog.server')
|
|
98
|
+
prismaState.configs = [
|
|
99
|
+
{ providerId: 'sensenova', models: ['SenseNova-2', '自定义模型X'], baseUrl: 'https://my-proxy.example.com/v1' },
|
|
100
|
+
]
|
|
101
|
+
const catalog = await buildDesktopModelCatalog()
|
|
102
|
+
expect(Object.keys(catalog)).toContain('SenseNova-2')
|
|
103
|
+
expect(Object.keys(catalog)).toContain('自定义模型X')
|
|
104
|
+
expect(Object.keys(catalog)).toContain('sensenova/SenseNova-2')
|
|
105
|
+
expect(Object.keys(catalog)).toContain('default')
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
it('种子不再参与:内置过期的模型(未在用户配置中)不在目录', async () => {
|
|
109
|
+
const { buildDesktopModelCatalog } = await import('../model-catalog.server')
|
|
110
|
+
prismaState.configs = [
|
|
111
|
+
{ providerId: 'sensenova', models: ['SenseNova-2'], baseUrl: null },
|
|
112
|
+
]
|
|
113
|
+
const catalog = await buildDesktopModelCatalog()
|
|
114
|
+
// 种子的 SenseChat-6 未被用户配置 → 不进桌面目录
|
|
115
|
+
expect(Object.keys(catalog)).not.toContain('SenseChat-6')
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it('models 非字符串项被过滤;无种子元数据的 providerId 跳过', async () => {
|
|
119
|
+
const { buildDesktopModelCatalog } = await import('../model-catalog.server')
|
|
120
|
+
prismaState.configs = [
|
|
121
|
+
{ providerId: 'unknown-provider', models: ['m1'], baseUrl: null },
|
|
122
|
+
{ providerId: 'sensenova', models: ['ok-model', 42, null], baseUrl: null },
|
|
123
|
+
]
|
|
124
|
+
const catalog = await buildDesktopModelCatalog()
|
|
125
|
+
expect(Object.keys(catalog)).toContain('ok-model')
|
|
126
|
+
expect(Object.keys(catalog)).not.toContain('m1')
|
|
127
|
+
expect(Object.keys(catalog)).not.toContain('42')
|
|
128
|
+
})
|
|
129
|
+
})
|
|
@@ -209,5 +209,19 @@ export function buildHarnessDefinition(overrides?: {
|
|
|
209
209
|
})
|
|
210
210
|
}
|
|
211
211
|
|
|
212
|
-
/** 单例 harness
|
|
212
|
+
/** 单例 harness 定义(静态种子目录;测试与默认引用)。 */
|
|
213
213
|
export const allblueHarness: AnyHarness = buildHarnessDefinition()
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* 运行时 harness 定义:桌面用**动态目录**(当前用户 AiProviderConfig 派生——
|
|
217
|
+
* 刷新模型/自定义 id,内置种子会过期),云端/web 保持种子静态目录。
|
|
218
|
+
* host.server 的单例重建(配置变更 → closeHarnessHost)时一起重建。
|
|
219
|
+
*/
|
|
220
|
+
export async function buildAllblueHarnessForRuntime(): Promise<AnyHarness> {
|
|
221
|
+
const { isDesktopServer } = await import('@/server/desktop-guest')
|
|
222
|
+
if (isDesktopServer()) {
|
|
223
|
+
const { buildDesktopModelCatalog } = await import('@/server/harness/model-catalog.server')
|
|
224
|
+
return buildHarnessDefinition({ models: await buildDesktopModelCatalog() })
|
|
225
|
+
}
|
|
226
|
+
return allblueHarness
|
|
227
|
+
}
|
|
@@ -22,7 +22,7 @@ import { createHarnessHost, type AcceptInput, type AnyHarness, type HarnessAcces
|
|
|
22
22
|
import { createHash, randomBytes } from 'node:crypto'
|
|
23
23
|
|
|
24
24
|
import { isHarnessHostEnabled } from '@/server/harness/gate.server'
|
|
25
|
-
import {
|
|
25
|
+
import { buildAllblueHarnessForRuntime } from '@/server/harness/define.server'
|
|
26
26
|
import { createReadOnlyCredentialStore } from '@/server/harness/credentials.server'
|
|
27
27
|
import { harnessAccess } from '@/server/harness/access.server'
|
|
28
28
|
import { trustedAcceptInput } from '@/server/harness/trusted-context.server'
|
|
@@ -34,6 +34,7 @@ export type { HarnessHostUser }
|
|
|
34
34
|
/** globalThis 上的单例槽位(HMR 重复构造防护)。 */
|
|
35
35
|
interface HostGlobal {
|
|
36
36
|
__allblue_harness_host__?: HarnessHost<HarnessHostUser>
|
|
37
|
+
__allblue_harness_def__?: AnyHarness
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
/**
|
|
@@ -90,7 +91,17 @@ export function buildHarnessHost(
|
|
|
90
91
|
* 续接上次未完的回合);后续调用复用同一实例(含 HMR 后的模块重载——globalThis
|
|
91
92
|
* 跨模块实例存活,故 recover 每进程只跑一次)。
|
|
92
93
|
*/
|
|
93
|
-
|
|
94
|
+
/** host 与 harness 定义成对返回(路由 createHarnessHandler 必须用同一次构建的 harness)。 */
|
|
95
|
+
export async function getHarnessRuntime(): Promise<{
|
|
96
|
+
host: HarnessHost<HarnessHostUser>
|
|
97
|
+
harness: AnyHarness
|
|
98
|
+
}> {
|
|
99
|
+
const host = await getHarnessHost()
|
|
100
|
+
const g = globalThis as unknown as HostGlobal
|
|
101
|
+
return { host, harness: g.__allblue_harness_def__! }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function getHarnessHost(): Promise<HarnessHost<HarnessHostUser>> {
|
|
94
105
|
if (!isHarnessHostEnabled()) {
|
|
95
106
|
throw new Error(
|
|
96
107
|
'[harness] host 未启用:仅在桌面部署(DEPLOY_TARGET=desktop)或显式 dev 开关' +
|
|
@@ -99,16 +110,22 @@ export function getHarnessHost(): HarnessHost<HarnessHostUser> {
|
|
|
99
110
|
}
|
|
100
111
|
|
|
101
112
|
const g = globalThis as unknown as HostGlobal
|
|
102
|
-
if (g.__allblue_harness_host__
|
|
113
|
+
if (g.__allblue_harness_host__ && g.__allblue_harness_def__) {
|
|
114
|
+
return g.__allblue_harness_host__
|
|
115
|
+
}
|
|
103
116
|
|
|
104
117
|
// 装配 access(getCurrentSession 映射 + owner-only + 抢建防护)与 acceptInput
|
|
105
118
|
// (可信上下文覆写,P0-2)。host.server.ts 仅服务端加载(经 /api/harness 路由,
|
|
106
119
|
// server.handlers 剥离),故服务端 import 安全;客户端永不 import 本文件。
|
|
107
|
-
|
|
120
|
+
// harness 定义走运行时工厂:桌面目录按当前用户配置动态派生(刷新模型/自定义
|
|
121
|
+
// id,内置种子会过期),配置变更由 serverFn closeHarnessHost() 触发本函数重建。
|
|
122
|
+
const harness = await buildAllblueHarnessForRuntime()
|
|
123
|
+
const host = buildHarnessHost(harness, {
|
|
108
124
|
access: harnessAccess(),
|
|
109
125
|
acceptInput: trustedAcceptInput(),
|
|
110
126
|
})
|
|
111
127
|
g.__allblue_harness_host__ = host
|
|
128
|
+
g.__allblue_harness_def__ = harness
|
|
112
129
|
|
|
113
130
|
// 启动恢复(官方 host.recover(),host.d.ts:845):接管上次宿主停止后遗留的
|
|
114
131
|
// 待跑输入 / 到期 schedule。fire-and-forget——getHarnessHost 同步返回,恢复在后台
|
|
@@ -161,6 +178,15 @@ export async function closeHarnessHost(options: {
|
|
|
161
178
|
const host = g.__allblue_harness_host__
|
|
162
179
|
if (host) {
|
|
163
180
|
await host.close({ recoverable: options.recoverable === true })
|
|
181
|
+
}
|
|
182
|
+
// host 与 harness 定义成对清除:模型目录变更(刷新模型/保存/删除)后
|
|
183
|
+
// 下次 getHarnessHost() 以新目录重建 host + harness 定义。
|
|
184
|
+
// 注意 recoverable close(桌面退出)语义不变:不清场待续接——仅在
|
|
185
|
+
// 非 recoverable(目录变更/测试)时成对清 harness 定义。
|
|
186
|
+
if (options.recoverable === true) {
|
|
187
|
+
g.__allblue_harness_host__ = undefined
|
|
188
|
+
} else {
|
|
164
189
|
g.__allblue_harness_host__ = undefined
|
|
190
|
+
g.__allblue_harness_def__ = undefined
|
|
165
191
|
}
|
|
166
192
|
}
|
|
@@ -18,6 +18,7 @@ import { createOpenRouterText } from '@tanstack/ai-openrouter'
|
|
|
18
18
|
import { createOpenaiChat } from '@tanstack/ai-openai'
|
|
19
19
|
import { openaiCompatibleText } from '@tanstack/ai-openai/compatible'
|
|
20
20
|
import { createAnthropicChat } from '@tanstack/ai-anthropic'
|
|
21
|
+
import { prisma } from '@allbluecn/database'
|
|
21
22
|
import { SEED_AI_PROVIDERS, type AiProviderMeta } from '@allbluecn/kernel'
|
|
22
23
|
|
|
23
24
|
/**
|
|
@@ -49,8 +50,10 @@ const DEFAULT_MODEL = 'openrouter/auto'
|
|
|
49
50
|
function keyedAdapterFactory(
|
|
50
51
|
provider: AiProviderMeta,
|
|
51
52
|
modelId: string,
|
|
53
|
+
baseUrlOverride?: string | null,
|
|
52
54
|
): KeyedAdapter<AnyTextAdapter> | null {
|
|
53
|
-
|
|
55
|
+
// 用户配置的 baseUrl 优先(BYOK 自定义端点),回落 provider 种子默认
|
|
56
|
+
const baseURL = baseUrlOverride || provider.defaultBaseUrl
|
|
54
57
|
switch (provider.adapterKind) {
|
|
55
58
|
case 'openai':
|
|
56
59
|
// create*Chat 形式把 apiKey 作独立参数(keyedAdapter 工厂约定);模型 id
|
|
@@ -122,3 +125,45 @@ export function defaultKeyedAdapter(): KeyedAdapter<AnyTextAdapter> {
|
|
|
122
125
|
createOpenRouterText(DEFAULT_MODEL as never, key, { appTitle: 'AllBlue' }) as unknown as AnyTextAdapter,
|
|
123
126
|
)
|
|
124
127
|
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 桌面动态模型目录:从**当前用户的 AiProviderConfig** 派生(刷新模型 API 拿回的
|
|
131
|
+
* models / 用户手填的自定义 id),而非 kernel 种子——内置清单会过期(真机验收
|
|
132
|
+
* 实证:商汤种子 id SenseChat-6/5/5-Lite 全被用户端点 404)。桌面是单用户场景,
|
|
133
|
+
* 目录即该用户配置的全集;配置变更(刷新模型/保存/删除)由 serverFn 触发
|
|
134
|
+
* closeHarnessHost() → 下次请求重建 host + harness 定义。
|
|
135
|
+
*
|
|
136
|
+
* key 域与 #662 一致:裸模型 id(与工作台 选择模型 同域)+ providerId/modelId 别名。
|
|
137
|
+
* baseUrl 取用户配置值优先(BYOK 自定义端点)。
|
|
138
|
+
*/
|
|
139
|
+
export async function buildDesktopModelCatalog(): Promise<
|
|
140
|
+
Record<string, AnyTextAdapter | KeyedAdapter<AnyTextAdapter>>
|
|
141
|
+
> {
|
|
142
|
+
const catalog: Record<string, AnyTextAdapter | KeyedAdapter<AnyTextAdapter>> = {
|
|
143
|
+
default: keyedAdapter('openrouter', (key): AnyTextAdapter =>
|
|
144
|
+
createOpenRouterText(DEFAULT_MODEL as never, key, {
|
|
145
|
+
appTitle: 'AllBlue',
|
|
146
|
+
}) as unknown as AnyTextAdapter,
|
|
147
|
+
),
|
|
148
|
+
}
|
|
149
|
+
const configs = await prisma.aiProviderConfig.findMany({
|
|
150
|
+
where: { enabled: true, apiKey: { not: null } },
|
|
151
|
+
select: { providerId: true, models: true, baseUrl: true },
|
|
152
|
+
})
|
|
153
|
+
for (const cfg of configs) {
|
|
154
|
+
const provider = SEED_AI_PROVIDERS.find((p) => p.providerId === cfg.providerId)
|
|
155
|
+
// 无种子元数据的 providerId(未来自定义服务商)跳过——adapterKind/baseUrl 无法判定
|
|
156
|
+
if (!provider) continue
|
|
157
|
+
const modelIds = Array.isArray(cfg.models)
|
|
158
|
+
? (cfg.models as unknown[]).filter((m): m is string => typeof m === 'string')
|
|
159
|
+
: []
|
|
160
|
+
for (const modelId of modelIds) {
|
|
161
|
+
const factory = keyedAdapterFactory(provider, modelId, cfg.baseUrl)
|
|
162
|
+
if (!factory) continue
|
|
163
|
+
if (!(modelId in catalog)) catalog[modelId] = factory
|
|
164
|
+
const alias = `${cfg.providerId}/${modelId}`
|
|
165
|
+
if (!(alias in catalog)) catalog[alias] = factory
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return catalog
|
|
169
|
+
}
|
|
@@ -58,7 +58,7 @@ export async function applyHarnessPermissionMode(
|
|
|
58
58
|
const mode = sandboxPolicyToPermissionMode(policy)
|
|
59
59
|
const { getHarnessHost } = await import('@/server/harness/host.server')
|
|
60
60
|
const { allblueHarness } = await import('@/server/harness/define.server')
|
|
61
|
-
const host = getHarnessHost()
|
|
61
|
+
const host = await getHarnessHost()
|
|
62
62
|
const session = await host.open(allblueHarness, { threadId, user })
|
|
63
63
|
try {
|
|
64
64
|
await session.setPluginSetting({ key: 'mode', value: mode, user })
|
|
@@ -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
|
|
|
@@ -270,7 +274,7 @@ export const deleteConversationFn = createServerFn({ method: "POST" })
|
|
|
270
274
|
const { isHarnessHostEnabled } = await import("@/server/harness/gate.server")
|
|
271
275
|
if (isHarnessHostEnabled()) {
|
|
272
276
|
const { getHarnessHost } = await import("@/server/harness/host.server")
|
|
273
|
-
await getHarnessHost().sessions.delete({
|
|
277
|
+
await (await getHarnessHost()).sessions.delete({
|
|
274
278
|
threadId: data.id,
|
|
275
279
|
user: { id: context.user.id },
|
|
276
280
|
})
|
|
@@ -587,6 +587,54 @@ export const createCustomProviderFn = createServerFn({ method: "POST" })
|
|
|
587
587
|
invalidateAiConfigCache(userId);
|
|
588
588
|
}
|
|
589
589
|
|
|
590
|
+
// harness host/harness 定义成对重建:模型目录按用户配置动态派生(刷新模型/
|
|
591
|
+
// 自定义 id),目录变更后旧 host 的目录已过期(真机验收:商汤种子 id 全 404)。
|
|
592
|
+
try {
|
|
593
|
+
const { isHarnessHostEnabled } = await import("@/server/harness/gate.server")
|
|
594
|
+
if (isHarnessHostEnabled()) {
|
|
595
|
+
const { closeHarnessHost } = await import("@/server/harness/host.server")
|
|
596
|
+
await closeHarnessHost()
|
|
597
|
+
}
|
|
598
|
+
} catch (error) {
|
|
599
|
+
console.warn("[providers] harness host 重建触发失败(下次请求自然重建):", error instanceof Error ? error.message : error)
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// harness host/harness 定义成对重建:模型目录按用户配置动态派生(刷新模型/
|
|
603
|
+
// 自定义 id),目录变更后旧 host 的目录已过期(真机验收:商汤种子 id 全 404)。
|
|
604
|
+
try {
|
|
605
|
+
const { isHarnessHostEnabled } = await import("@/server/harness/gate.server")
|
|
606
|
+
if (isHarnessHostEnabled()) {
|
|
607
|
+
const { closeHarnessHost } = await import("@/server/harness/host.server")
|
|
608
|
+
await closeHarnessHost()
|
|
609
|
+
}
|
|
610
|
+
} catch (error) {
|
|
611
|
+
console.warn("[providers] harness host 重建触发失败(下次请求自然重建):", error instanceof Error ? error.message : error)
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// harness host/harness 定义成对重建:模型目录按用户配置动态派生(刷新模型/
|
|
615
|
+
// 自定义 id),目录变更后旧 host 的目录已过期(真机验收:商汤种子 id 全 404)。
|
|
616
|
+
try {
|
|
617
|
+
const { isHarnessHostEnabled } = await import("@/server/harness/gate.server")
|
|
618
|
+
if (isHarnessHostEnabled()) {
|
|
619
|
+
const { closeHarnessHost } = await import("@/server/harness/host.server")
|
|
620
|
+
await closeHarnessHost()
|
|
621
|
+
}
|
|
622
|
+
} catch (error) {
|
|
623
|
+
console.warn("[providers] harness host 重建触发失败(下次请求自然重建):", error instanceof Error ? error.message : error)
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// harness host/harness 定义成对重建:模型目录按用户配置动态派生(刷新模型/
|
|
627
|
+
// 自定义 id),目录变更后旧 host 的目录已过期(真机验收:商汤种子 id 全 404)。
|
|
628
|
+
try {
|
|
629
|
+
const { isHarnessHostEnabled } = await import("@/server/harness/gate.server")
|
|
630
|
+
if (isHarnessHostEnabled()) {
|
|
631
|
+
const { closeHarnessHost } = await import("@/server/harness/host.server")
|
|
632
|
+
await closeHarnessHost()
|
|
633
|
+
}
|
|
634
|
+
} catch (error) {
|
|
635
|
+
console.warn("[providers] harness host 重建触发失败(下次请求自然重建):", error instanceof Error ? error.message : error)
|
|
636
|
+
}
|
|
637
|
+
|
|
590
638
|
return {
|
|
591
639
|
success: true,
|
|
592
640
|
providerId,
|
|
@@ -58,7 +58,7 @@ export const forkHarnessThreadFn = createServerFn({ method: "POST" })
|
|
|
58
58
|
}
|
|
59
59
|
const { getHarnessHost } = await import("@/server/harness/host.server")
|
|
60
60
|
const { allblueHarness } = await import("@/server/harness/define.server")
|
|
61
|
-
const host = getHarnessHost()
|
|
61
|
+
const host = await getHarnessHost()
|
|
62
62
|
const newThreadId = crypto.randomUUID()
|
|
63
63
|
await host.fork(allblueHarness, {
|
|
64
64
|
threadId: data.threadId,
|