Merge remote-tracking branch 'origin/master' into xtr/session-store-write-lifecycle
# Conflicts: # apps/web/tests/new-session-refused.e2e.ts # docs/event-producer-consumer.md # docs/event-producer-consumer.zh.md
This commit is contained in:
commit
e7ffab7902
339 files changed
+4943
-1504
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { Context, FiberState } from '@deepseek-ai/cordis'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import AgentController from '@deepseek-ai/dsh-agent-controller'
|
||||
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
||||
import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import type { Agent, ModelSelectionRef } from '@deepseek-ai/dsh-agent'
|
||||
@@ -38,6 +39,7 @@ async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
await ctx.plugin(AgentController)
|
||||
await ctx.plugin(CommandRuntime)
|
||||
const session = ctx.sessions.create(SESSION, {
|
||||
meta: { cwd: '/workspace', ...(origin === undefined ? {} : { origin }) },
|
||||
@@ -99,6 +101,8 @@ async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
selectionFor: () => selection,
|
||||
serializeImageAdmission: <Value>(_agent: Agent, operation: () => Promise<Value>) => operation(),
|
||||
} as unknown as ApiSessionAgentController
|
||||
// Image prompts take their admission turn at once; no model selection competes in these tests.
|
||||
Object.assign(agents, { acquireImageAdmission: () => Promise.resolve(() => {}) })
|
||||
const uploads = new FileUploads(ctx)
|
||||
if (uploadRoute === undefined) throw new Error('file upload route was not registered')
|
||||
return {
|
||||
@@ -117,6 +121,8 @@ async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
|
||||
/** The owner source `SessionController.prompt()` builds for {@link promptRequest}. */
|
||||
const USER_SOURCE: MessageSource = { kind: 'user', rpcId: 'req-1' as SessionRequestId }
|
||||
/** A client that stays connected for the whole prompt. */
|
||||
const SIGNAL = new AbortController().signal
|
||||
|
||||
function promptRequest(content: Parameters<SessionCommandController['prompt']>[0]['content']) {
|
||||
return {
|
||||
@@ -168,7 +174,7 @@ describe('Session file uploads', () => {
|
||||
{ type: 'file', receiptId: receipt.receiptId },
|
||||
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
|
||||
{ type: 'text', text: 'read it' },
|
||||
]), USER_SOURCE)
|
||||
]), USER_SOURCE, SIGNAL)
|
||||
expect(followup).toHaveBeenCalledTimes(1)
|
||||
const message = followup.mock.calls[0]?.[0] as UserMessage
|
||||
expect(message.content).toEqual([
|
||||
@@ -195,7 +201,7 @@ describe('Session file uploads', () => {
|
||||
name: 'huge.bin',
|
||||
}))
|
||||
expect(receipt.file).toMatchObject({ name: 'huge.bin', bytes: 5 })
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
expect((followup.mock.calls[0]?.[0] as UserMessage).content).toEqual([
|
||||
{ type: 'file', attachment: receipt.file },
|
||||
])
|
||||
@@ -222,7 +228,7 @@ describe('Session file uploads', () => {
|
||||
await expect(controller.prompt(promptRequest([
|
||||
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
|
||||
{ type: 'file', receiptId: 'missing-receipt' as FileUploadReceiptId },
|
||||
]), USER_SOURCE)).rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'FILE_NOT_STAGED' } })
|
||||
]), USER_SOURCE, SIGNAL)).rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'FILE_NOT_STAGED' } })
|
||||
expect(followup).not.toHaveBeenCalled()
|
||||
expect(saveImages).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -320,7 +326,7 @@ describe('Session file uploads', () => {
|
||||
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 }]), USER_SOURCE)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
uploads.retirePrompt(agent, 'other-request')
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
@@ -335,7 +341,7 @@ describe('Session file uploads', () => {
|
||||
{ data: 'AAAA' },
|
||||
new AbortController().signal,
|
||||
)
|
||||
await first.controller.prompt(promptRequest([{ type: 'file', receiptId: observed.receiptId }]), USER_SOURCE)
|
||||
await first.controller.prompt(promptRequest([{ type: 'file', receiptId: observed.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
first.agent.session.append('user/message', createUserMessage({
|
||||
content: [{ type: 'text', text: 'extension event' }],
|
||||
source: { kind: 'user', rpcId: 1 } as never,
|
||||
@@ -360,9 +366,9 @@ describe('Session file uploads', () => {
|
||||
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, USER_SOURCE)
|
||||
await controller.prompt(request, USER_SOURCE, SIGNAL)
|
||||
agent.inbox.append('next-turn', followup.mock.calls[0]?.[0] as UserMessage)
|
||||
await expect(controller.prompt(request, USER_SOURCE)).resolves.toEqual({ accepted: true })
|
||||
await expect(controller.prompt(request, USER_SOURCE, SIGNAL)).resolves.toEqual({ accepted: true })
|
||||
expect(followup).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
@@ -379,7 +385,7 @@ describe('Session file uploads', () => {
|
||||
source: { kind: 'user', rpcId: request.requestId },
|
||||
}), { surfaceOp: 'append' })
|
||||
|
||||
await expect(controller.prompt(request, USER_SOURCE)).resolves.toEqual({ accepted: true })
|
||||
await expect(controller.prompt(request, USER_SOURCE, SIGNAL)).resolves.toEqual({ accepted: true })
|
||||
expect(followup).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -389,7 +395,7 @@ describe('Session file uploads', () => {
|
||||
saveImages.mockReturnValueOnce(admitted.promise)
|
||||
const prompting = controller.prompt(promptRequest([
|
||||
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
|
||||
]), USER_SOURCE)
|
||||
]), USER_SOURCE, SIGNAL)
|
||||
await vi.waitFor(() => { expect(saveImages).toHaveBeenCalledOnce() })
|
||||
await disposeAgent()
|
||||
admitted.resolve([{
|
||||
@@ -401,7 +407,7 @@ describe('Session file uploads', () => {
|
||||
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 }]), USER_SOURCE)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
const admitted = Promise.withResolvers<readonly ImageAttachmentRef[]>()
|
||||
saveImages.mockReturnValueOnce(admitted.promise)
|
||||
const prompting = controller.prompt({
|
||||
@@ -410,7 +416,7 @@ describe('Session file uploads', () => {
|
||||
{ type: 'image', mediaType: 'image/png', data: 'AAAA' },
|
||||
]),
|
||||
requestId: 'req-2' as SessionRequestId,
|
||||
}, USER_SOURCE)
|
||||
}, USER_SOURCE, SIGNAL)
|
||||
await vi.waitFor(() => { expect(saveImages).toHaveBeenCalledOnce() })
|
||||
uploads.retirePrompt(agent, 'req-1')
|
||||
admitted.resolve([{
|
||||
@@ -424,12 +430,12 @@ describe('Session file uploads', () => {
|
||||
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 }]), USER_SOURCE)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
followup.mockImplementationOnce(() => { throw new Error('busy') })
|
||||
await expect(controller.prompt({
|
||||
...promptRequest([{ type: 'file', receiptId: receipt.receiptId }]),
|
||||
requestId: 'req-2' as SessionRequestId,
|
||||
}, USER_SOURCE)).rejects.toMatchObject({ code: 'session/agent-busy' })
|
||||
}, USER_SOURCE, SIGNAL)).rejects.toMatchObject({ code: 'session/agent-busy' })
|
||||
uploads.retirePrompt(agent, 'req-1')
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toBeUndefined()
|
||||
})
|
||||
@@ -440,7 +446,7 @@ describe('Session file uploads', () => {
|
||||
followup.mockImplementationOnce(() => { throw new Error('busy') })
|
||||
await expect(controller.prompt(promptRequest([
|
||||
{ type: 'file', receiptId: receipt.receiptId },
|
||||
]), USER_SOURCE)).rejects.toMatchObject({ code: 'session/agent-busy' })
|
||||
]), USER_SOURCE, SIGNAL)).rejects.toMatchObject({ code: 'session/agent-busy' })
|
||||
uploads.retirePrompt(agent, 'req-1')
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
})
|
||||
@@ -448,7 +454,7 @@ describe('Session file uploads', () => {
|
||||
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 }]), USER_SOURCE)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE, SIGNAL)
|
||||
const queued = followup.mock.calls[0]?.[0] as UserMessage
|
||||
agent.inbox.append('next-turn', queued)
|
||||
expect(await controller.updateQueue({
|
||||
@@ -469,7 +475,7 @@ describe('Session file uploads', () => {
|
||||
await controller.prompt(promptRequest([
|
||||
{ type: 'file', receiptId: first.receiptId },
|
||||
{ type: 'file', receiptId: second.receiptId },
|
||||
]), USER_SOURCE)
|
||||
]), USER_SOURCE, SIGNAL)
|
||||
|
||||
const message = followup.mock.calls[0]?.[0] as UserMessage
|
||||
expect(message.content).toEqual([
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* Session prompts through the Agent controller's admission stage: how the
|
||||
* `session/prompt` Remote reports a held, refused, or failed admission to the
|
||||
* client.
|
||||
*/
|
||||
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import SessionStore from '@deepseek-ai/dsh-session'
|
||||
import type { UserMessage } from '@deepseek-ai/dsh-session'
|
||||
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
|
||||
import type { SessionPromptRequest, SessionRequestId } from '../src/types.ts'
|
||||
import { createSessionTestRemote } from './test-remote.ts'
|
||||
|
||||
let nextRequestId = 1
|
||||
|
||||
async function harness(options: { readonly refusal?: Error } = {}) {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SessionProjectionRegistry)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
const session = ctx.sessions.create()
|
||||
const inbox = createInboxStub()
|
||||
const deliver = (target: 'next-turn' | 'next-step', message: UserMessage): void => {
|
||||
if (options.refusal !== undefined) throw options.refusal
|
||||
inbox.append(target, message)
|
||||
}
|
||||
const agent: Agent = {
|
||||
id: session.id,
|
||||
options: {},
|
||||
session,
|
||||
inbox,
|
||||
status: 'idle',
|
||||
ctx,
|
||||
send: () => {},
|
||||
followup: (message) => { deliver('next-turn', message) },
|
||||
steer: (message) => { deliver('next-step', message) },
|
||||
inject: () => {},
|
||||
cancel: () => {},
|
||||
runMaintenance: task => task(new AbortController().signal),
|
||||
whenIdle: () => Promise.resolve(),
|
||||
}
|
||||
const unregister = await ctx.agents.register(agent)
|
||||
const remote = await createSessionTestRemote(ctx, {
|
||||
defaultModelSelection: () => ({ provider: 'fixture', model: 'fixture-model' }),
|
||||
cwd: '/tmp',
|
||||
})
|
||||
const prompt = (text: string, mode: SessionPromptRequest['mode'] = 'queue', requestId?: SessionRequestId) => ({
|
||||
requestId: requestId ?? `admission-${String(nextRequestId++)}` as SessionRequestId,
|
||||
sessionId: session.id,
|
||||
mode,
|
||||
content: [{ type: 'text' as const, text }],
|
||||
})
|
||||
return { ctx, agent, inbox, remote, prompt, unregister }
|
||||
}
|
||||
|
||||
function textsOf(messages: readonly UserMessage[]): string[] {
|
||||
return messages.map(message => message.content.map(block => block.type === 'text' ? block.text : '').join(''))
|
||||
}
|
||||
|
||||
describe('Session prompt admission', () => {
|
||||
it('admits a queued prompt into the next turn and a steered one into the next step', async () => {
|
||||
const { ctx, agent, inbox, remote, prompt } = await harness()
|
||||
const admitted: Agent[] = []
|
||||
ctx.on('agent-controller/admission', async ({ agent: subject }, next) => {
|
||||
admitted.push(subject)
|
||||
return await next()
|
||||
})
|
||||
|
||||
expect(await remote.prompt(prompt('later'))).toEqual({ ok: true, value: { accepted: true } })
|
||||
expect(await remote.prompt(prompt('now', 'steer'))).toEqual({ ok: true, value: { accepted: true } })
|
||||
expect(admitted).toEqual([agent, agent])
|
||||
expect(textsOf(inbox.nextTurn)).toEqual(['later'])
|
||||
expect(textsOf(inbox.nextStep)).toEqual(['now'])
|
||||
})
|
||||
|
||||
it('keeps the prompt call open while a listener holds it', async () => {
|
||||
const { ctx, inbox, remote, prompt } = await harness()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
ctx.on('agent-controller/admission', async (_admission, next) => {
|
||||
await release.promise
|
||||
return await next()
|
||||
})
|
||||
|
||||
let settled = false
|
||||
const pending = remote.prompt(prompt('held')).finally(() => { settled = true })
|
||||
await new Promise<void>((resolve) => { setImmediate(resolve) })
|
||||
expect(settled).toBe(false)
|
||||
expect(inbox.nextTurn).toEqual([])
|
||||
release.resolve(undefined)
|
||||
expect(await pending).toEqual({ ok: true, value: { accepted: true } })
|
||||
expect(textsOf(inbox.nextTurn)).toEqual(['held'])
|
||||
})
|
||||
|
||||
it('returns a refusal with its reason and whether its plugin presents it, and keeps the inbox untouched', async () => {
|
||||
const { ctx, inbox, remote, prompt } = await harness()
|
||||
let presented = true
|
||||
ctx.on('agent-controller/admission', () => Promise.resolve({
|
||||
kind: 'reject' as const, reason: 'fixture/worktree-missing', message: 'The worktree was removed.', presented,
|
||||
}))
|
||||
|
||||
expect(await remote.prompt(prompt('refused'))).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'session/prompt-rejected',
|
||||
message: 'The worktree was removed.',
|
||||
details: { reason: 'fixture/worktree-missing', presented: true },
|
||||
},
|
||||
})
|
||||
presented = false
|
||||
expect(await remote.prompt(prompt('refused again'))).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/prompt-rejected', details: { reason: 'fixture/worktree-missing', presented: false } },
|
||||
})
|
||||
expect(inbox.nextTurn).toEqual([])
|
||||
})
|
||||
|
||||
it('reports a failed listener as a refusal the client explains', async () => {
|
||||
const { ctx, inbox, remote, prompt } = await harness()
|
||||
ctx.on('agent-controller/admission', () => Promise.reject(new Error('listener broke')))
|
||||
|
||||
const result = await remote.prompt(prompt('broken'))
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/prompt-rejected', details: { reason: 'agent-controller/admission-failed', presented: false } },
|
||||
})
|
||||
expect(result.ok ? '' : result.error.message).toContain('listener broke')
|
||||
expect(inbox.nextTurn).toEqual([])
|
||||
})
|
||||
|
||||
it('cancels a held prompt whose client went away', async () => {
|
||||
const { ctx, inbox, remote, prompt } = await harness()
|
||||
ctx.on('agent-controller/admission', async ({ signal }, next) => {
|
||||
await new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => { reject(signal.reason as Error) }, { once: true })
|
||||
})
|
||||
return await next()
|
||||
})
|
||||
|
||||
const client = new AbortController()
|
||||
const pending = remote.prompt(prompt('abandoned'), client.signal)
|
||||
await new Promise<void>((resolve) => { setImmediate(resolve) })
|
||||
client.abort(new Error('client left'))
|
||||
expect(await pending).toMatchObject({ ok: false, error: { code: 'gateway/cancelled' } })
|
||||
expect(inbox.nextTurn).toEqual([])
|
||||
})
|
||||
|
||||
it('reports a Session whose Agent was disposed while its prompt was held as not found', async () => {
|
||||
const { ctx, agent, remote, prompt, unregister } = await harness()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
ctx.on('agent-controller/admission', async (_admission, next) => {
|
||||
await release.promise
|
||||
return await next()
|
||||
})
|
||||
|
||||
const pending = remote.prompt(prompt('orphaned'))
|
||||
await new Promise<void>((resolve) => { setImmediate(resolve) })
|
||||
await unregister()
|
||||
release.resolve(undefined)
|
||||
expect(await pending).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/not-found', details: { sessionId: agent.id } },
|
||||
})
|
||||
})
|
||||
|
||||
it('maps a refusal from another copy of the agent-controller module by its code', async () => {
|
||||
const { ctx, agent, remote, prompt } = await harness()
|
||||
// Another copy of the module raises the same fields from its own class.
|
||||
const refusal = (reason: string): Error => Object.assign(new Error('The worktree was removed.'), {
|
||||
name: 'AgentAdmissionRejected', code: 'AGENT_ADMISSION_REJECTED', reason, presented: true,
|
||||
})
|
||||
vi.spyOn(ctx.agentController, 'deliver')
|
||||
.mockRejectedValueOnce(refusal('fixture/worktree-missing'))
|
||||
.mockRejectedValueOnce(refusal('agent-controller/agent-gone'))
|
||||
|
||||
expect(await remote.prompt(prompt('refused'))).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'session/prompt-rejected',
|
||||
message: 'The worktree was removed.',
|
||||
details: { reason: 'fixture/worktree-missing', presented: true },
|
||||
},
|
||||
})
|
||||
expect(await remote.prompt(prompt('orphaned'))).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/not-found', details: { sessionId: agent.id } },
|
||||
})
|
||||
})
|
||||
|
||||
it('acknowledges a repeated request without admitting it again', async () => {
|
||||
const { ctx, inbox, remote, prompt } = await harness()
|
||||
let admissions = 0
|
||||
ctx.on('agent-controller/admission', async (_admission, next) => {
|
||||
admissions += 1
|
||||
return await next()
|
||||
})
|
||||
|
||||
const first = prompt('once')
|
||||
expect(await remote.prompt(first)).toEqual({ ok: true, value: { accepted: true } })
|
||||
expect(await remote.prompt(prompt('once', 'queue', first.requestId))).toEqual({ ok: true, value: { accepted: true } })
|
||||
expect(admissions).toBe(1)
|
||||
expect(textsOf(inbox.nextTurn)).toEqual(['once'])
|
||||
})
|
||||
|
||||
it('reports the Agent refusing to queue a prompt as busy', async () => {
|
||||
const { remote, prompt } = await harness({ refusal: new Error('inbox closed') })
|
||||
|
||||
expect(await remote.prompt(prompt('rejected'))).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/agent-busy', details: { reason: 'Error: inbox closed' } },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -137,6 +137,46 @@ async function harness(logged?: {
|
||||
return { ctx, agent, sessionId: session.id }
|
||||
}
|
||||
|
||||
/** An image store whose saved attachments are one-pixel PNGs. */
|
||||
function provideImageStore(ctx: Context): void {
|
||||
const attachments = {
|
||||
imageLimits: {
|
||||
maxImageBytes: 4,
|
||||
maxImagesPerMessage: 2,
|
||||
maxMessageImageBytes: 4,
|
||||
maxImagePixels: 4,
|
||||
maxImageDimension: 2000,
|
||||
mediaTypes: ['image/png'],
|
||||
},
|
||||
validateImage: () => Promise.resolve(),
|
||||
saveImage: (input: { data: Uint8Array; mediaType: 'image/png' }) => Promise.resolve({
|
||||
attachmentId: `att-${String(input.data[0])}`, mediaType: input.mediaType, bytes: input.data.byteLength, width: 1, height: 1,
|
||||
}),
|
||||
}
|
||||
ctx.provide('attachments', Object.setPrototypeOf(attachments, AttachmentStore.prototype) as never)
|
||||
}
|
||||
|
||||
/** A queued prompt with its text, after a one-pixel image when `withImage` is set. */
|
||||
function imagePrompt(sessionId: SessionId, text: string, withImage: boolean): SessionPromptRequest {
|
||||
return promptRequest({
|
||||
sessionId,
|
||||
mode: 'queue',
|
||||
content: [
|
||||
...withImage ? [{ type: 'image' as const, mediaType: 'image/png' as const, data: 'AQ==' }] : [],
|
||||
{ type: 'text' as const, text },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
function textOf(message: UserMessage): string {
|
||||
return message.content.map(block => block.type === 'text' ? block.text : '').join('')
|
||||
}
|
||||
|
||||
/** Let pending prompts run as far as they can. */
|
||||
async function settle(): Promise<void> {
|
||||
await new Promise<void>((resolve) => { setImmediate(resolve) })
|
||||
}
|
||||
|
||||
function expectValue<T>(result: { ok: true; value: T } | { ok: false }): T {
|
||||
if (!result.ok) throw new Error('expected successful response')
|
||||
return result.value
|
||||
@@ -313,6 +353,110 @@ describe('Web session model selection', () => {
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('admits image prompts in arrival order behind an image prompt that a listener holds', async () => {
|
||||
const { ctx, agent, sessionId } = await harness()
|
||||
provideImageStore(ctx)
|
||||
const followed: string[] = []
|
||||
Object.assign(agent, { followup: (message: UserMessage) => { followed.push(textOf(message)) } })
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
ctx.on('agent-controller/admission', async ({ message }, next) => {
|
||||
if (textOf(message) === 'held') await release.promise
|
||||
return await next()
|
||||
})
|
||||
const remote = await createSessionTestRemote(ctx, {
|
||||
defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
|
||||
cwd: '/tmp',
|
||||
})
|
||||
|
||||
const prompts = [
|
||||
remote.prompt(imagePrompt(sessionId, 'held', true)),
|
||||
remote.prompt(imagePrompt(sessionId, 'second image', true)),
|
||||
remote.prompt(imagePrompt(sessionId, 'third text', false)),
|
||||
]
|
||||
await settle()
|
||||
expect(followed).toEqual([])
|
||||
release.resolve(undefined)
|
||||
expect((await Promise.all(prompts)).map(result => result.ok)).toEqual([true, true, true])
|
||||
expect(followed).toEqual(['held', 'second image', 'third text'])
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('keeps a model selection behind the image prompt being admitted but not behind one still queued', async () => {
|
||||
const { ctx, agent, sessionId } = await harness()
|
||||
registerTextOnly(ctx)
|
||||
provideImageStore(ctx)
|
||||
const events: string[] = []
|
||||
Object.assign(agent, { followup: (message: UserMessage) => { events.push(`admitted ${textOf(message)}`) } })
|
||||
const releases = new Map([['held image', Promise.withResolvers<undefined>()], ['held text', Promise.withResolvers<undefined>()]])
|
||||
ctx.on('agent-controller/admission', async ({ message }, next) => {
|
||||
await releases.get(textOf(message))?.promise
|
||||
return await next()
|
||||
})
|
||||
const remote = await createSessionTestRemote(ctx, {
|
||||
defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
|
||||
cwd: '/tmp',
|
||||
})
|
||||
const select = () => remote.selectModel(request({ sessionId, provider: 'text-only', model: 'plain' }))
|
||||
.then((result) => { events.push('selected'); return result })
|
||||
|
||||
// A held image prompt was checked against the current model, so the selection waits for its append.
|
||||
const heldImage = remote.prompt(imagePrompt(sessionId, 'held image', true))
|
||||
await settle()
|
||||
const first = select()
|
||||
await settle()
|
||||
expect(events).toEqual([])
|
||||
releases.get('held image')?.resolve(undefined)
|
||||
expect((await heldImage).ok).toBe(true)
|
||||
expect((await first).ok).toBe(true)
|
||||
expect(events).toEqual(['admitted held image', 'selected'])
|
||||
|
||||
// An image prompt queued behind a held text prompt has not been checked yet, so the selection does not wait for it.
|
||||
const heldText = remote.prompt(imagePrompt(sessionId, 'held text', false))
|
||||
const queuedImage = remote.prompt(imagePrompt(sessionId, 'queued image', true))
|
||||
await settle()
|
||||
expect((await select()).ok).toBe(true)
|
||||
expect(events).toEqual(['admitted held image', 'selected', 'selected'])
|
||||
releases.get('held text')?.resolve(undefined)
|
||||
expect((await heldText).ok).toBe(true)
|
||||
expect(await queuedImage).toMatchObject({
|
||||
ok: false, error: { code: 'session/attachment-invalid', details: { reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' } },
|
||||
})
|
||||
expect(events).toEqual(['admitted held image', 'selected', 'selected', 'admitted held text'])
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('passes the image admission turn on when the sender of a waiting image prompt leaves', async () => {
|
||||
const { ctx, agent, sessionId } = await harness()
|
||||
provideImageStore(ctx)
|
||||
const followed: string[] = []
|
||||
Object.assign(agent, { followup: (message: UserMessage) => { followed.push(textOf(message)) } })
|
||||
const listing = Promise.withResolvers<readonly LlmModelInfo[]>()
|
||||
ctx.llm.registerAdapter(['gated'], new class extends CatalogAdapter {
|
||||
override listModels(): Promise<readonly LlmModelInfo[]> {
|
||||
return listing.promise
|
||||
}
|
||||
}('Gated', []))
|
||||
const remote = await createSessionTestRemote(ctx, {
|
||||
defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
|
||||
cwd: '/tmp',
|
||||
})
|
||||
|
||||
// The selection holds the image admission turn while the provider lists its models.
|
||||
const selection = remote.selectModel(request({ sessionId, provider: 'gated', model: 'slow' }))
|
||||
await settle()
|
||||
const sender = new AbortController()
|
||||
const leaving = remote.prompt(imagePrompt(sessionId, 'left', true), sender.signal)
|
||||
await settle()
|
||||
sender.abort(new Error('client left'))
|
||||
expect(await leaving).toMatchObject({ ok: false, error: { code: 'gateway/cancelled' } })
|
||||
|
||||
listing.resolve([{ provider: 'gated', id: 'slow', name: 'Slow' }])
|
||||
expect((await selection).ok).toBe(true)
|
||||
expect((await remote.prompt(imagePrompt(sessionId, 'after', true))).ok).toBe(true)
|
||||
expect(followed).toEqual(['after'])
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('authorizes attachment bytes only when the session event stream references the id', async () => {
|
||||
const { ctx, agent, sessionId } = await harness()
|
||||
const ref = {
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
remoteErrorOf,
|
||||
type RemoteResult,
|
||||
} from '@deepseek-ai/dsh-typert-protocol'
|
||||
import AgentController from '@deepseek-ai/dsh-agent-controller'
|
||||
import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access'
|
||||
import SessionController from '../src/index.ts'
|
||||
import type {
|
||||
@@ -293,6 +294,7 @@ async function installControllers(
|
||||
} as never)
|
||||
}
|
||||
installSessionReadTestServices(ctx)
|
||||
if (ctx.get('agentController') === undefined) new AgentController(ctx)
|
||||
if (ctx.get('remoteAccess') === undefined) new RemoteAccessService(ctx)
|
||||
const cwd = vi.spyOn(process, 'cwd').mockReturnValue(defaults.cwd)
|
||||
class TestController extends SessionController {
|
||||
|
||||
Reference in new issue
Block a user