@allbluecn/web-app 0.27.18 → 0.27.20

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.18",
3
+ "version": "0.27.20",
4
4
  "license": "AGPL-3.0-or-later",
5
5
  "type": "module",
6
6
  "files": [
@@ -10,8 +10,14 @@ vi.mock('@/lib/auth/auth-client', () => ({
10
10
  useSession: vi.fn(),
11
11
  }))
12
12
 
13
+ // 桌面运行时判定(Bug#2:桌面未登录 session=null 时 Pro 功能需 fail-closed)
14
+ vi.mock('@/lib/desktop-env', () => ({
15
+ isDesktopClient: vi.fn(() => false),
16
+ }))
17
+
13
18
  import { useSubscription } from '../subscription-provider'
14
19
  import { useSession } from '@/lib/auth/auth-client'
20
+ import { isDesktopClient } from '@/lib/desktop-env'
15
21
 
16
22
  const mockUseSubscription = useSubscription as ReturnType<typeof vi.fn>
17
23
  const mockUseSession = useSession as ReturnType<typeof vi.fn>
@@ -97,4 +103,40 @@ describe('useFeature', () => {
97
103
  const { result } = renderHook(() => useFeature('hostedAi'))
98
104
  expect(result.current.enabled).toBe(false)
99
105
  })
106
+
107
+ // Bug#2:桌面真机未登录(session=null)时 Pro 功能泄漏——沙箱档等 Pro 入口
108
+ // 因 OSS_BASE_FEATURES 白名单被判 enabled。桌面未登录与 guest 同为本机匿名态,
109
+ // 必须 fail-closed 返回 requiresLogin。
110
+ it('桌面未登录(session=null)→ requiresLogin(Pro 功能 fail-closed)', () => {
111
+ vi.mocked(isDesktopClient).mockReturnValue(true)
112
+ mockUseSession.mockReturnValue({ data: null })
113
+ mockUseSubscription.mockReturnValue({
114
+ planName: 'open-source',
115
+ // sandboxExecution 在 OSS_BASE_FEATURES 内 → features 为 true,
116
+ // 若不在桌面未登录分支拦截就会泄漏为 enabled
117
+ features: { sandboxExecution: true },
118
+ unavailable: [],
119
+ loading: false,
120
+ })
121
+
122
+ const { result } = renderHook(() => useFeature('sandboxExecution'))
123
+ expect(result.current.enabled).toBe(false)
124
+ expect(result.current.requiresLogin).toBe(true)
125
+ })
126
+
127
+ // 云/web 未登录不收敛(营销态可展示 Pro 入口引导注册),仅桌面壳内 fail-closed
128
+ it('云/web 未登录(session=null,非桌面)→ 不受桌面分支影响', () => {
129
+ vi.mocked(isDesktopClient).mockReturnValue(false)
130
+ mockUseSession.mockReturnValue({ data: null })
131
+ mockUseSubscription.mockReturnValue({
132
+ planName: 'open-source',
133
+ features: { sandboxExecution: true },
134
+ unavailable: [],
135
+ loading: false,
136
+ })
137
+
138
+ const { result } = renderHook(() => useFeature('sandboxExecution'))
139
+ expect(result.current.enabled).toBe(true)
140
+ expect(result.current.requiresLogin).toBeUndefined()
141
+ })
100
142
  })
@@ -1,5 +1,6 @@
1
1
  import { useSubscription } from './subscription-provider'
2
2
  import { useSession } from '@/lib/auth/auth-client'
3
+ import { isDesktopClient } from '@/lib/desktop-env'
3
4
  import { type FeatureKey } from '@allbluecn/kernel'
4
5
 
5
6
  // 桌面访客会话固定 userId(服务端唯一来源 src/server/desktop-guest.ts 的
@@ -27,6 +28,14 @@ export function useFeature(feature: FeatureKey): FeatureState {
27
28
  return { enabled: false, loading: false, requiresLogin: true }
28
29
  }
29
30
 
31
+ // 桌面未登录(session 仍为 null,尚未回落 guest):与 guest 同为「本机匿名」态,
32
+ // Pro 功能必须 fail-closed,否则 OSS_BASE_FEATURES 白名单会让沙箱档等 Pro 入口
33
+ // 在登录前泄漏(真机验收 Bug#2)。桌面 guest 一旦回落,走上面 isGuest 分支同口径。
34
+ // 云/web 未登录不在此列(营销态可展示 Pro 入口引导注册),仅桌面壳内收敛。
35
+ if (!session && isDesktopClient()) {
36
+ return { enabled: false, loading: false, requiresLogin: true }
37
+ }
38
+
30
39
  return {
31
40
  enabled: features[feature] === true,
32
41
  loading,
@@ -19,6 +19,7 @@
19
19
  import { useState, useRef, useEffect, useCallback } from "react"
20
20
  import { toast } from "@/components/ui/toast"
21
21
  import type { Editor } from "@tiptap/core"
22
+ import type { MediaRecord } from "@tanstack/ai-harness/client"
22
23
  import { decideSubmit, type BusyAction } from "./submit-machine"
23
24
  import { resolveTakeover, type ComposerTakeover } from "./takeover"
24
25
  import { useAttachments } from "./attachments/use-attachments"
@@ -142,17 +143,29 @@ export interface HarnessComposerProps {
142
143
  whenBusy?: "queue" | "interrupt"
143
144
  knowledgeBaseIds?: string[]
144
145
  /**
145
- * 就绪附件的引用列表(T6):只带 blobId/mimeType/fileName,wire 组装
146
+ * 旧链就绪附件的引用列表(T6):只带 blobId/mimeType/fileName,wire 组装
146
147
  * (url source + metadata.blobRef)在 workbench-page.handleSend 完成,
147
148
  * harnessBlobUrl 的单一来源留在 lib/harness/blob-url.ts。
148
149
  */
149
150
  attachments?: Array<{ blobId: string; mimeType: string; fileName: string }>
151
+ /**
152
+ * harness 路径就绪附件(T2.11 ④):putMedia 得到的 MediaRecord,经
153
+ * workbench handleSend → adapter → view.send(text, records) 以 harness-media:
154
+ * 引用发送。与 attachments(旧链 blobRef)二选一(D13,按 putMedia 是否传入)。
155
+ */
156
+ harnessAttachments?: MediaRecord[]
150
157
  /** handoff 板块上下文透传(服务端注入系统提示词用) */
151
158
  board?: string
152
159
  entityId?: string
153
160
  }
154
161
  ) => void
155
162
  onStop: () => void
163
+ /**
164
+ * harness 附件上传器(T2.11 ④):传入 harness client.putMedia(经 workbench chat 面
165
+ * 透传),附件改走 putMedia 得 MediaRecord(消息 part 用 harness-media: 引用)。
166
+ * **不传则走旧链** blobRef(web/SaaS 至 Phase 4 唯一路径,D13 按部署目标二选一)。
167
+ */
168
+ putMedia?: (file: { body: Blob; mimeType: string; name: string }) => Promise<MediaRecord>
156
169
  messages: ReadonlyArray<{ id: string; role: string; parts: ReadonlyArray<{ type: string; content?: unknown }> }>
157
170
  scrollContainerRef?: React.RefObject<HTMLDivElement | null>
158
171
  model?: string
@@ -203,6 +216,7 @@ export function HarnessComposer({
203
216
  busyPreference,
204
217
  onSend,
205
218
  onStop,
219
+ putMedia,
206
220
  conversationRegionRef,
207
221
  messages,
208
222
  model,
@@ -256,7 +270,9 @@ export function HarnessComposer({
256
270
  }
257
271
  }
258
272
  }, [pendingPrefillEntity, pendingPrefillText, aiReady])
259
- const { attachments, addFiles, removeAttachment, clearAttachments, retryAttachment, hasPending } = useAttachments()
273
+ // 附件上传(T2.11 ④):传入 putMedia(harness 路径)则附件走 client.putMedia 得
274
+ // MediaRecord(消息 part 用 harness-media: 引用);不传(旧链)走 blobRef。D13 二选一。
275
+ const { attachments, addFiles, removeAttachment, clearAttachments, retryAttachment, hasPending } = useAttachments({ putMedia })
260
276
  const hasFailedAttachments = attachments.some((a) => a.status === "error")
261
277
  // T6 三入口之三:卡片级拖拽(dragenter/dragleave 计数器防子元素抖动,
262
278
  // 拖入时 ring 高亮;drop 收文件走同一 addFiles 引用管道)
@@ -340,17 +356,24 @@ export function HarnessComposer({
340
356
  ...new Set([...(knowledgeBaseIds ?? []), ...editorMentionKbIds]),
341
357
  ]
342
358
 
343
- // 附件引用式发送(T6):就绪附件只传 blobId/mimeType/fileName,wire 层
344
- // (workbench-page.handleSend)组 url source + metadata.blobRef。白名单
345
- // 全为位图,引用通道统一覆盖;未就绪附件已被 decideSubmit 拦在发送之前
359
+ // 附件引用式发送(T6 / T2.11 ④):按上传通道二选一(D13)。
360
+ // - 旧链(blobId,web/SaaS):只传 blobId/mimeType/fileName,wire 层
361
+ // (workbench-page.handleSend)组 url source + metadata.blobRef。
362
+ // - harness(mediaRecord,putMedia):传 MediaRecord,workbench handleSend →
363
+ // adapter → view.send(text, records) 以 harness-media: 引用发送。
364
+ // 白名单全为位图,引用通道统一覆盖;未就绪附件已被 decideSubmit 拦在发送之前
346
365
  const readyAttachments = attachments
347
366
  .filter((a) => a.status === "ready" && a.blobId)
348
367
  .map((a) => ({ blobId: a.blobId as string, mimeType: a.file.type, fileName: a.file.name }))
368
+ const readyMediaRecords = attachments
369
+ .filter((a) => a.status === "ready" && a.mediaRecord)
370
+ .map((a) => a.mediaRecord as MediaRecord)
349
371
 
350
372
  onSend(text, {
351
373
  whenBusy,
352
374
  knowledgeBaseIds: mergedKbIds.length ? mergedKbIds : undefined,
353
375
  attachments: readyAttachments.length ? readyAttachments : undefined,
376
+ harnessAttachments: readyMediaRecords.length ? readyMediaRecords : undefined,
354
377
  // 透传板块上下文(如果存在),服务端可据此注入系统提示词
355
378
  ...(handoffContext ? { board: handoffContext.board, entityId: handoffContext.entityId } : {}),
356
379
  })
@@ -214,6 +214,7 @@ function WorkbenchCenter() {
214
214
  onBusyPreferenceChange={body.setBusyPreference}
215
215
  onSend={body.handleSend}
216
216
  onStop={body.handleStop}
217
+ putMedia={chat.putMedia}
217
218
  conversationRegionRef={conversationRegionRef}
218
219
  messages={chat.messages}
219
220
  model={body.effectiveModel}
@@ -41,6 +41,7 @@ vi.mock('@/components/harness/harness-chat-slots', () => ({
41
41
 
42
42
  import { useHarnessChatAdapter } from '../use-harness-chat-adapter'
43
43
  import type { HarnessSession } from '../use-harness-session'
44
+ import type { MediaRecord } from '@tanstack/ai-harness/client'
44
45
 
45
46
  /** 构造最小 harness 会话假体(HarnessSession 形状)。 */
46
47
  function makeFakeSession(overrides: Partial<HarnessSession> = {}): HarnessSession {
@@ -160,6 +161,51 @@ describe('useHarnessChatAdapter(T2.8 适配层)', () => {
160
161
  expect(send).toHaveBeenCalledWith('ab')
161
162
  })
162
163
 
164
+ it('sendMessage:harnessAttachments → view.send(text, records)(T2.11 ④ putMedia 引用)', () => {
165
+ const send = vi.fn(async () => {})
166
+ const record = {
167
+ id: 'm1',
168
+ threadId: 't1',
169
+ kind: 'image',
170
+ mimeType: 'image/png',
171
+ name: 'cat.png',
172
+ size: 3,
173
+ createdAt: 1,
174
+ source: 'user',
175
+ } as MediaRecord
176
+ const { result } = renderHook(() =>
177
+ useHarnessChatAdapter(makeFakeSession({ send })),
178
+ )
179
+ act(() => {
180
+ result.current.sendMessage('look', { harnessAttachments: [record] })
181
+ })
182
+ // 附件不进文本 content,改经 view.send 第二参(MediaRecord[]),由 view 内部
183
+ // mediaPart(record) 组 harness-media: 引用——组件层契约即「records 原样透传」。
184
+ expect(send).toHaveBeenCalledWith('look', [record])
185
+ })
186
+
187
+ it('sendMessage:无 harnessAttachments → view.send(text) 纯文本(旧链 blobRef 路径不串味)', () => {
188
+ const send = vi.fn(async () => {})
189
+ const { result } = renderHook(() =>
190
+ useHarnessChatAdapter(makeFakeSession({ send })),
191
+ )
192
+ act(() => {
193
+ result.current.sendMessage('plain', { whenBusy: 'queue' })
194
+ })
195
+ expect(send).toHaveBeenCalledWith('plain')
196
+ })
197
+
198
+ it('putMedia 透传:adapter 暴露 session.putMedia(T2.11 ④ composer 上传器)', async () => {
199
+ const putMedia = vi.fn(async () => ({}) as MediaRecord)
200
+ const { result } = renderHook(() =>
201
+ useHarnessChatAdapter(makeFakeSession({ putMedia })),
202
+ )
203
+ expect(result.current.putMedia).toBe(putMedia)
204
+ const file = { body: new Blob(['x']), mimeType: 'image/png', name: 'cat.png' }
205
+ await result.current.putMedia?.(file)
206
+ expect(putMedia).toHaveBeenCalledWith(file)
207
+ })
208
+
163
209
  it('citations 重建:web_search 工具结果 → setLatestCitations', () => {
164
210
  const viewMessages: ViewMessage[] = [
165
211
  {
@@ -0,0 +1,80 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+
5
+ // T2.11 ④ putMedia 接线单测:useHarnessSession 暴露的 putMedia 必须转发到
6
+ // harness client.putMedia(composer 的 useAttachments 上传器据此得 MediaRecord)。
7
+ // mock client/view,不依赖真实 host。
8
+
9
+ import { describe, it, expect, vi, beforeEach } from 'vitest'
10
+ import { renderHook, act } from '@testing-library/react'
11
+ import { createStore } from '@tanstack/store'
12
+
13
+ const putMediaMock = vi.fn()
14
+ const sendViewMock = vi.fn()
15
+
16
+ vi.mock('@tanstack/ai-harness/client', () => ({
17
+ createHarnessClient: () => ({
18
+ putMedia: putMediaMock,
19
+ }),
20
+ }))
21
+
22
+ vi.mock('@tanstack/ai-harness/view', () => ({
23
+ createSessionView: () => viewMock,
24
+ }))
25
+
26
+ // view.store 用真 TanStack Store(useStore 订阅切片),其余动作给 mock。
27
+ const viewMock = {
28
+ store: createStore({
29
+ messages: [],
30
+ status: 'idle',
31
+ connection: 'open',
32
+ approvals: [],
33
+ interrupts: [],
34
+ questions: [],
35
+ clientTools: [],
36
+ queuedTurns: 0,
37
+ waitingInputs: [],
38
+ }),
39
+ send: sendViewMock,
40
+ approve: vi.fn(),
41
+ reject: vi.fn(),
42
+ cancel: vi.fn(),
43
+ }
44
+
45
+ import { useHarnessSession } from '../use-harness-session'
46
+
47
+ beforeEach(() => {
48
+ putMediaMock.mockReset()
49
+ putMediaMock.mockResolvedValue({
50
+ id: 'm1',
51
+ threadId: 't1',
52
+ kind: 'image',
53
+ mimeType: 'image/png',
54
+ name: 'cat.png',
55
+ size: 3,
56
+ createdAt: 1,
57
+ source: 'user',
58
+ })
59
+ })
60
+
61
+ describe('useHarnessSession putMedia 接线(T2.11 ④)', () => {
62
+ it('暴露的 putMedia 转发到 client.putMedia,返回 MediaRecord', async () => {
63
+ const { result } = renderHook(() => useHarnessSession({ threadId: 't1' }))
64
+ expect(typeof result.current.putMedia).toBe('function')
65
+
66
+ const file = { body: new Blob(['x']), mimeType: 'image/png', name: 'cat.png' }
67
+ let record: unknown
68
+ await act(async () => {
69
+ record = await result.current.putMedia(file)
70
+ })
71
+
72
+ expect(putMediaMock).toHaveBeenCalledWith(file)
73
+ expect(record).toMatchObject({ id: 'm1', kind: 'image', name: 'cat.png' })
74
+ })
75
+
76
+ it('暴露 client 原始引用(title 写回订阅 hostEvents 用,T2.11 ②)', () => {
77
+ const { result } = renderHook(() => useHarnessSession({ threadId: 't1' }))
78
+ expect(result.current.client).toBeDefined()
79
+ })
80
+ })
@@ -0,0 +1,103 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+
5
+ // T2.11 ② title 写回单测:useHarnessTitleWriteBack 订阅 client.hostEvents(),
6
+ // 把当前线程的 title 变更(官方 title 插件写入 harness_sessions 后经 host 事件派发)
7
+ // 经 onTitle 上抛给调用方(工作台 connection 负责 updateConversationFn 写 ChatThread.title)。
8
+ // mock client,不依赖真实 host。
9
+
10
+ import { describe, it, expect, vi } from 'vitest'
11
+ import { renderHook, waitFor } from '@testing-library/react'
12
+ import type { HostEvent } from '@tanstack/ai-harness/client'
13
+ import { useHarnessTitleWriteBack } from '../use-harness-title-writeback'
14
+
15
+ /** 构造 host 事件假体(只喂 type==='session' 的 HostSessionEvent)。 */
16
+ function sessionEvent(threadId: string, title: string): HostEvent {
17
+ return {
18
+ type: 'session',
19
+ threadId,
20
+ entry: { tenantId: 'tenant', threadId, title, revision: 1 },
21
+ } as unknown as HostEvent
22
+ }
23
+
24
+ /** 把给定事件序列包成一个 hostEvents 异步可迭代(消费完即结束)。 */
25
+ function makeClient(events: HostEvent[]): {
26
+ hostEvents: () => AsyncIterable<HostEvent>
27
+ } {
28
+ return {
29
+ hostEvents: () =>
30
+ (async function* () {
31
+ for (const e of events) yield e
32
+ })(),
33
+ }
34
+ }
35
+
36
+ describe('useHarnessTitleWriteBack(T2.11 ② title 写回)', () => {
37
+ it('线程标题变更 → onTitle 收到新标题', async () => {
38
+ const onTitle = vi.fn()
39
+ const client = makeClient([sessionEvent('t1', '旅行计划')])
40
+ renderHook(() =>
41
+ useHarnessTitleWriteBack({ client, threadId: 't1', onTitle }),
42
+ )
43
+ await waitFor(() => expect(onTitle).toHaveBeenCalledWith('旅行计划'))
44
+ })
45
+
46
+ it('其他线程的标题事件不上抛(threadId 不匹配)', async () => {
47
+ const onTitle = vi.fn()
48
+ const client = makeClient([sessionEvent('other', '别人的会话')])
49
+ renderHook(() =>
50
+ useHarnessTitleWriteBack({ client, threadId: 't1', onTitle }),
51
+ )
52
+ // 事件流已消费完(无匹配),onTitle 不应被调用
53
+ await waitFor(() => expect(onTitle).not.toHaveBeenCalled())
54
+ })
55
+
56
+ it('非 session 事件(status 等)不上抛', async () => {
57
+ const onTitle = vi.fn()
58
+ const client = makeClient([
59
+ { type: 'status', threadId: 't1', status: 'running', at: 1 } as unknown as HostEvent,
60
+ sessionEvent('t1', '新标题'),
61
+ ])
62
+ renderHook(() =>
63
+ useHarnessTitleWriteBack({ client, threadId: 't1', onTitle }),
64
+ )
65
+ await waitFor(() => expect(onTitle).toHaveBeenCalledWith('新标题'))
66
+ expect(onTitle).toHaveBeenCalledTimes(1)
67
+ })
68
+
69
+ it('同一标题只上抛一次(host 重连重放已写回标题不重复写 ChatThread)', async () => {
70
+ const onTitle = vi.fn()
71
+ const client = makeClient([
72
+ sessionEvent('t1', '同一标题'),
73
+ sessionEvent('t1', '同一标题'),
74
+ ])
75
+ renderHook(() =>
76
+ useHarnessTitleWriteBack({ client, threadId: 't1', onTitle }),
77
+ )
78
+ await waitFor(() => expect(onTitle).toHaveBeenCalledWith('同一标题'))
79
+ await waitFor(() => expect(onTitle).toHaveBeenCalledTimes(1))
80
+ })
81
+
82
+ it('空标题 / 非字符串标题不上抛', async () => {
83
+ const onTitle = vi.fn()
84
+ const client = makeClient([
85
+ sessionEvent('t1', ''),
86
+ { type: 'session', threadId: 't1', entry: { title: null } } as unknown as HostEvent,
87
+ ])
88
+ renderHook(() =>
89
+ useHarnessTitleWriteBack({ client, threadId: 't1', onTitle }),
90
+ )
91
+ await waitFor(() => expect(onTitle).not.toHaveBeenCalled())
92
+ })
93
+
94
+ it('enabled=false 不订阅', async () => {
95
+ const onTitle = vi.fn()
96
+ const hostEvents = vi.fn()
97
+ const client = { hostEvents }
98
+ renderHook(() =>
99
+ useHarnessTitleWriteBack({ client, threadId: 't1', enabled: false, onTitle }),
100
+ )
101
+ await waitFor(() => expect(hostEvents).not.toHaveBeenCalled())
102
+ })
103
+ })
@@ -29,6 +29,7 @@ import type {
29
29
  ViewMessage,
30
30
  ViewPart,
31
31
  } from '@tanstack/ai-harness/view'
32
+ import type { MediaRecord } from '@tanstack/ai-harness/client'
32
33
  import { HarnessSessionAppChat } from './harness-session-appchat'
33
34
  import type { HarnessSession } from './use-harness-session'
34
35
  import { setLatestCitations } from '@/components/harness/harness-chat-slots'
@@ -64,12 +65,25 @@ export interface HarnessChatLike {
64
65
  interrupts: TakeoverInterruptLike[]
65
66
  sendMessage: (
66
67
  content: string | { content: ReadonlyArray<{ type: string; text?: string }> },
67
- options?: { whenBusy?: 'queue' | 'interrupt'; body?: unknown },
68
+ options?: {
69
+ whenBusy?: 'queue' | 'interrupt'
70
+ body?: unknown
71
+ /**
72
+ * harness 附件(T2.11 ④):putMedia 上传得到的 MediaRecord,经 view.send(text,
73
+ * records) 以 harness-media: 引用发送。旧链不传(走 blobRef content parts)。
74
+ */
75
+ harnessAttachments?: ReadonlyArray<MediaRecord>
76
+ },
68
77
  ) => void
69
78
  stop: () => void
70
79
  clear: () => void
71
80
  reload: () => void
72
81
  AppChat: ComponentType<Record<string, never>>
82
+ /**
83
+ * 附件上传器(T2.11 ④):harness client.putMedia,透传给 composer 的
84
+ * useAttachments。旧链无此能力(undefined → useAttachments 走 blobRef)。
85
+ */
86
+ putMedia?: (file: { body: Blob; mimeType: string; name: string }) => Promise<MediaRecord>
73
87
  }
74
88
 
75
89
  /** 把单个 ViewPart 压成 UIMessage part 投影(type + content)。 */
@@ -215,7 +229,7 @@ function extractResults(raw: unknown): Array<{ title: string; url: string }> {
215
229
  * 调用方经 options.harnessAttachments 透传,见 tie-up 3)。
216
230
  */
217
231
  export function useHarnessChatAdapter(session: HarnessSession): HarnessChatLike {
218
- const { view, messages: viewMessages, status, connection, approvals, interrupts: viewInterrupts, questions, send, cancel } = session
232
+ const { view, messages: viewMessages, status, connection, approvals, interrupts: viewInterrupts, questions, send, cancel, putMedia } = session
219
233
 
220
234
  const [error, setError] = useState<Error | null>(null)
221
235
 
@@ -254,14 +268,21 @@ export function useHarnessChatAdapter(session: HarnessSession): HarnessChatLike
254
268
 
255
269
  const sendMessage = useCallback<HarnessChatLike['sendMessage']>(
256
270
  (content, options) => {
257
- void options
258
271
  const text = typeof content === 'string'
259
272
  ? content
260
273
  : (content.content ?? [])
261
274
  .map((p) => (typeof p.text === 'string' ? p.text : ''))
262
275
  .join('')
263
276
  setError(null)
264
- void send(text)
277
+ // harness 附件(T2.11 ④):putMedia 得到的 MediaRecord 经 view.send(text, records)
278
+ // 发送(view 内部 mediaPart(record) 组 harness-media: 引用,字节留在服务端 media store)。
279
+ // 无附件走纯文本,与旧链 blobRef content parts 互斥(D13 二选一)。
280
+ const records = options?.harnessAttachments
281
+ if (records && records.length > 0) {
282
+ void send(text, records)
283
+ } else {
284
+ void send(text)
285
+ }
265
286
  },
266
287
  [send],
267
288
  )
@@ -295,5 +316,6 @@ export function useHarnessChatAdapter(session: HarnessSession): HarnessChatLike
295
316
  clear,
296
317
  reload,
297
318
  AppChat,
319
+ putMedia,
298
320
  }
299
321
  }
@@ -45,9 +45,11 @@ export interface UseHarnessSessionOptions {
45
45
  export function useHarnessSession({ threadId }: UseHarnessSessionOptions) {
46
46
  // client + view 稳定引用:threadId 变化才重建(view 持有 SSE 连接与 store)。
47
47
  // createSessionView 自身处理重连/gap/媒体 URL 刷新,无需在此重试。
48
- const view = useMemo(() => {
48
+ // client 一并暴露:putMedia(附件上传,T2.11 ④)与 hostEvents(title 写回,
49
+ // T2.11 ②)都在 client 上,view 不转发这两个能力。
50
+ const { client, view } = useMemo(() => {
49
51
  const client = createHarnessClient<AnyHarness>({ url: '/api/harness', threadId })
50
- return createSessionView(client)
52
+ return { client, view: createSessionView(client) }
51
53
  }, [threadId])
52
54
 
53
55
  // live 状态切片:useStore 订阅 view.store(TanStack Store),按字段选择避免全量重渲染
@@ -74,9 +76,22 @@ export function useHarnessSession({ threadId }: UseHarnessSessionOptions) {
74
76
  }, [view])
75
77
  const cancel = useCallback(() => view.cancel(), [view])
76
78
 
79
+ // 附件上传器(T2.11 ④):harness client.putMedia 暴露给 composer 的 useAttachments。
80
+ // 用 client.putMedia(接受 Blob)而非 view.putMedia(MediaBody 仅 ArrayBuffer|Uint8Array,
81
+ // 见 view/index.d.ts:101),与 use-attachments 的 File/Blob 通道类型对齐。
82
+ // 签名与 useAttachments 的 putMedia 上传器一致:{ body: Blob; mimeType; name } → MediaRecord。
83
+ const putMedia = useCallback(
84
+ (file: { body: Blob; mimeType: string; name: string }) => client.putMedia(file),
85
+ [client],
86
+ )
87
+
77
88
  return {
78
89
  /** view 原始引用(供 client-tools-dispatcher 订阅 clientTools、queue-bar 读连接态) */
79
90
  view,
91
+ /** harness client 原始引用(title 写回订阅 hostEvents、后续 sessions.* 编排用,T2.11 ②) */
92
+ client,
93
+ /** 附件上传器(composer useAttachments 消费;harness 路径专用,旧链不传) */
94
+ putMedia,
80
95
  messages,
81
96
  status,
82
97
  connection,
@@ -0,0 +1,72 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // harness title 写回 ChatThread(设计 §6 / T2.7 / T2.11 ②)。
6
+ //
7
+ // 官方 title 插件(first-party/title)在会话首个回合后用 adapter 生成短标题,写入
8
+ // session index entry(harness_sessions.title)。侧栏单一真源是 ChatThread,故本 hook
9
+ // 订阅 client.hostEvents(),过滤 type==='session' 的 HostSessionEvent(rename 会派发,
10
+ // host.d.ts:566),把新标题经 onTitle 回调上抛给调用方(工作台 connection 负责
11
+ // updateConversationFn 写 ChatThread.title + 更新侧栏 conversations 状态)。
12
+ //
13
+ // 纯客户端:只订阅 harness client 的 host 事件流,不直接碰 serverFn/DB——单一职责,
14
+ // 可用 mock client(hostEvents 产出假 HostSessionEvent)单测「标题变更 → onTitle」。
15
+
16
+ import { useEffect, useRef } from 'react'
17
+ import type { HostEvent } from '@tanstack/ai-harness/client'
18
+
19
+ /** 最小 client 形状(只依赖 hostEvents;用结构类型避免拖入 HarnessClient 泛型)。 */
20
+ export interface TitleWriteBackClient {
21
+ hostEvents: (options?: { signal?: AbortSignal }) => AsyncIterable<HostEvent>
22
+ }
23
+
24
+ /**
25
+ * 订阅 harness host 事件流,把当前线程的标题变更经 onTitle 上抛(T2.11 ②)。
26
+ *
27
+ * - 只认 `type === 'session'` 且 `threadId` 匹配的事件;标题为非空 string 才上抛。
28
+ * - 同一标题只上抛一次(lastTitleRef 去重),避免 host 重连重放已写回的标题。
29
+ * - onTitle 走 ref,保证 effect 仅在 client/threadId/enabled 变化时重订阅(回调身份
30
+ * 抖动不重置 SSE 流)。
31
+ * - 卸载 / 切线程时 abort,关闭 host SSE 流。
32
+ */
33
+ export function useHarnessTitleWriteBack(options: {
34
+ client: TitleWriteBackClient | null | undefined
35
+ threadId: string | null | undefined
36
+ enabled?: boolean
37
+ onTitle: (title: string) => void
38
+ }): void {
39
+ const { client, threadId, enabled = true, onTitle } = options
40
+ const onTitleRef = useRef(onTitle)
41
+ onTitleRef.current = onTitle
42
+ const lastTitleRef = useRef<string | null>(null)
43
+
44
+ useEffect(() => {
45
+ if (!enabled || !client || !threadId) return
46
+ const controller = new AbortController()
47
+ let cancelled = false
48
+ // 重置去重锚:切线程时上一线程的标题不再抑制新线程的首个标题
49
+ lastTitleRef.current = null
50
+ void (async () => {
51
+ try {
52
+ for await (const event of client.hostEvents({ signal: controller.signal })) {
53
+ if (cancelled) break
54
+ if (event.type !== 'session') continue
55
+ if (event.threadId !== threadId) continue
56
+ const title = event.entry?.title
57
+ if (typeof title !== 'string' || title.length === 0) continue
58
+ if (title === lastTitleRef.current) continue
59
+ lastTitleRef.current = title
60
+ onTitleRef.current(title)
61
+ }
62
+ } catch {
63
+ // 流结束 / abort / 网络断开:title 写回尽力而为,静默(与 host SSE 重连由
64
+ // client 自管一致;此处不重连,下次 threadId/client 变化或重挂载再订阅)。
65
+ }
66
+ })()
67
+ return () => {
68
+ cancelled = true
69
+ controller.abort()
70
+ }
71
+ }, [client, threadId, enabled])
72
+ }
@@ -33,6 +33,8 @@ import { useEffect, useRef } from 'react'
33
33
  import { useHarnessChat } from '@/components/harness/chat-ui'
34
34
  import { useHarnessSession } from '@/components/harness/session/use-harness-session'
35
35
  import { useHarnessChatAdapter } from '@/components/harness/session/use-harness-chat-adapter'
36
+ import { useHarnessTitleWriteBack } from '@/components/harness/session/use-harness-title-writeback'
37
+ import { updateConversationFn } from '@/server/serverFns/chat/conversations'
36
38
  import { isHarnessClientEnabled } from '@/lib/harness-gate'
37
39
  import {
38
40
  attachLatestCitationsToMessageId,
@@ -121,13 +123,27 @@ function LegacyConnection({ children }: { children: React.ReactNode }) {
121
123
 
122
124
  /** 门控开(桌面 / dev 开关):harness 会话经适配层。 */
123
125
  function HarnessConnection({ children }: { children: React.ReactNode }) {
124
- const { threadId, chatRef, pendingSend, setPendingSend, activeConversationId, setRetryDismissed } = useWorkbenchBody()
126
+ const { threadId, chatRef, pendingSend, setPendingSend, activeConversationId, setRetryDismissed, setConversations } = useWorkbenchBody()
125
127
 
126
128
  const session = useHarnessSession({ threadId })
127
129
  const chat = useHarnessChatAdapter(session)
128
130
  const workbenchChat = toWorkbenchChat(chat)
129
131
  chatRef.current = workbenchChat
130
132
 
133
+ // title 写回 ChatThread(T2.11 ②):官方 title 插件生成标题写入 harness_sessions,
134
+ // 经 host 事件流(client.hostEvents)到达;侧栏单一真源是 ChatThread,故在此把标题
135
+ // 同步回 ChatThread(updateConversationFn)+ 就地更新侧栏 conversations 状态。
136
+ useHarnessTitleWriteBack({
137
+ client: session.client,
138
+ threadId,
139
+ onTitle: (title) => {
140
+ void updateConversationFn({ data: { id: threadId, title } }).catch(() => {})
141
+ setConversations((prev) =>
142
+ prev.map((c) => (c.id === threadId ? { ...c, title } : c)),
143
+ )
144
+ },
145
+ })
146
+
131
147
  // 切线程清 citations(harness 以服务端为真源,adapter.clear/reload 为 no-op)
132
148
  useEffect(() => {
133
149
  clearHarnessCitations()
@@ -61,6 +61,8 @@ import {
61
61
  deleteConversationFn,
62
62
  forkConversationFn,
63
63
  } from '@/server/serverFns/chat/conversations'
64
+ import { forkHarnessThreadFn } from '@/server/serverFns/harness/fork-thread'
65
+ import { isHarnessClientEnabled } from '@/lib/harness-gate'
64
66
  import { agentsQueryOptions } from '@/lib/queries/agents'
65
67
  import { useSelectedModel } from '@/lib/ai/use-selected-model'
66
68
  import { useSearchCapability } from '@/lib/ai/use-search-capability'
@@ -79,6 +81,7 @@ import { toastError } from '@/lib/toast-error'
79
81
  import type { BusyAction } from '@/components/harness/composer/submit-machine'
80
82
  import type { TakeoverInterruptLike } from '@/components/harness/composer/takeover'
81
83
  import type { MultimodalContent, SendMessageOptions } from '@tanstack/ai-client'
84
+ import type { MediaRecord } from '@tanstack/ai-harness/client'
82
85
  import type { AgentData } from '@/components/agents/agents-page'
83
86
 
84
87
  /** 本地 Agent 列表项(localAgentsQueryOptions)的最小形状,供默认选择 effect 用。 */
@@ -111,6 +114,11 @@ export interface WorkbenchChat {
111
114
  clear: () => void
112
115
  reload: () => void
113
116
  AppChat: React.ComponentType<Record<string, never>>
117
+ /**
118
+ * 附件上传器(T2.11 ④):仅 harness 路径有值(adapter 透传 client.putMedia),
119
+ * 旧链为 undefined → composer 的 useAttachments 走 blobRef 旧链。
120
+ */
121
+ putMedia?: (file: { body: Blob; mimeType: string; name: string }) => Promise<import('@tanstack/ai-harness/client').MediaRecord>
114
122
  }
115
123
 
116
124
  export interface HarnessInitialConversation {
@@ -142,8 +150,12 @@ export interface PendingThreadSend {
142
150
  sendOptions?: WorkbenchSendOptions
143
151
  }
144
152
 
145
- /** 发送 options:跟随旧 useHarnessChat.sendMessage 第二参(whenBusy + body)。 */
146
- export type WorkbenchSendOptions = SendMessageOptions
153
+ /** 发送 options:跟随旧 useHarnessChat.sendMessage 第二参(whenBusy + body)。
154
+ * harness 路径(T2.11 ④)附加 harnessAttachments:putMedia 得到的 MediaRecord,
155
+ * 经 adapter 透传 view.send(text, records)(harness-media: 引用),旧链不传。 */
156
+ export type WorkbenchSendOptions = SendMessageOptions & {
157
+ harnessAttachments?: MediaRecord[]
158
+ }
147
159
 
148
160
  /** 发送 content:跟随旧 useHarnessChat.sendMessage 首参(string | MultimodalContent)。 */
149
161
  export type WorkbenchSendContent = string | MultimodalContent
@@ -205,6 +217,7 @@ export interface WorkbenchBodyContextValue extends WorkbenchProps {
205
217
  whenBusy?: 'queue' | 'interrupt'
206
218
  knowledgeBaseIds?: string[]
207
219
  attachments?: AttachmentRef[]
220
+ harnessAttachments?: MediaRecord[]
208
221
  }
209
222
  }
210
223
  | undefined
@@ -320,6 +333,7 @@ export function WorkbenchProvider({
320
333
  whenBusy?: 'queue' | 'interrupt'
321
334
  knowledgeBaseIds?: string[]
322
335
  attachments?: AttachmentRef[]
336
+ harnessAttachments?: MediaRecord[]
323
337
  }
324
338
  }
325
339
  | undefined
@@ -662,7 +676,12 @@ export function WorkbenchProvider({
662
676
  async (id: string) => {
663
677
  let forked: Conversation
664
678
  try {
665
- forked = await forkConversationFn({ data: { threadId: id } })
679
+ // T2.11 ②:harness 路径 fork 走 host.fork(transcript 由 host 持有)+ 建
680
+ // ChatThread 行(侧栏可见);旧链走 forkConversationFn(全量复制 ChatMessage)。
681
+ // D13 按部署目标二选一。
682
+ forked = isHarnessClientEnabled()
683
+ ? await forkHarnessThreadFn({ data: { threadId: id } })
684
+ : await forkConversationFn({ data: { threadId: id } })
666
685
  } catch (e) {
667
686
  toastError(e, m.common_operationFailed())
668
687
  return
@@ -670,20 +689,21 @@ export function WorkbenchProvider({
670
689
  setConversations((prev) => [forked, ...prev])
671
690
  navigate({ to: '/harness/$threadId', params: { threadId: forked.id } })
672
691
  },
673
- [navigate],
692
+ [navigate, setConversations],
674
693
  )
675
694
 
676
695
  const handleSend = useCallback(
677
696
  async (
678
697
  val: string,
679
- opts?: { whenBusy?: 'queue' | 'interrupt'; knowledgeBaseIds?: string[]; attachments?: AttachmentRef[] },
698
+ opts?: { whenBusy?: 'queue' | 'interrupt'; knowledgeBaseIds?: string[]; attachments?: AttachmentRef[]; harnessAttachments?: MediaRecord[] },
680
699
  flags?: { isRetry?: boolean },
681
700
  ) => {
682
701
  if (engine === 'local' && !localCwd) {
683
702
  toastError(new Error(m.harness_localWorkspace_required()), m.common_operationFailed())
684
703
  return
685
704
  }
686
- if (engine === 'local' && opts?.attachments && opts.attachments.length > 0) {
705
+ const hasAttachments = (opts?.attachments?.length ?? 0) > 0 || (opts?.harnessAttachments?.length ?? 0) > 0
706
+ if (engine === 'local' && hasAttachments) {
687
707
  toastError(new Error(m.harness_engine_localNoAttachments()), m.common_operationFailed())
688
708
  return
689
709
  }
@@ -696,6 +716,7 @@ export function WorkbenchProvider({
696
716
  whenBusy: opts?.whenBusy,
697
717
  knowledgeBaseIds: opts?.knowledgeBaseIds,
698
718
  attachments: opts?.attachments,
719
+ harnessAttachments: opts?.harnessAttachments,
699
720
  },
700
721
  })
701
722
  }
@@ -709,11 +730,16 @@ export function WorkbenchProvider({
709
730
  : opts.knowledgeBaseIds
710
731
  ? { knowledgeBaseIds: opts.knowledgeBaseIds }
711
732
  : undefined,
733
+ // harness 附件(T2.11 ④):MediaRecord 经 adapter 透传 view.send;旧链 chat
734
+ // 的 sendMessage 不识别此字段(忽略),故对旧链无副作用(D13 二选一)。
735
+ ...(opts.harnessAttachments && opts.harnessAttachments.length > 0
736
+ ? { harnessAttachments: opts.harnessAttachments }
737
+ : {}),
712
738
  }
713
739
  : undefined
714
740
  const content: PendingThreadSend['content'] =
715
741
  opts?.attachments && opts.attachments.length > 0
716
- ? // 多模态消息(T6 引用式发送):文本 + 图片引用 parts——url source 经
742
+ ? // 多模态消息(T6 引用式发送,旧链 blobRef):文本 + 图片引用 parts——url source 经
717
743
  // harnessBlobUrl(发送与渲染共用同一路径),metadata.blobRef/fileName
718
744
  // 供服务端 attachment-deref 解引用(fileName 用于降级占位文案)。引用
719
745
  // 形态落库,重载后按引用渲染,wire 体积与图片大小无关。
@@ -727,7 +753,10 @@ export function WorkbenchProvider({
727
753
  })),
728
754
  ],
729
755
  }
730
- : val
756
+ : // harness 路径(putMedia):附件不进 content(避免相对 URL 被 harness 输入边界
757
+ // 以 media_url_not_allowed 拒收,设计 §5.10),改经 sendOptions.harnessAttachments
758
+ // → view.send(text, records)(harness-media: 引用)。
759
+ val
731
760
  if (!activeIdRef.current) {
732
761
  // 空态首条消息:先建会话拿真实 id(失败早退),再经 pendingSend 槽
733
762
  // 等 hook 以新 threadId 重建 client 后发送——直接 sendMessage 会把
@@ -112,7 +112,7 @@ export const SDK_GROUPS: SdkGroup[] = [
112
112
  "items": [
113
113
  {
114
114
  "name": "@allbluecn/web-app",
115
- "version": "v0.27.18",
115
+ "version": "v0.27.20",
116
116
  "lastUpdate": "Nov 9, 2026",
117
117
  "source": "apps/web/package.json",
118
118
  "docsUrl": "https://github.com/allbluecn/allblue"
@@ -40,44 +40,58 @@ async function handleHarnessRequest(request: Request): Promise<Response> {
40
40
  if (!isHarnessHostEnabled()) return notFound()
41
41
 
42
42
  // server-only 薄适配层经 server.handlers 剥离,客户端不会加载;动态 import 使
43
- // 门控关闭路径完全不触达 harness 装配(避免无谓构造)。
44
- const [{ getHarnessHost }, { allblueHarness }, { createHarnessHandler }, { getCurrentSession }, { checkAiRateLimit, RateLimitExceededError }] = await Promise.all([
45
- import('@/server/harness/host.server'),
46
- import('@/server/harness/define.server'),
47
- import('@tanstack/ai-harness/server'),
48
- import('@/lib/session'),
49
- import('@/server/lib/rate-limit'),
50
- ])
43
+ // 门控关闭路径完全不触达 harness 装配(避免无谓构造)。整段包顶层 try/catch:
44
+ // 官方 createHarnessHandler 内部虽把 handler 异常转 400,但**动态 import 与 host
45
+ // 首次构造(getHarnessHost → createPrismaPersistence → @allbluecn/database 顶层
46
+ // await createPrismaClient)发生在该内部 try/catch 之前**——桌面真机未登录验收发现
47
+ // 这段抛错(PGlite 未就绪 / 迁移未跑 / env 缺失等)会以裸框架 500 逃逸,客户端
48
+ // describe/snapshot/transcript 三个 GET 全部 `Harness * failed (500)` 且 SSE 重连
49
+ // 退避耗尽 → 「重试次数已达上限」。收敛为结构化 503,不再让装配期故障裸奔。
50
+ try {
51
+ const [{ getHarnessHost }, { allblueHarness }, { createHarnessHandler }, { getCurrentSession }, { checkAiRateLimit, RateLimitExceededError }] = await Promise.all([
52
+ import('@/server/harness/host.server'),
53
+ import('@/server/harness/define.server'),
54
+ import('@tanstack/ai-harness/server'),
55
+ import('@/lib/session'),
56
+ import('@/server/lib/rate-limit'),
57
+ ])
51
58
 
52
- const url = new URL(request.url)
53
- const isControl = url.pathname.endsWith('/control')
54
- if (request.method === 'POST' && isControl) {
55
- const op = await readControlOp(request)
56
- if (op && RATE_LIMITED_OPS.has(op)) {
57
- // 限流身份取 access 层同源会话(client context 不可信,P0-2)
58
- const session = await getCurrentSession(request)
59
- const userId = session?.user?.id
60
- if (userId) {
61
- try {
62
- await checkAiRateLimit(userId, 'chat')
63
- } catch (err) {
64
- if (err instanceof RateLimitExceededError) {
65
- return new Response(
66
- JSON.stringify({ error: 'rate_limited', retryAfterMs: err.retryAfterMs }),
67
- { status: 429, headers: { 'content-type': 'application/json', 'retry-after': String(Math.ceil(err.retryAfterMs / 1000)) } },
68
- )
59
+ const url = new URL(request.url)
60
+ const isControl = url.pathname.endsWith('/control')
61
+ if (request.method === 'POST' && isControl) {
62
+ const op = await readControlOp(request)
63
+ if (op && RATE_LIMITED_OPS.has(op)) {
64
+ // 限流身份取 access 层同源会话(client context 不可信,P0-2)
65
+ const session = await getCurrentSession(request)
66
+ const userId = session?.user?.id
67
+ if (userId) {
68
+ try {
69
+ await checkAiRateLimit(userId, 'chat')
70
+ } catch (err) {
71
+ if (err instanceof RateLimitExceededError) {
72
+ return new Response(
73
+ JSON.stringify({ error: 'rate_limited', retryAfterMs: err.retryAfterMs }),
74
+ { status: 429, headers: { 'content-type': 'application/json', 'retry-after': String(Math.ceil(err.retryAfterMs / 1000)) } },
75
+ )
76
+ }
77
+ throw err
69
78
  }
70
- throw err
71
79
  }
72
80
  }
73
81
  }
74
- }
75
82
 
76
- // host 带 access(getCurrentSession 映射 + owner-only + 抢建防护 + acceptInput
77
- // 可信上下文覆写)。access/acceptInput 已在 getHarnessHost 单例内装配。
78
- const host = getHarnessHost()
79
- const handler = createHarnessHandler({ host, harness: allblueHarness })
80
- return handler(request)
83
+ // host 带 access(getCurrentSession 映射 + owner-only + 抢建防护 + acceptInput
84
+ // 可信上下文覆写)。access/acceptInput 已在 getHarnessHost 单例内装配。
85
+ const host = getHarnessHost()
86
+ const handler = createHarnessHandler({ host, harness: allblueHarness })
87
+ return await handler(request)
88
+ } catch (error) {
89
+ console.error('[harness] 请求处理失败(host 装配或 handler 异常):', error)
90
+ return new Response(
91
+ JSON.stringify({ error: 'harness_unavailable', message: error instanceof Error ? error.message : String(error) }),
92
+ { status: 503, headers: { 'content-type': 'application/json' } },
93
+ )
94
+ }
81
95
  }
82
96
 
83
97
  export const Route = createFileRoute('/api/harness/$')({
@@ -0,0 +1,176 @@
1
+ // @vitest-environment node
2
+
3
+ // forkHarnessThreadFn 单测(T2.11 ②):host.fork 整段复制 + 建 ChatThread 行(侧栏可见)。
4
+ // mock host/gate/define/prisma,不依赖真实 host。归属(userId 进 where)、host 未启用拒绝、
5
+ // fork → ChatThread.id = host.fork 的 newThreadId(ChatThread ↔ harness_sessions 对齐)。
6
+
7
+ import { beforeEach, describe, expect, it, vi } from "vitest"
8
+
9
+ vi.mock("@tanstack/react-start", () => ({
10
+ // 与 cancel-run.test.ts 同构:依序执行 middleware 的 server 段(复现 context 合并)
11
+ createServerFn: () => {
12
+ const api: any = {
13
+ _middlewares: [] as any[],
14
+ middleware(mws: any[]) {
15
+ api._middlewares.push(...mws)
16
+ return api
17
+ },
18
+ validator(schema: any) {
19
+ api._validator = schema
20
+ return api
21
+ },
22
+ handler(fn: any) {
23
+ return async (args: { data: unknown }) => {
24
+ let data = args?.data
25
+ if (api._validator && data !== undefined) {
26
+ data = api._validator.parse ? api._validator.parse(data) : data
27
+ }
28
+ let context: any = {}
29
+ for (const mw of api._middlewares) {
30
+ const serverFn = mw?.options?.server
31
+ if (!serverFn) continue
32
+ const result = await serverFn({
33
+ data,
34
+ context,
35
+ method: "POST",
36
+ serverFnMeta: {},
37
+ signal: new AbortController().signal,
38
+ next: async (inner: any) => ({ context: { ...context, ...(inner?.context ?? {}) } }),
39
+ })
40
+ context = result.context
41
+ }
42
+ return fn({ data, context })
43
+ }
44
+ },
45
+ }
46
+ return api
47
+ },
48
+ createMiddleware: (opts: any) => {
49
+ const mw: any = { options: { type: opts?.type } }
50
+ mw.server = (fn: Function) => {
51
+ mw.options.server = fn
52
+ return mw
53
+ }
54
+ return mw
55
+ },
56
+ }))
57
+ vi.mock("@tanstack/react-start/server", () => ({ getRequest: () => ({}) }))
58
+
59
+ const mocks = vi.hoisted(() => {
60
+ const findFirst = vi.fn()
61
+ const create = vi.fn()
62
+ const getCurrentSession = vi.fn()
63
+ const fork = vi.fn()
64
+ return { findFirst, create, getCurrentSession, fork }
65
+ })
66
+
67
+ vi.mock("@allbluecn/database", () => ({
68
+ prisma: {
69
+ chatThread: {
70
+ findFirst: mocks.findFirst,
71
+ create: mocks.create,
72
+ },
73
+ },
74
+ }))
75
+ vi.mock("@/lib/session", () => ({
76
+ getCurrentSession: mocks.getCurrentSession,
77
+ }))
78
+ vi.mock("@/server/harness/gate.server", () => ({
79
+ isHarnessHostEnabled: () => true,
80
+ }))
81
+ vi.mock("@/server/harness/host.server", () => ({
82
+ getHarnessHost: () => ({ fork: mocks.fork }),
83
+ }))
84
+ vi.mock("@/server/harness/define.server", () => ({
85
+ allblueHarness: { name: "allblue/harness" },
86
+ }))
87
+
88
+ import { forkHarnessThreadFn } from "../fork-thread"
89
+
90
+ const OWNER = { id: "user-1", name: "owner", email: "owner@example.com" }
91
+
92
+ const SOURCE = {
93
+ title: "迁移计划",
94
+ agentId: "agent-1",
95
+ engine: "cloud",
96
+ localCwd: null,
97
+ localAgentId: null,
98
+ }
99
+
100
+ beforeEach(() => {
101
+ vi.clearAllMocks()
102
+ mocks.getCurrentSession.mockResolvedValue({ user: OWNER })
103
+ mocks.findFirst.mockResolvedValue(SOURCE)
104
+ mocks.fork.mockResolvedValue({})
105
+ mocks.create.mockImplementation(async ({ data }: any) => ({
106
+ id: data.id,
107
+ title: data.title,
108
+ updatedAt: new Date(),
109
+ isArchived: false,
110
+ agentId: data.agentId,
111
+ localCwd: data.localCwd ?? null,
112
+ localAgentId: data.localAgentId ?? null,
113
+ agent: { name: "A", avatarEmoji: "🤖" },
114
+ }))
115
+ })
116
+
117
+ describe("forkHarnessThreadFn", () => {
118
+ it("线程不存在(他人/无)→ 拒绝,不 fork 不建行", async () => {
119
+ mocks.findFirst.mockResolvedValue(null)
120
+ await expect(
121
+ forkHarnessThreadFn({ data: { threadId: "t-1" } }),
122
+ ).rejects.toThrow("thread not found")
123
+ expect(mocks.fork).not.toHaveBeenCalled()
124
+ expect(mocks.create).not.toHaveBeenCalled()
125
+ })
126
+
127
+ it("归属:userId 进 where(只 fork 自己的线程)", async () => {
128
+ await forkHarnessThreadFn({ data: { threadId: "t-1" } })
129
+ expect(mocks.findFirst).toHaveBeenCalledWith({
130
+ where: { id: "t-1", userId: "user-1" },
131
+ select: expect.objectContaining({ engine: true }),
132
+ })
133
+ })
134
+
135
+ it("fork 成功 → host.fork 整段复制 + ChatThread.id = newThreadId(侧栏可见)", async () => {
136
+ const res = await forkHarnessThreadFn({ data: { threadId: "t-1" } })
137
+
138
+ // host.fork 被调:整段 transcript(at 缺省)+ 归属取当前用户
139
+ expect(mocks.fork).toHaveBeenCalledTimes(1)
140
+ const [harness, opts] = mocks.fork.mock.calls[0]
141
+ expect(harness).toMatchObject({ name: "allblue/harness" })
142
+ expect(opts.threadId).toBe("t-1")
143
+ expect(opts.user).toEqual({ id: "user-1" })
144
+ expect(opts.newThreadId).toBeTruthy()
145
+
146
+ // ChatThread 行以 fork 出的 newThreadId 建(ChatThread ↔ harness_sessions 对齐)
147
+ expect(mocks.create).toHaveBeenCalledWith(
148
+ expect.objectContaining({
149
+ data: expect.objectContaining({
150
+ id: opts.newThreadId,
151
+ userId: "user-1",
152
+ title: "迁移计划 (fork)",
153
+ }),
154
+ }),
155
+ )
156
+
157
+ // 返回侧栏 Conversation 形状(engine 收窄到 cloud|local)
158
+ expect(res).toMatchObject({
159
+ id: opts.newThreadId,
160
+ title: "迁移计划 (fork)",
161
+ engine: "cloud",
162
+ })
163
+ })
164
+
165
+ it("无标题源线程 fork → 标题落 (fork)", async () => {
166
+ mocks.findFirst.mockResolvedValue({ ...SOURCE, title: null })
167
+ const res = await forkHarnessThreadFn({ data: { threadId: "t-1" } })
168
+ expect(res.title).toBe("(fork)")
169
+ })
170
+
171
+ it("本地引擎线程 fork → engine 收窄为 local", async () => {
172
+ mocks.findFirst.mockResolvedValue({ ...SOURCE, engine: "local", localCwd: "/tmp/x" })
173
+ const res = await forkHarnessThreadFn({ data: { threadId: "t-1" } })
174
+ expect(res.engine).toBe("local")
175
+ })
176
+ })
@@ -0,0 +1,100 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // harness 会话 fork(设计 §6 / T2.7 / T2.11 ②)。
6
+ //
7
+ // 侧栏「分叉」在 harness 路径走 host.fork(整段 transcript 复制,at 缺省 = 全量,
8
+ // host.d.ts:620-632),新线程落在同一 tenant 的 harness_sessions(Phase 1 独立表)。
9
+ // 但侧栏单一真源是 ChatThread——故本 serverFn 在 host.fork 之后**应用层对齐**:以
10
+ // fork 出的 newThreadId 建 ChatThread 行,新线程即在侧栏可见(ChatThread ↔
11
+ // harness_sessions 对齐,Phase 1 既定边界)。
12
+ //
13
+ // 归属:host.fork 的 user 传当前会话用户(= run.user,设计 §6「新行归属取 run.user」),
14
+ // ChatThread.userId 同为该用户。与 legacy forkConversationFn(全量复制 ChatMessage 行)
15
+ // 互斥:harness 路径 transcript 由 host 持有,无需复制 ChatMessage(D13 二选一)。
16
+
17
+ import { getPrisma } from "@allbluecn/database/get-prisma"
18
+ import { createServerFn } from "@tanstack/react-start"
19
+ import { authContextMiddleware } from "@/server/middlewares/auth-context"
20
+ import { z } from "zod"
21
+
22
+ const forkThreadInput = z.object({
23
+ threadId: z.string().min(1),
24
+ })
25
+
26
+ /**
27
+ * harness 会话 fork:host.fork 整段复制 → 建 ChatThread 行(侧栏可见)。
28
+ *
29
+ * 失败语义:host.fork 抛错(线程不存在 / 归属不符 / fork 动作被拒)→ 直接上抛,
30
+ * 由调用方(工作台 handleFork)toast,不建 ChatThread(避免孤儿侧栏行)。建
31
+ * ChatThread 失败(极罕见)→ 上抛,harness_sessions 已 fork 的新线程无侧栏入口,
32
+ * 但 transcript 完好(重进线程 id 即可恢复),不回滚 host.fork(无分布式事务)。
33
+ */
34
+ export const forkHarnessThreadFn = createServerFn({ method: "POST" })
35
+ .middleware([authContextMiddleware])
36
+ .validator(forkThreadInput)
37
+ .handler(async ({ data, context }) => {
38
+ const prisma = await getPrisma()
39
+ const userId = context.user.id
40
+
41
+ const source = await prisma.chatThread.findFirst({
42
+ where: { id: data.threadId, userId },
43
+ select: {
44
+ title: true,
45
+ agentId: true,
46
+ engine: true,
47
+ localCwd: true,
48
+ localAgentId: true,
49
+ },
50
+ })
51
+ if (!source) throw new Error("thread not found")
52
+
53
+ // harness host 侧 fork(整段 transcript + settings + plugin config + media)。
54
+ // 仅 host 启用(桌面 / dev 开关)时可达;否则显式报错(与路由层 404 一致)。
55
+ const { isHarnessHostEnabled } = await import("@/server/harness/gate.server")
56
+ if (!isHarnessHostEnabled()) {
57
+ throw new Error("harness host 未启用,无法 fork")
58
+ }
59
+ const { getHarnessHost } = await import("@/server/harness/host.server")
60
+ const { allblueHarness } = await import("@/server/harness/define.server")
61
+ const host = getHarnessHost()
62
+ const newThreadId = crypto.randomUUID()
63
+ await host.fork(allblueHarness, {
64
+ threadId: data.threadId,
65
+ newThreadId,
66
+ // at 缺省 = 整段 transcript(host.d.ts:623-624),对齐 legacy fork 语义
67
+ user: { id: userId },
68
+ })
69
+
70
+ // 应用层对齐:fork 出的 harness_sessions 行 → 建 ChatThread 行(侧栏单一真源)。
71
+ // 标题沿用 legacy fork 口径(`${title} (fork)` / `(fork)`);host 侧 entry.title
72
+ // 亦为旧标题 + " (fork)"(host.d.ts:481-482),两侧一致。
73
+ const conversation = await prisma.chatThread.create({
74
+ data: {
75
+ id: newThreadId,
76
+ userId,
77
+ title: source.title ? `${source.title} (fork)` : "(fork)",
78
+ agentId: source.agentId,
79
+ engine: source.engine,
80
+ localCwd: source.localCwd,
81
+ localAgentId: source.localAgentId,
82
+ },
83
+ include: { agent: { select: { name: true, avatarEmoji: true } } },
84
+ })
85
+
86
+ return {
87
+ id: conversation.id,
88
+ title: conversation.title,
89
+ lastMessageAt: conversation.updatedAt,
90
+ messageCount: 0,
91
+ isArchived: conversation.isArchived,
92
+ agentId: conversation.agentId,
93
+ // Prisma engine 列为 String,收窄到 Conversation.engine 联合(local 之外归 cloud)
94
+ engine: source.engine === "local" ? ("local" as const) : ("cloud" as const),
95
+ localCwd: conversation.localCwd,
96
+ localAgentId: conversation.localAgentId,
97
+ agentName: conversation.agent?.name ?? null,
98
+ agentEmoji: conversation.agent?.avatarEmoji ?? null,
99
+ }
100
+ })