Merge remote-tracking branch 'origin/master' into worktree/process-plugin-streaming-72f9b3

# Conflicts:
#	docs/event-producer-consumer.i18n.yaml
#	docs/event-producer-consumer.md
#	docs/event-producer-consumer.zh.md
#	docs/module-graph.i18n.yaml
#	docs/module-graph.md
#	docs/module-graph.zh.md
#	packages/api/remotes/package.json
#	packages/api/remotes/src/client/index.ts
#	packages/api/session-controller/README.i18n.yaml
#	packages/api/session-controller/README.md
#	packages/api/session-controller/README.zh.md
#	packages/api/session-controller/tsconfig.host.json
#	packages/client/ui-approval/src/client/contract/slots.ts
#	packages/client/ui-chat/src/client/chat/MessageItem.tsx
#	packages/client/ui-chat/src/client/conversation-nodes/assistant.ts
#	packages/client/ui-chat/src/client/conversation-nodes/partial.ts
#	packages/client/ui-chat/src/client/conversation-nodes/tool.ts
#	packages/client/ui-chat/src/client/model/tool-call-tree.ts
This commit is contained in:
Yichen Jiang committed 2026-09-04 17:28:12 +08:00
commit d3b1f2d1bc
461 files changed
+12176 -1942

No files matched your search

@@ -65,6 +65,11 @@ async function mount(initialGeneration?: ConnectionGeneration): Promise<Bench> {
registerGenerationSource: () => () => {},
start: () => ({ stop: () => {} }),
}
ctx.reflect.provide('connection', connection)
ctx.reflect.provide('fileUpload', {
available: true,
post: () => Promise.reject(new Error('unexpected file upload')),
})
ctx.reflect.provide('remote', {
...remote,
$stream: <Item>(options: RemoteStreamOptions<Item>) => (
@@ -73,8 +73,9 @@ describe('Client Session contracts', () => {
expectTypeOf<SessionPageRequest['throughSeq']>().toEqualTypeOf<number>()
})
it('keeps its catalog-visible prompt parts identical to attachment intake', () => {
expectTypeOf<SessionPromptContentPart>().toEqualTypeOf<AttachmentPromptContentPart>()
it('keeps its text and image prompt parts identical to attachment intake', () => {
expectTypeOf<Exclude<SessionPromptContentPart, { type: 'file' }>>()
.toEqualTypeOf<AttachmentPromptContentPart>()
})
it('publishes exact replace, prepend, and append event-window changes', () => {
@@ -112,6 +112,23 @@ describe('Session queue commands', () => {
})).toEqual({ accepted: true })
expect(steer).toHaveBeenCalledWith(steered)
const queuedFile = createUserMessage({
content: [{
type: 'file',
attachment: { attachmentId: AttachmentId('file-queued'), name: 'queued.txt', bytes: 6 },
}],
source: { kind: 'user', rpcId: 'file-rpc' as never },
})
inbox.append('next-turn', queuedFile)
expect(controller.updateQueue({
sessionId: agent.id, itemId: queuedFile.id, action: { kind: 'steer' },
})).toEqual({ accepted: true })
expect(steer).toHaveBeenLastCalledWith(queuedFile)
expect(queuedFile).toMatchObject({
source: { kind: 'user', rpcId: 'file-rpc' },
content: [{ type: 'file', attachment: { name: 'queued.txt', bytes: 6 } }],
})
await expectFailure(Promise.resolve().then(() => controller.cancel({
sessionId: SessionId('missing'),
})), 'session/not-found')
@@ -0,0 +1,471 @@
import { Context } from '@deepseek-ai/cordis'
import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
import type { Agent, ModelSelectionRef } from '@deepseek-ai/dsh-agent'
import AttachmentStore, { AttachmentId } from '@deepseek-ai/dsh-attachment'
import type {
FileAttachmentRef, ImageAttachmentRef, SaveFileAttachment, SaveFileStreamAttachment,
} from '@deepseek-ai/dsh-attachment'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import type { UserMessage } from '@deepseek-ai/dsh-llm'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import CommandRuntime from '@deepseek-ai/dsh-commands'
import { createScope } from '@deepseek-ai/dsh-scope'
import FileUploads from '@deepseek-ai/dsh-client-file-upload'
import type { FileUploadReceiptId } from '@deepseek-ai/dsh-client-file-upload/types'
import { describe, expect, it, vi } from 'vitest'
import type { ApiSessionAgentController } from '../src/agent.ts'
import { SessionCommandController } from '../src/commands.ts'
import type { SessionRequestId } from '../src/types.ts'
const SESSION = SessionId('upload-session')
async function uploadHarness(origin?: 'subagent'): Promise<{
ctx: Context
controller: SessionCommandController
uploads: FileUploads
agent: Agent
followup: ReturnType<typeof vi.fn>
saveFile: ReturnType<typeof vi.fn>
saveFileStream: ReturnType<typeof vi.fn>
saveImages: ReturnType<typeof vi.fn>
disposeAgent: () => void
uploadRoute: (request: Request) => Promise<Response>
}> {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(AgentRegistry)
await ctx.plugin(CommandRuntime)
const session = ctx.sessions.create(SESSION, {
meta: { cwd: '/workspace', ...(origin === undefined ? {} : { origin }) },
})
const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} })
const followup = vi.fn()
const agent = {
id: session.id,
session,
inbox,
status: 'idle',
ctx: undefined,
steer: vi.fn(),
followup,
cancel: vi.fn(),
} as unknown as Agent
;(agent as { ctx: Context }).ctx = createScope(ctx, agent).ctx
const disposeAgent = ctx.agents.register(agent)
const saveFile = vi.fn((input: SaveFileAttachment): Promise<FileAttachmentRef> => Promise.resolve({
attachmentId: AttachmentId(`sha256:${'cd'.repeat(32)}`),
name: input.name ?? 'file',
bytes: input.data.byteLength,
}))
const saveFileStream = vi.fn(async (input: SaveFileStreamAttachment): Promise<FileAttachmentRef> => {
let bytes = 0
for await (const chunk of input.data) bytes += chunk.byteLength
return {
attachmentId: AttachmentId(`sha256:${'ef'.repeat(32)}`),
name: input.name ?? 'file',
bytes,
}
})
const saveImages = vi.fn((): Promise<readonly ImageAttachmentRef[]> =>
Promise.reject(new Error('fixture did not expect image persistence')))
ctx.provide('attachments', Object.setPrototypeOf(
{ saveFile, saveFileStream, saveImages },
AttachmentStore.prototype,
) as never)
let uploadRoute: ((request: Request) => Promise<Response>) | undefined
ctx.provide('connection', {
fetch: {
register: (route: { readonly fetch: (request: Request) => Promise<Response> }) => {
uploadRoute = route.fetch
return () => {}
},
},
} as never)
ctx.provide('llm', {
listProviders: () => [{ id: 'fixture', name: 'Fixture' }],
resolveModelInfo: () => Promise.resolve({ provider: 'fixture', id: 'fixture-model', name: 'Fixture' }),
} as never)
const selection: ModelSelectionRef = {
current: { provider: 'fixture', model: 'fixture-model' },
assembled: undefined,
}
const agents = {
resolveAgent: () => Promise.resolve({ agent }),
selectionFor: () => selection,
serializeImageAdmission: <Value>(_agent: Agent, operation: () => Promise<Value>) => operation(),
} as unknown as ApiSessionAgentController
const uploads = new FileUploads(ctx)
if (uploadRoute === undefined) throw new Error('file upload route was not registered')
return {
ctx,
controller: new SessionCommandController(ctx, agents, '/workspace'),
uploads,
agent,
followup,
saveFile,
saveFileStream,
saveImages,
disposeAgent,
uploadRoute,
}
}
function promptRequest(content: Parameters<SessionCommandController['prompt']>[0]['content']) {
return {
requestId: 'req-1' as SessionRequestId,
sessionId: SESSION,
mode: 'queue' as const,
content,
}
}
describe('Session file uploads', () => {
it('registers an HTTP route bound to the upload service', async () => {
const { uploadRoute } = await uploadHarness()
await expect(uploadRoute(new Request('http://host/upload')))
.resolves.toMatchObject({ status: 405 })
})
it('stages one verbatim upload and preserves its order with an admitted image', async () => {
const { ctx, controller, uploads, agent, followup, saveFile, saveImages } = await uploadHarness()
const receipt = await uploads.upload(agent, { data: 'AAAA', name: 'notes.pdf' }, new AbortController().signal)
expect(saveFile).toHaveBeenCalledTimes(1)
expect(receipt.file.name).toBe('notes.pdf')
expect(receipt.file.bytes).toBe(3)
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
expect(uploads.resolve(agent, 'missing' as FileUploadReceiptId)).toBeUndefined()
const commandHandler = vi.fn((_invocation: unknown) => ({ kind: 'success' as const }))
ctx.commands.register({
name: 'files', description: 'Use staged files', input: { hint: '<task>', attachments: true },
handler: commandHandler,
})
await ctx.commands.execute(
agent,
'/files inspect',
[{ type: 'file', receiptId: receipt.receiptId }],
new AbortController().signal,
)
expect(commandHandler.mock.calls[0]?.[0]).toMatchObject({
attachments: [{ type: 'file', attachment: receipt.file }],
})
const image: ImageAttachmentRef = {
attachmentId: AttachmentId(`sha256:${'ab'.repeat(32)}`),
mediaType: 'image/png',
bytes: 3,
width: 1,
height: 1,
}
saveImages.mockResolvedValueOnce([image])
await controller.prompt(promptRequest([
{ type: 'file', receiptId: receipt.receiptId },
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
{ type: 'text', text: 'read it' },
]))
expect(followup).toHaveBeenCalledTimes(1)
const message = followup.mock.calls[0]?.[0] as UserMessage
expect(message.content).toEqual([
{ type: 'file', attachment: receipt.file },
{ type: 'image', attachment: image },
{ type: 'text', text: 'read it' },
])
})
it('stages a bounded byte stream and forwards cancellation to storage', async () => {
const { controller, uploads, followup, saveFileStream } = await uploadHarness()
const abort = new AbortController()
const receipt = await uploads.uploadStream({
sessionId: SESSION,
data: (async function* (): AsyncIterable<Uint8Array> {
yield Uint8Array.of(1, 2)
yield Uint8Array.of(3, 4, 5)
})(),
signal: abort.signal,
name: 'huge.bin',
})
expect(saveFileStream).toHaveBeenCalledWith(expect.objectContaining({
signal: abort.signal,
name: 'huge.bin',
}))
expect(receipt.file).toMatchObject({ name: 'huge.bin', bytes: 5 })
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]))
expect((followup.mock.calls[0]?.[0] as UserMessage).content).toEqual([
{ type: 'file', attachment: receipt.file },
])
})
it('keeps the stream name optional and maps storage failures through the same error vocabulary', async () => {
const { uploads, saveFileStream } = await uploadHarness()
const stream = (async function* (): AsyncIterable<Uint8Array> {})()
await expect(uploads.uploadStream({ sessionId: SESSION, data: stream }))
.resolves.toMatchObject({ file: { name: 'file', bytes: 0 } })
expect(saveFileStream).toHaveBeenLastCalledWith({ data: stream })
saveFileStream.mockRejectedValueOnce('disk offline')
await expect(uploads.uploadStream({
sessionId: SESSION,
data: (async function* (): AsyncIterable<Uint8Array> { yield Uint8Array.of(1) })(),
}))
.rejects.toMatchObject({
code: 'gateway/internal', message: 'failed to store file upload: disk offline',
})
})
it('rejects a prompt citing a file that was never staged for the session', async () => {
const { controller, followup, saveImages } = await uploadHarness()
await expect(controller.prompt(promptRequest([
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
{ type: 'file', receiptId: 'missing-receipt' as FileUploadReceiptId },
]))).rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'FILE_NOT_STAGED' } })
expect(followup).not.toHaveBeenCalled()
expect(saveImages).not.toHaveBeenCalled()
})
it('publishes no receipt when its exact Agent is disposed during storage', async () => {
const { uploads, agent, saveFile, disposeAgent } = await uploadHarness()
const saved = Promise.withResolvers<FileAttachmentRef>()
saveFile.mockReturnValueOnce(saved.promise)
const uploading = uploads.upload(agent, { data: 'AAAA', name: 'late.bin' }, new AbortController().signal)
await vi.waitFor(() => { expect(saveFile).toHaveBeenCalledOnce() })
disposeAgent()
saved.resolve({
attachmentId: AttachmentId(`sha256:${'ab'.repeat(32)}`), name: 'late.bin', bytes: 3,
})
await expect(uploading).rejects.toMatchObject({ code: 'session/not-found' })
})
it('resolves a cold ordinary Agent and releases the resolver registration', async () => {
const { ctx, uploads, agent, disposeAgent } = await uploadHarness()
disposeAgent()
const resolveAgent = vi.fn(async () => {
ctx.agents.register(agent)
return agent
})
const disposeResolver = uploads.registerAgentResolver(resolveAgent)
expect(() => { uploads.registerAgentResolver(resolveAgent) }).toThrow('already registered')
await expect(uploads.uploadStream({
sessionId: SESSION,
data: (async function* (): AsyncIterable<Uint8Array> { yield Uint8Array.of(1) })(),
})).resolves.toMatchObject({ file: { bytes: 1 } })
expect(resolveAgent).toHaveBeenCalledWith(SESSION)
disposeResolver()
const replacement = vi.fn(async () => agent)
const disposeReplacement = uploads.registerAgentResolver(replacement)
disposeResolver()
expect(() => { uploads.registerAgentResolver(replacement) }).toThrow('already registered')
expect(disposeReplacement).toBeTypeOf('function')
disposeReplacement()
})
it('rejects a cold upload when no Agent resolver is registered', async () => {
const { uploads, disposeAgent } = await uploadHarness()
disposeAgent()
await expect(uploads.uploadStream({
sessionId: SESSION,
data: (async function* (): AsyncIterable<Uint8Array> {})(),
})).rejects.toMatchObject({ code: 'session/not-found' })
})
it('rejects subagent uploads and access outside the receiving Agent scope', async () => {
const child = await uploadHarness('subagent')
await expect(child.uploads.upload(
child.agent,
{ data: 'AAAA' },
new AbortController().signal,
)).rejects.toMatchObject({
code: 'subagent/attachment-invalid',
details: { reason: 'SUBAGENT_FILE_UNSUPPORTED' },
})
expect(child.saveFile).not.toHaveBeenCalled()
const ordinary = await uploadHarness()
const receipt = await ordinary.uploads.upload(
ordinary.agent,
{ data: 'AAAA' },
new AbortController().signal,
)
const foreignScope = { ...ordinary.agent, ctx: ordinary.ctx } as Agent
expect(() => ordinary.uploads.resolve(foreignScope, receipt.receiptId))
.toThrow('operation requires the Agent\'s own scope')
})
it('retires accepted receipts after their rpcId becomes observable', async () => {
const { controller, uploads, agent } = await uploadHarness()
uploads.retirePrompt(agent, 'not-staged')
const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal)
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]))
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
uploads.retirePrompt(agent, 'other-request')
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
uploads.retirePrompt(agent, 'req-1')
expect(uploads.resolve(agent, receipt.receiptId)).toBeUndefined()
})
it('retires observed prompt receipts and drops staged state with the Session', async () => {
const first = await uploadHarness()
const observed = await first.uploads.upload(
first.agent,
{ data: 'AAAA' },
new AbortController().signal,
)
await first.controller.prompt(promptRequest([{ type: 'file', receiptId: observed.receiptId }]))
first.ctx.emit('session/event', first.agent.session, {
type: 'user/message',
data: createUserMessage({
content: [{ type: 'text', text: 'extension event' }],
source: { kind: 'user', rpcId: 1 } as never,
}),
} as never)
expect(first.uploads.resolve(first.agent, observed.receiptId)).toEqual(observed.file)
first.agent.session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'observed' }],
source: { kind: 'user', rpcId: 'req-1' as SessionRequestId },
}), { surfaceOp: 'append' })
expect(first.uploads.resolve(first.agent, observed.receiptId)).toBeUndefined()
const second = await uploadHarness()
const abandoned = await second.uploads.upload(
second.agent,
{ data: 'AAAA' },
new AbortController().signal,
)
second.ctx.emit('session/disposed', second.agent.session)
expect(second.uploads.resolve(second.agent, abandoned.receiptId)).toBeUndefined()
})
it('deduplicates a retried rpcId already present in the Agent inbox', async () => {
const { controller, agent, followup } = await uploadHarness()
const request = promptRequest([{ type: 'text', text: 'once' }])
await controller.prompt(request)
agent.inbox.append('next-turn', followup.mock.calls[0]?.[0] as UserMessage)
await expect(controller.prompt(request)).resolves.toEqual({ accepted: true })
expect(followup).toHaveBeenCalledOnce()
})
it('deduplicates a retried rpcId already present in the durable log', async () => {
const { controller, agent, followup } = await uploadHarness()
const request = promptRequest([{ type: 'text', text: 'once' }])
agent.session.append('turn/start', { turn: 1 })
agent.session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'unidentified' }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
agent.session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'accepted' }],
source: { kind: 'user', rpcId: request.requestId },
}), { surfaceOp: 'append' })
await expect(controller.prompt(request)).resolves.toEqual({ accepted: true })
expect(followup).not.toHaveBeenCalled()
})
it('rejects when the Agent disappears during prompt admission', async () => {
const { controller, saveImages, disposeAgent } = await uploadHarness()
const admitted = Promise.withResolvers<readonly ImageAttachmentRef[]>()
saveImages.mockReturnValueOnce(admitted.promise)
const prompting = controller.prompt(promptRequest([
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
]))
await vi.waitFor(() => { expect(saveImages).toHaveBeenCalledOnce() })
disposeAgent()
admitted.resolve([{
attachmentId: AttachmentId('admitted-image'), mediaType: 'image/png', bytes: 3, width: 1, height: 1,
}])
await expect(prompting).rejects.toMatchObject({ code: 'session/not-found' })
})
it('rejects when a previously bound receipt retires during image admission', async () => {
const { controller, uploads, agent, saveImages } = await uploadHarness()
const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal)
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]))
const admitted = Promise.withResolvers<readonly ImageAttachmentRef[]>()
saveImages.mockReturnValueOnce(admitted.promise)
const prompting = controller.prompt({
...promptRequest([
{ type: 'file', receiptId: receipt.receiptId },
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
]),
requestId: 'req-2' as SessionRequestId,
})
await vi.waitFor(() => { expect(saveImages).toHaveBeenCalledOnce() })
uploads.retirePrompt(agent, 'req-1')
admitted.resolve([{
attachmentId: AttachmentId('admitted-image'), mediaType: 'image/png', bytes: 3, width: 1, height: 1,
}])
await expect(prompting).rejects.toMatchObject({
code: 'session/attachment-invalid', details: { reason: 'FILE_NOT_STAGED' },
})
})
it('keeps the prior receipt binding when a later prompt attempt fails', async () => {
const { controller, uploads, agent, followup } = await uploadHarness()
const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal)
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]))
followup.mockImplementationOnce(() => { throw new Error('busy') })
await expect(controller.prompt({
...promptRequest([{ type: 'file', receiptId: receipt.receiptId }]),
requestId: 'req-2' as SessionRequestId,
})).rejects.toMatchObject({ code: 'session/agent-busy' })
uploads.retirePrompt(agent, 'req-1')
expect(uploads.resolve(agent, receipt.receiptId)).toBeUndefined()
})
it('restores an unbound receipt after prompt delivery fails', async () => {
const { controller, uploads, agent, followup } = await uploadHarness()
const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal)
followup.mockImplementationOnce(() => { throw new Error('busy') })
await expect(controller.prompt(promptRequest([
{ type: 'file', receiptId: receipt.receiptId },
]))).rejects.toMatchObject({ code: 'session/agent-busy' })
uploads.retirePrompt(agent, 'req-1')
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
})
it('retires a prompt-bound receipt when its queued occurrence is removed', async () => {
const { controller, uploads, agent, followup } = await uploadHarness()
const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal)
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]))
const queued = followup.mock.calls[0]?.[0] as UserMessage
agent.inbox.append('next-turn', queued)
expect(controller.updateQueue({
sessionId: SESSION,
itemId: queued.id,
action: { kind: 'remove' },
})).toEqual({ accepted: true })
expect(uploads.resolve(agent, receipt.receiptId)).toBeUndefined()
})
it('keeps separate names for identical bytes uploaded more than once', async () => {
const { controller, uploads, agent, followup } = await uploadHarness()
const first = await uploads.upload(agent, { data: 'AAAA', name: 'first.txt' }, new AbortController().signal)
const second = await uploads.upload(agent, { data: 'AAAA', name: 'second.txt' }, new AbortController().signal)
expect(first.file.attachmentId).toBe(second.file.attachmentId)
expect(first.receiptId).not.toBe(second.receiptId)
await controller.prompt(promptRequest([
{ type: 'file', receiptId: first.receiptId },
{ type: 'file', receiptId: second.receiptId },
]))
const message = followup.mock.calls[0]?.[0] as UserMessage
expect(message.content).toEqual([
{ type: 'file', attachment: first.file },
{ type: 'file', attachment: second.file },
])
})
it('maps a non-canonical payload to the wire attachment error', async () => {
const { uploads, agent, saveFile } = await uploadHarness()
await expect(uploads.upload(agent, { data: 'not base64!!' }, new AbortController().signal))
.rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'INVALID_FILE_BASE64' } })
expect(saveFile).not.toHaveBeenCalled()
})
it('maps an unexpected storage failure to the internal wire error', async () => {
const { uploads, agent, saveFile } = await uploadHarness()
saveFile.mockRejectedValueOnce(new Error('disk unavailable'))
await expect(uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal))
.rejects.toMatchObject({
code: 'gateway/internal',
message: 'failed to store file upload: Error: disk unavailable',
})
})
})
@@ -42,6 +42,16 @@ describe('SessionController facade', () => {
list: () => Promise.resolve([header]),
inspect,
}) as never)
let uploadResolver: ((sessionId: SessionId) => Promise<Agent>) | undefined
ctx.provide('fileUploads', {
registerAgentResolver: (resolve: (sessionId: SessionId) => Promise<Agent>) => {
uploadResolver = resolve
return () => {}
},
resolve: () => undefined,
bindPrompt: () => ({ commit: () => {}, [Symbol.dispose]: () => {} }),
retirePrompt: () => {},
} as never)
const controller = createSessionTestController(ctx, defaults)
const status = vi.fn()
const failure = vi.fn()
@@ -65,6 +75,17 @@ describe('SessionController facade', () => {
ctx,
} as Agent
ctx.agents.register(agent)
const resolveUploadAgent = (id: SessionId): Promise<Agent> => {
if (uploadResolver === undefined) throw new Error('file upload resolver was not registered')
return uploadResolver(id)
}
await expect(resolveUploadAgent(sessionId)).resolves.toBe(agent)
const activationError = new RemoteError('session/not-found', 'missing upload session', { sessionId })
vi.spyOn(
(controller as unknown as { agents: ApiSessionAgentController }).agents,
'resolveAgent',
).mockResolvedValueOnce({ error: activationError })
await expect(resolveUploadAgent(sessionId)).rejects.toBe(activationError)
const consumeSelection = vi.spyOn(
(controller as unknown as { agents: ApiSessionAgentController }).agents,
'consumeSelection',
@@ -83,6 +104,10 @@ describe('SessionController facade', () => {
content: [{ type: 'text', text: 'hello' }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'browser prompt' }],
source: { kind: 'user', rpcId: 'controller-rpc' as never },
}), { surfaceOp: 'append' })
expect(status).toHaveBeenCalledWith(sessionId, true)
expect(failure).toHaveBeenCalledWith(sessionId, expect.stringContaining('fixture failure'))
expect(activity).toHaveBeenCalledWith(sessionId, expect.any(Number))
@@ -108,7 +133,7 @@ describe('SessionController facade', () => {
}, abort.signal)[Symbol.asyncIterator]()
await expect(iterator.next()).resolves.toMatchObject({
done: false,
value: { type: 'snapshot', cursor: 1 },
value: { type: 'snapshot', cursor: 2 },
})
abort.abort()
await expect(iterator.next()).resolves.toEqual({ done: true, value: undefined })
@@ -73,21 +73,29 @@ describe('Session queue snapshot intake', () => {
])
})
it('marks mixed-content messages non-editable and keeps image blocks out of the text preview', () => {
it('marks mixed-content messages non-editable and keeps attachment blocks out of the text preview', () => {
const session = makeSession()
session.handleControlFrame(queueFrame([{
id: 'q-image',
body: '',
content: [{ type: 'text', text: 'hi' }, { type: 'image', data: 'x' } as never],
content: [
{ type: 'text', text: 'hi' },
{ type: 'image', data: 'x' } as never,
{ type: 'file', attachment: { attachmentId: 'file-1', name: 'notes.txt', bytes: 5 } } as never,
],
}]))
const queue = session.getSnapshot().queue
expect(typeof queue[0]?.messageId).toBe('string')
expect(queue).toMatchObject([
{
id: 'q-image', placement: 'queued',
content: [{ type: 'text', text: 'hi' }, { type: 'image', data: 'x' }],
// Image blocks render as thumbnails from `content`, so the preview
// carries only the text; non-image foreign blocks keep their marker.
content: [
{ type: 'text', text: 'hi' },
{ type: 'image', data: 'x' },
{ type: 'file', attachment: { attachmentId: 'file-1', name: 'notes.txt', bytes: 5 } },
],
// Attachment blocks render from `content`, so the preview carries
// only text; other foreign blocks keep their marker.
preview: 'hi', text: null,
},
])
@@ -8,14 +8,14 @@ import { SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq } from '@deepseek-
import { describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import SessionStore from '@deepseek-ai/dsh-session'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
import { SessionHistoryController } from '@deepseek-ai/dsh-api-session-controller/src/history.ts'
import { subagentIdentityProjectionDefinition } from '@deepseek-ai/dsh-subagent/src/projection.ts'
import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
import { createUserMessage, MessageId } from '@deepseek-ai/dsh-llm'
import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
import type { SessionPromptRequest, SessionRequestId } from '../src/types.ts'
import {
SessionPersistenceRevision,
@@ -42,6 +42,10 @@ function promptRequest(
}
}
function inboxFor(session: Session): Inbox {
return new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} })
}
function header(id: string, createdAt: number, extra: Partial<SessionHeader> = {}): SessionHeader {
return { version: SESSION_FORMAT_VERSION, id: sid(id), createdAt, isSeeded: false, cwd: '/proj', ...extra }
}
@@ -540,7 +544,9 @@ describe('subagent ownership fence', () => {
inheritedEventCount: SessionLogOffset(1),
})
const followup = vi.fn()
const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
const agent = {
id: session.id, session, inbox: inboxFor(session), status: 'idle', ctx, followup,
} as unknown as Agent
ctx.agents.register(agent)
const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
@@ -559,7 +565,9 @@ describe('subagent ownership fence', () => {
await ctx.plugin(AgentRegistry)
const session = ctx.sessions.create(sid('session-browser-zone'), { meta: { cwd: '/proj' } })
const followup = vi.fn()
const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
const agent = {
id: session.id, session, inbox: inboxFor(session), status: 'idle', ctx, followup,
} as unknown as Agent
ctx.agents.register(agent)
const remote = createSessionTestRemote(ctx, {
defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
@@ -679,6 +687,7 @@ describe('sessions.prompt synchronous rejection', () => {
ctx.agents.register({
id: session.id,
session,
inbox: inboxFor(session),
status: 'idle',
ctx,
followup: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
@@ -665,7 +665,7 @@ describe('Web session model selection', () => {
const savedRef = {
attachmentId: 'saved-image', mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1,
}
ctx.provide('attachments', {
ctx.provide('attachments', Object.setPrototypeOf({
saveImages: () => {
if (saveMode === 'error') return Promise.reject(new Error('image store offline'))
if (saveMode === 'remote') {
@@ -673,7 +673,7 @@ describe('Web session model selection', () => {
}
return Promise.resolve([savedRef])
},
} as never)
}, AttachmentStore.prototype) as never)
const followup = vi.fn()
Object.assign(agent, { followup })
const remote = createSessionTestRemote(ctx, {
@@ -2,7 +2,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
import { SessionSeq, type SessionEvent, type SessionId } from '@deepseek-ai/dsh-session/types'
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
import { Session } from '../src/client/sessions/session.ts'
@@ -31,8 +31,20 @@ function imageRef(id: string): ImageAttachmentRef {
} as unknown as ImageAttachmentRef
}
function fileRef(id: string, name = 'notes.txt'): FileAttachmentRef {
return { attachmentId: id, name, bytes: 3 } as unknown as FileAttachmentRef
}
type AttachmentRef = ImageAttachmentRef | FileAttachmentRef
function attachmentBlock(attachment: AttachmentRef) {
return 'mediaType' in attachment
? { type: 'image' as const, attachment }
: { type: 'file' as const, attachment }
}
/** A durable browser-prompt user/message whose source echoes `rpcId`. */
function promptEvent(seq: SessionSeq, rpcId: SessionRequestId, refs: readonly ImageAttachmentRef[] = []): SessionEvent {
function promptEvent(seq: SessionSeq, rpcId: SessionRequestId, refs: readonly AttachmentRef[] = []): SessionEvent {
return {
seq,
time: 1_700_000_000_000 + seq,
@@ -40,7 +52,7 @@ function promptEvent(seq: SessionSeq, rpcId: SessionRequestId, refs: readonly Im
surfaceOp: 'append',
data: createUserMessage({
content: [
...refs.map(attachment => ({ type: 'image' as const, attachment })),
...refs.map(attachmentBlock),
{ type: 'text' as const, text: '发送' },
],
source: { kind: 'user', rpcId },
@@ -48,14 +60,14 @@ function promptEvent(seq: SessionSeq, rpcId: SessionRequestId, refs: readonly Im
} as unknown as SessionEvent
}
function queuedItem(rpcId: SessionRequestId, refs: readonly ImageAttachmentRef[] = []): SessionQueuedItem {
function queuedItem(rpcId: SessionRequestId, refs: readonly AttachmentRef[] = []): SessionQueuedItem {
return {
id: 'm-queued' as SessionQueuedItem['id'],
placement: 'queued',
rpcId,
message: {
id: 'm-queued' as SessionQueuedItem['id'],
content: refs.map(attachment => ({ type: 'image', attachment })) as unknown as SessionQueuedItem['message']['content'],
content: refs.map(attachmentBlock) as unknown as SessionQueuedItem['message']['content'],
},
}
}
@@ -72,23 +84,27 @@ describe('beginSubmission', () => {
const handle = session.beginSubmission({
mode: 'queue',
text: '你好',
images: [{ previewUrl: 'blob:p1', name: 'a.png', width: 4, height: 3 }],
attachments: [{
type: 'image', value: { previewUrl: 'blob:p1', name: 'a.png', width: 4, height: 3 },
}],
})
expect(session.getSnapshot().promptAttempted).toBe(true)
expect(session.getSnapshot().pendingSubmissions).toMatchObject([{
requestId: handle.requestId,
placement: 'transcript',
text: '你好',
images: [{ previewUrl: 'blob:p1', name: 'a.png', width: 4, height: 3 }],
attachments: [{
type: 'image', value: { previewUrl: 'blob:p1', name: 'a.png', width: 4, height: 3 },
}],
}])
})
it('derives and captures the echo placement from running state and delivery mode', () => {
const { session } = makeSession()
session.beginSubmission({ mode: 'queue', text: '空闲', images: [] })
session.beginSubmission({ mode: 'queue', text: '空闲', attachments: [] })
session.handleRunning(true)
session.beginSubmission({ mode: 'queue', text: '排队', images: [] })
session.beginSubmission({ mode: 'steer', text: '纠偏', images: [] })
session.beginSubmission({ mode: 'queue', text: '排队', attachments: [] })
session.beginSubmission({ mode: 'steer', text: '纠偏', attachments: [] })
session.handleRunning(false)
expect(session.getSnapshot().pendingSubmissions.map(({ text, placement }) => ({ text, placement }))).toEqual([
{ text: '空闲', placement: 'transcript' },
@@ -103,7 +119,7 @@ describe('beginSubmission', () => {
const handle = session.beginSubmission({
mode: 'queue',
text: '放弃',
images: [],
attachments: [],
onRetire: retirement => retirements.push(retirement),
})
handle.abandon()
@@ -121,7 +137,7 @@ describe('prompt-coupled retirement', () => {
const handle = session.beginSubmission({
mode: 'queue',
text: '失败的',
images: [],
attachments: [],
onRetire: retirement => retirements.push(retirement),
})
const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue', undefined, handle.requestId)
@@ -133,7 +149,7 @@ describe('prompt-coupled retirement', () => {
it('sends the echo identity as the prompt requestId', async () => {
const { api, session } = makeSession()
const handle = session.beginSubmission({ mode: 'queue', text: '带 id', images: [] })
const handle = session.beginSubmission({ mode: 'queue', text: '带 id', attachments: [] })
await session.prompt([{ type: 'text', text: '带 id' }], 'queue', undefined, handle.requestId)
expect(api.callsOf('session.prompt')).toMatchObject([{ requestId: handle.requestId }])
})
@@ -141,7 +157,7 @@ describe('prompt-coupled retirement', () => {
it('an unidentified prompt failure leaves registered echoes alone', async () => {
const { api, session } = makeSession()
api.onPrompt = () => Promise.resolve(err(new RemoteError('session/agent-busy', '忙', { reason: 'busy' })))
session.beginSubmission({ mode: 'queue', text: '还在', images: [] })
session.beginSubmission({ mode: 'queue', text: '还在', attachments: [] })
await session.prompt([{ type: 'text', text: '另一个' }], 'queue')
expect(session.getSnapshot().pendingSubmissions).toHaveLength(1)
})
@@ -156,7 +172,7 @@ describe('observed retirement', () => {
const handle = session.beginSubmission({
mode: 'queue',
text: '发送',
images: [{ previewUrl: 'blob:p1' }],
attachments: [{ type: 'image', value: { previewUrl: 'blob:p1' } }],
onRetire: retirement => retirements.push(retirement),
})
const refs = [imageRef('att-1')]
@@ -176,7 +192,7 @@ describe('observed retirement', () => {
const handle = session.beginSubmission({
mode: 'queue',
text: '排队',
images: [{ previewUrl: 'blob:p1' }],
attachments: [{ type: 'image', value: { previewUrl: 'blob:p1' } }],
onRetire: retirement => retirements.push(retirement),
})
const refs = [imageRef('att-q')]
@@ -188,9 +204,31 @@ describe('observed retirement', () => {
expect(session.getSnapshot().queue).toMatchObject([{ rpcId: handle.requestId }])
})
it('retires a mixed echo with durable references in original selection order', async () => {
const { api, session } = makeSession()
api.onHistory = () => Promise.resolve(ok(historyValue([])))
await session.open()
const retirements: PendingSubmissionRetirement[] = []
const file = fileRef('file-1')
const handle = session.beginSubmission({
mode: 'queue',
text: 'mixed',
attachments: [
{ type: 'image', value: { previewUrl: 'blob:first' } },
{ type: 'file', value: file },
{ type: 'image', value: { previewUrl: 'blob:last' } },
],
onRetire: retirement => retirements.push(retirement),
})
const refs = [imageRef('image-1'), file, imageRef('image-2')]
await api.pushFollow(SID, { type: 'event', event: promptEvent(SessionSeq(0), handle.requestId, refs) as never })
await settleFrames()
expect(retirements).toEqual([{ reason: 'observed', attachments: refs }])
})
it('a full-window install (reconnect resync) retires echoes observed in the window', async () => {
const { api, session } = makeSession()
const handle = session.beginSubmission({ mode: 'queue', text: '重连', images: [] })
const handle = session.beginSubmission({ mode: 'queue', text: '重连', attachments: [] })
api.onHistory = () => Promise.resolve(ok(historyValue([promptEvent(SessionSeq(12), handle.requestId)])))
await session.open()
await settleFrames()
@@ -205,7 +243,7 @@ describe('observed retirement', () => {
const handle = session.beginSubmission({
mode: 'queue',
text: '先观察',
images: [],
attachments: [],
onRetire: retirement => retirements.push(retirement),
})
await api.pushFollow(SID, { type: 'event', event: promptEvent(SessionSeq(0), handle.requestId) as never })
@@ -222,7 +260,7 @@ describe('observed retirement', () => {
const handle = session.beginSubmission({
mode: 'queue',
text: '同一请求',
images: [],
attachments: [],
onRetire: retirement => retirements.push(retirement),
})
session.handleControlFrame({
@@ -245,7 +283,7 @@ describe('observed retirement', () => {
const { api, session } = makeSession()
api.onHistory = () => Promise.resolve(ok(historyValue([])))
await session.open()
const handle = session.beginSubmission({ mode: 'queue', text: '帧', images: [] })
const handle = session.beginSubmission({ mode: 'queue', text: '帧', attachments: [] })
await api.pushFollow(SID, { type: 'event', event: promptEvent(SessionSeq(0), handle.requestId) as never })
expect(session.getSnapshot().pendingSubmissions).toHaveLength(1)
expect(frames).toHaveLength(1)
@@ -263,13 +301,13 @@ describe('disposal', () => {
const observed = session.beginSubmission({
mode: 'queue',
text: '已观察',
images: [],
attachments: [],
onRetire: retirement => retirements.push({ text: '已观察', retirement }),
})
session.beginSubmission({
mode: 'queue',
text: '未settle',
images: [],
attachments: [],
onRetire: retirement => retirements.push({ text: '未settle', retirement }),
})
await api.pushFollow(SID, { type: 'event', event: promptEvent(SessionSeq(0), observed.requestId) as never })
@@ -15,7 +15,6 @@ const PARENT = 'fk-parent' as SessionId
afterEach(() => {
vi.unstubAllGlobals()
})
function makeSession(
api = new FakeApiClient(),
options: SessionOptions = {},
@@ -479,6 +478,29 @@ describe('prompt and cancel errors', () => {
})
})
it('rejects staged files instead of dropping them from subagent continuations', async () => {
const api = new FakeApiClient()
const session = new Session(SID, fakeRemote(api), {
address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
parentAvailable: true,
})
await session.open()
const prompted = await session.prompt([
{ type: 'file', receiptId: 'receipt' as never },
{ type: 'text', text: '继续' },
], 'queue')
expect(prompted).toMatchObject({
ok: false,
error: {
code: 'subagent/attachment-invalid',
details: { reason: 'SUBAGENT_FILE_UNSUPPORTED' },
},
})
expect(api.callsOf('subagents.prompt')).toEqual([])
})
it('sends a one-shot address to the Host under the continuable marker', async () => {
const api = new FakeApiClient()
api.onSubagentPrompt = () => Promise.resolve(err(new RemoteError(
@@ -3,6 +3,11 @@
import { SessionLogOffset } from '@deepseek-ai/dsh-session'
import type { Context } from '@deepseek-ai/cordis'
import type { ModelSelection as AgentModelSelection } from '@deepseek-ai/dsh-agent'
import type {
AdmittedPromptContentPart,
AttachmentAdmissionPart,
ImageAttachmentLimits,
} from '@deepseek-ai/dsh-attachment'
import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
import {
SessionPersistenceNotFoundError,
@@ -91,6 +96,15 @@ export interface TestSessionRemoteDefaults {
const installed = new WeakMap<Context, SessionController>()
const TEST_IMAGE_LIMITS: ImageAttachmentLimits = Object.freeze({
maxImageBytes: 5 * 1024 * 1024,
maxImagesPerMessage: 20,
maxMessageImageBytes: 100 * 1024 * 1024,
maxImagePixels: 40_000_000,
maxImageDimension: 2000,
mediaTypes: Object.freeze(['image/png'] as const),
})
/** Compact header-and-events point read a persistence double declares per session. */
interface TestSessionInspection {
readonly meta: SessionHeader
@@ -233,6 +247,29 @@ function installControllers(
},
} as never)
}
if (ctx.get('attachments') === undefined) {
ctx.provide('attachments', {
imageLimits: TEST_IMAGE_LIMITS,
admitPromptContent: async (
content: readonly AttachmentAdmissionPart[],
): Promise<AdmittedPromptContentPart[]> => {
const admitted: AdmittedPromptContentPart[] = []
for (const part of content) {
if (part.type === 'image') throw new Error('test did not configure image persistence')
admitted.push(part)
}
return admitted
},
} as never)
}
if (ctx.get('fileUploads') === undefined) {
ctx.provide('fileUploads', {
registerAgentResolver: () => () => {},
resolve: () => undefined,
bindPrompt: () => ({ commit: () => {}, [Symbol.dispose]: () => {} }),
retirePrompt: () => {},
} as never)
}
installSessionReadTestServices(ctx)
const cwd = vi.spyOn(process, 'cwd').mockReturnValue(defaults.cwd)
let controller: SessionController