Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# The generated catalog is verified byte-for-byte against its LF serializer.
src/server/services/market/catalog/skills.json text eol=lf

# Preserve the vendored source bytes checked against UPSTREAM.json on Windows.
native/agent-desktop/** text=auto eol=lf
5 changes: 5 additions & 0 deletions .github/workflows/pr-quality.yml
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,11 @@ jobs:
bun-version-file: package.json
- name: Install root dependencies
run: bun install --frozen-lockfile
- name: Install ripgrep
run: |
sudo apt-get update
sudo apt-get install -y ripgrep
rg --version
- name: Run the agent loop against a mock LLM and recorded traffic
run: bun run check:agent-e2e
- name: Upload agent e2e artifacts
Expand Down
3 changes: 3 additions & 0 deletions adapters/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

43 changes: 43 additions & 0 deletions adapters/common/__tests__/audio-transcription.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { afterEach, describe, expect, it, mock } from 'bun:test'
import { AdapterHttpClient } from '../http-client.js'

const originalFetch = globalThis.fetch
afterEach(() => { globalThis.fetch = originalFetch })

describe('IM audio transcription through the local server', () => {
it('sends bounded WAV bytes using local authentication and returns the transcript', async () => {
const client = new AdapterHttpClient('ws://127.0.0.1:3456', { localAccessToken: 'fixture-token' })
globalThis.fetch = mock(async (input, init) => {
expect(String(input)).toBe('http://127.0.0.1:3456/api/voice/transcribe')
expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer fixture-token')
expect(new Headers(init?.headers).get('Content-Type')).toBe('audio/wav')
expect(init?.redirect).toBe('error')
expect(Buffer.from(init?.body as Uint8Array).toString()).toBe('wav fixture')
return Response.json({ text: '转写结果', audioSeconds: 1 })
}) as unknown as typeof fetch
expect(await client.transcribeAudio(Buffer.from('wav fixture'))).toBe('转写结果')
})
it('rejects oversized input before fetch and propagates cancellation', async () => {
const client = new AdapterHttpClient('ws://127.0.0.1:3456', { localAccessToken: 'fixture-token' })
let calls = 0
globalThis.fetch = mock(async (_input, init) => {
calls++
return await new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(new Error('cancelled')), { once: true })
})
}) as unknown as typeof fetch
await expect(client.transcribeAudio(Buffer.alloc(4 * 1024 * 1024 + 1))).rejects.toThrow('4 MiB')
expect(calls).toBe(0)
const controller = new AbortController()
const request = client.transcribeAudio(Buffer.from('wav'), controller.signal)
controller.abort()
await expect(request).rejects.toThrow('cancelled')
})
it('surfaces missing recognizer and malformed responses instead of inventing a transcript', async () => {
const client = new AdapterHttpClient('ws://127.0.0.1:3456', { localAccessToken: 'fixture-token' })
globalThis.fetch = mock(async () => Response.json({ message: 'not ready' }, { status: 409 })) as unknown as typeof fetch
await expect(client.transcribeAudio(Buffer.from('wav'))).rejects.toThrow('409')
globalThis.fetch = mock(async () => Response.json({ text: 4 })) as unknown as typeof fetch
await expect(client.transcribeAudio(Buffer.from('wav'))).rejects.toThrow('无效结果')
})
})
132 changes: 130 additions & 2 deletions adapters/common/__tests__/chat-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,56 @@ afterEach(() => {
})

describe('ImChatRuntime authorization', () => {
it.each(['reconnect', 'send', 'download', 'lease'])('allows redelivery of the same id after a failed %s attempt', async failure => {
const { runtime, bridge, httpClient, sessionStore, dedup } = createRuntime()
sessionStore.set(CHAT_ID, 'old-session', tmpDir)
httpClient.existingSessions.add('old-session')
let failing = true
bridge.isSessionOpen = () => false
bridge.waitForOpen = async () => !(failing && failure === 'reconnect')
httpClient.acquireLeaseHook = async () => {
if (failing && failure === 'lease') throw new Error('lease failed')
}
const loadAttachments = async () => {
if (failing && failure === 'download') throw new Error('download failed')
return []
}
bridge.sendResult = failure !== 'send'
const message = { dedupKey: 'retry-same-id', hasAttachments: true, loadAttachments }
try {
await inbound(runtime, 'retry me', message)
expect(bridge.sent).toHaveLength(0)
failing = false
bridge.sendResult = true
await inbound(runtime, 'retry me', message)
await inbound(runtime, 'retry me', message)
expect(bridge.sent.map(item => item.content)).toEqual(['retry me'])
expect(httpClient.acquiredLeases).toHaveLength(2)
expect(httpClient.releasedLeases).toHaveLength(failure === 'lease' ? 0 : 1)
} finally {
dedup.destroy()
}
})

it('suppresses concurrent redelivery while the first attempt is still pending', async () => {
const { runtime, bridge, httpClient, dedup } = createRuntime()
let release!: () => void
const pending = new Promise<void>(resolve => { release = resolve })
httpClient.acquireLeaseHook = () => pending
try {
const first = inbound(runtime, 'once', { dedupKey: 'concurrent' })
await inbound(runtime, 'once', { dedupKey: 'concurrent' })
expect(httpClient.acquiredLeases).toHaveLength(1)
release()
await first
await inbound(runtime, 'once', { dedupKey: 'concurrent' })
expect(bridge.sent.map(item => item.content)).toEqual(['once'])
} finally {
release()
dedup.destroy()
}
})

it('refuses an unpaired sender and forwards nothing to the session', async () => {
writeAdapterConfig({ wecom: { pairedUsers: [], allowedUsers: [] } })
const { runtime, notices, bridge, httpClient } = createRuntime()
Expand Down Expand Up @@ -375,6 +425,60 @@ describe('ImChatRuntime inbound power activity', () => {
})

describe('ImChatRuntime session lifecycle', () => {
it.each(['/status', '/stop', '/clear'])('retries the same %s message id after the connection recovers', async command => {
const { runtime, bridge, httpClient, sessionStore, notices, dedup } = createRuntime()
sessionStore.set(CHAT_ID, 'old-session', tmpDir)
httpClient.existingSessions.add('old-session')
let online = false
bridge.isSessionOpen = () => online
bridge.waitForOpen = async () => online
try {
await inbound(runtime, command, { dedupKey: 'command-retry' })
expect(notices[0]).toContain('重试')
online = true
await inbound(runtime, command, { dedupKey: 'command-retry' })
await inbound(runtime, command, { dedupKey: 'command-retry' })
expect(notices).toHaveLength(2)
if (command === '/stop') expect(bridge.stopped).toEqual([CHAT_ID])
if (command === '/clear') expect(bridge.sent.map(item => item.content)).toEqual(['/clear'])
} finally {
dedup.destroy()
}
})

it('retains dedup after /clear was sent even if the confirmation notice fails', async () => {
const { runtime, bridge, port, dedup } = createRuntime()
try {
await inbound(runtime, 'hello')
port.sendNotice = async () => { throw new Error('notice unavailable') }
await inbound(runtime, '/clear', { dedupKey: 'clear-once' })
await inbound(runtime, '/clear', { dedupKey: 'clear-once' })
expect(bridge.sent.map(item => item.content)).toEqual(['hello', '/clear'])
} finally {
dedup.destroy()
}
})

it('retries the same permission reply id after a rejected socket send', async () => {
const { runtime, bridge, dedup } = createRuntime()
try {
await runtime.handleServerMessage(CHAT_ID, {
type: 'permission_request', requestId: 'retry-permission', toolName: 'Bash', input: {},
})
const send = bridge.sendPermissionResponse.bind(bridge)
bridge.sendPermissionResponse = () => false
await inbound(runtime, '1', { dedupKey: 'permission-retry' })
expect(bridge.permissionResponses).toHaveLength(0)
bridge.sendPermissionResponse = send
await inbound(runtime, '1', { dedupKey: 'permission-retry' })
await inbound(runtime, '1', { dedupKey: 'permission-retry' })
expect(bridge.permissionResponses).toEqual([{ requestId: 'retry-permission', allowed: true, rule: undefined }])
expect(bridge.sent).toHaveLength(0)
} finally {
dedup.destroy()
}
})

it.each(['/status', '/stop', '/clear'])('reports a retryable disconnect for %s without changing the binding', async (command) => {
const { runtime, bridge, httpClient, sessionStore, notices } = createRuntime()
sessionStore.set(CHAT_ID, 'old-session', path.join(tmpDir, 'original-project'))
Expand Down Expand Up @@ -541,6 +645,26 @@ describe('ImChatRuntime server stream', () => {
expect(notices.filter(notice => notice.includes('ask-1'))).toHaveLength(1)
})

it('retries an undelivered approval after a reconnect snapshot without inflating pending count', async () => {
const { runtime, port, notices, dedup } = createRuntime()
const request = { type: 'permission_request', requestId: 'retry-prompt', toolName: 'Bash', input: {} }
const send = port.sendNotice
let failing = true
port.sendNotice = async (chatId, text) => {
if (failing) throw new Error('platform offline')
await send(chatId, text)
}
try {
await expect(runtime.handleServerMessage(CHAT_ID, request)).rejects.toThrow('platform offline')
await runtime.handleServerMessage(CHAT_ID, { type: 'permission_requests_snapshot', toolRequestIds: [request.requestId], turnActive: true })
failing = false
await runtime.handleServerMessage(CHAT_ID, request)
await runtime.handleServerMessage(CHAT_ID, request)
expect(notices.filter(text => text.includes(request.requestId))).toHaveLength(1)
expect(runtime.getRuntimeState(CHAT_ID).pendingPermissionCount).toBe(1)
} finally { dedup.destroy() }
})

it('routes a numeric reply to the single pending permission request', async () => {
const { runtime, bridge } = createRuntime()

Expand Down Expand Up @@ -635,8 +759,12 @@ describe('ImChatRuntime server stream', () => {
text: `![inside](${insidePath}) ![outside](/etc/hosts)`,
})
await runtime.handleServerMessage(CHAT_ID, { type: 'message_complete' })
// The upload is dispatched without blocking the stream.
await new Promise((resolve) => setTimeout(resolve, 20))
// The upload is dispatched without blocking the stream. Wait for its
// observable result rather than depending on a 20 ms filesystem deadline.
const uploadDeadline = Date.now() + 2000
while (images.length === 0 && Date.now() < uploadDeadline) {
await new Promise((resolve) => setTimeout(resolve, 5))
}

expect(images).toEqual([{ mime: 'image/png', alt: 'inside' }])
})
Expand Down
31 changes: 31 additions & 0 deletions adapters/common/__tests__/format.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,37 @@ describe('splitMessage', () => {
expect(chunks.every((c) => c.length <= 20)).toBe(true)
})

it('keeps supplementary Unicode characters intact at hard split boundaries', () => {
for (const text of ['abc🙂def𠮷ghi', '🙂'.repeat(8), 'a𐐷🙂b中🙂文']) {
for (let limit = 2; limit <= 9; limit += 1) {
const chunks = splitMessage(text, limit)
expect(chunks.join('')).toBe(text)
for (const chunk of chunks) {
expect(chunk.length).toBeLessThanOrEqual(limit)
expect(Buffer.from(chunk, 'utf8').toString('utf8')).toBe(chunk)
}
}
}
})

it('makes progress with whole code points when limit one cannot hold a surrogate pair', () => {
expect(splitMessage('a🙂b𐐷', 1)).toEqual(['a', '🙂', 'b', '𐐷'])
})

it('does not exceed the budget to include a sentence delimiter', () => {
const text = 'abcd. efgh'
const chunks = splitMessage(text, 4)
expect(chunks.every((chunk) => chunk.length <= 4)).toBe(true)
expect(chunks.join('').replace(/\s/g, '')).toBe(text.replace(/\s/g, ''))
})

it('keeps paragraph, line, sentence, and word splitting priorities', () => {
expect(splitMessage('🙂 first\n\nsecond. third last', 22)[0]).toBe('🙂 first')
expect(splitMessage('🙂 first\nsecond. third last', 22)[0]).toBe('🙂 first')
expect(splitMessage('🙂 first. second third last', 22)[0]).toBe('🙂 first.')
expect(splitMessage('🙂 first second third last', 22)[0]).toBe('🙂 first second third')
})

it('preserves all content after splitting', () => {
const text = 'Hello world. This is a test. Foo bar baz.'
const chunks = splitMessage(text, 15)
Expand Down
12 changes: 6 additions & 6 deletions adapters/common/__tests__/http-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,9 +382,9 @@ describe('AdapterHttpClient', () => {

expect(result.sessions.map((session) => session.id)).toEqual(['session-1'])
expect(result.total).toBe(2)
expect((globalThis.fetch as any).mock.calls[0][0]).toBe(
`http://127.0.0.1:3456/api/sessions?project=${encodeURIComponent(rootDir)}&limit=10&offset=5`,
)
const requested = new URL((globalThis.fetch as any).mock.calls[0][0])
expect(`${requested.origin}${requested.pathname}`).toBe('http://127.0.0.1:3456/api/sessions')
expect([...requested.searchParams]).toEqual([['project', rootDir], ['limit', '10'], ['offset', '5']])
} finally {
fs.rmSync(rootDir, { recursive: true, force: true })
}
Expand Down Expand Up @@ -494,9 +494,9 @@ describe('AdapterHttpClient', () => {
const result = await client.listSkills(rootDir)

expect(result.skills[0]?.name).toBe('reviewer')
expect((globalThis.fetch as any).mock.calls[0][0]).toBe(
`http://127.0.0.1:3456/api/skills?cwd=${encodeURIComponent(fs.realpathSync(rootDir))}`,
)
const requested = new URL((globalThis.fetch as any).mock.calls[0][0])
expect(`${requested.origin}${requested.pathname}`).toBe('http://127.0.0.1:3456/api/skills')
expect([...requested.searchParams]).toEqual([['cwd', fs.realpathSync(rootDir)]])
} finally {
fs.rmSync(rootDir, { recursive: true, force: true })
}
Expand Down
8 changes: 8 additions & 0 deletions adapters/common/__tests__/message-dedup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,19 @@ describe('MessageDedup', () => {
expect(dedup.tryRecord('msg-1')).toBe(false)
})

it('does not record a message when only checking accepted ids', () => {
expect(dedup.has('retryable')).toBe(false)
expect(dedup.has('retryable')).toBe(false)
expect(dedup.tryRecord('retryable')).toBe(true)
expect(dedup.has('retryable')).toBe(true)
})

it('allows same ID after TTL expires', async () => {
const shortDedup = new MessageDedup(50, 100) // 50ms TTL
expect(shortDedup.tryRecord('msg-1')).toBe(true)
expect(shortDedup.tryRecord('msg-1')).toBe(false)
await new Promise((r) => setTimeout(r, 60))
expect(shortDedup.has('msg-1')).toBe(false)
expect(shortDedup.tryRecord('msg-1')).toBe(true)
shortDedup.destroy()
})
Expand Down
40 changes: 39 additions & 1 deletion adapters/common/__tests__/permission-sync.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'bun:test'
import { syncImPermissionState } from '../permission-sync.js'
import { deliverImPermissionPrompt, syncImPermissionState } from '../permission-sync.js'

function harness() {
const runtime = { state: 'permission_pending' as 'idle' | 'thinking' | 'streaming' | 'tool_executing' | 'permission_pending', pendingPermissionCount: 2 }
Expand All @@ -8,6 +8,44 @@ function harness() {
}

describe('IM approval reconciliation for restored sessions (#1286)', () => {
it('retries failed delivery after a snapshot and deduplicates successful delivery across snapshots', async () => {
const { runtime, pending } = harness()
let attempts = 0
const deliver = async () => {
attempts++
if (attempts === 1) throw new Error('offline')
}
await expect(deliverImPermissionPrompt('chat', 'first', runtime, pending, deliver)).rejects.toThrow('offline')
const snapshot = { type: 'permission_requests_snapshot', toolRequestIds: ['first'], turnActive: true }
syncImPermissionState('chat', snapshot, runtime, pending)
await deliverImPermissionPrompt('chat', 'first', runtime, pending, deliver)
syncImPermissionState('chat', snapshot, runtime, pending)
await deliverImPermissionPrompt('chat', 'first', runtime, pending, deliver)
expect(attempts).toBe(2)
expect(runtime.pendingPermissionCount).toBe(1)
})

it.each(['resolution', 'snapshot', 'reset'])('does not resurrect a request removed by %s while delivery waits', async removal => {
const { runtime, pending } = harness()
let release!: () => void
const gate = new Promise<void>(resolve => { release = resolve })
let sends = 0
const delivery = deliverImPermissionPrompt('chat', 'first', runtime, pending, async isCurrent => {
await gate
if (isCurrent()) sends++
throw new Error('interrupted')
})
await deliverImPermissionPrompt('chat', 'first', runtime, pending, async () => { sends++ })
if (removal === 'reset') pending.delete('chat')
else syncImPermissionState('chat', removal === 'resolution'
? { type: 'permission_resolved', permissionType: 'tool', requestId: 'first' }
: { type: 'permission_requests_snapshot', toolRequestIds: [], turnActive: false }, runtime, pending)
release()
await expect(delivery).rejects.toThrow('interrupted')
expect(sends).toBe(0)
expect(pending.get('chat')?.has('first') ?? false).toBe(false)
})

it('removes approvals answered in Desktop, without decrementing twice', () => {
const { runtime, pending } = harness()
const resolved = { type: 'permission_resolved', permissionType: 'tool', requestId: 'first' }
Expand Down
7 changes: 7 additions & 0 deletions adapters/common/__tests__/permission.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,11 @@ describe('permission helpers', () => {
expect(formatPermissionDecisionStatus({ allowed: true, rule: 'always' })).toContain('永久允许')
expect(formatPermissionDecisionStatus({ allowed: false })).toContain('拒绝')
})
it('uses only numeric instructions for one pending request and explicit commands for multiple', () => {
expect(formatPermissionInstructions('req-1', { pendingCount: 1 })).toBe('回复 1 允许一次,2 永久允许,3 拒绝。')
const multiple = formatPermissionInstructions('req-2', { pendingCount: 2 })
expect(multiple).toContain('多个待审批请求')
expect(multiple).not.toContain('回复 1')
for (const action of ['allow', 'always', 'deny']) expect(multiple).toContain(`/${action} req-2`)
})
})
Loading
Loading