Skip to content
Merged
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
16 changes: 15 additions & 1 deletion admin-ui/src/pages/CapturePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { useToast } from '../lib/toast'
interface CaptureEntry {
id: number
timestamp: number
durationMs: number | null
source: string
protocol: string
model: string
Expand Down Expand Up @@ -73,6 +74,15 @@ function fmtSize(s: string | null): string {
return b + 'B'
}

function fmtDuration(ms: number | null): string {
if (ms == null) return '—'
if (ms < 1000) return `${ms} ms`
if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 2 : 1)} s`
const minutes = Math.floor(ms / 60_000)
const seconds = ((ms % 60_000) / 1000).toFixed(1)
return `${minutes}m ${seconds}s`
}

async function readSSE(
response: Response,
signal: AbortSignal,
Expand Down Expand Up @@ -372,6 +382,7 @@ export default function CapturePage() {
<TableRow>
<TableHead className="w-10">#</TableHead>
<TableHead className="w-40">{t('admin.capture.time')}</TableHead>
<TableHead className="text-end">{t('admin.capture.duration')}</TableHead>
<TableHead>{t('admin.capture.sourceCol')}</TableHead>
<TableHead>{t('admin.capture.adapter')}</TableHead>
<TableHead>{t('admin.capture.inboundProtocol')}</TableHead>
Expand All @@ -396,6 +407,9 @@ export default function CapturePage() {
<TableCell className="font-mono text-[10.5px] whitespace-nowrap text-muted-foreground">
{fmtTime(e.timestamp)}
</TableCell>
<TableCell className="text-end font-mono text-[10.5px] whitespace-nowrap text-muted-foreground">
{fmtDuration(e.durationMs)}
</TableCell>
<TableCell className="text-[11.5px] text-foreground">{e.source}</TableCell>
<TableCell className="text-[11.5px] text-muted-foreground">{e.adapterName || '—'}</TableCell>
<TableCell className="font-mono text-[11px] text-muted-foreground">{e.protocol}</TableCell>
Expand All @@ -422,7 +436,7 @@ export default function CapturePage() {

{filtered.length === 0 && (
<TableRow>
<TableCell colSpan={11} className="py-12 text-center text-[13px] text-muted-foreground">
<TableCell colSpan={12} className="py-12 text-center text-[13px] text-muted-foreground">
{t('admin.capture.empty')}
</TableCell>
</TableRow>
Expand Down
1 change: 1 addition & 0 deletions locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@
"sourceProxy": "Proxy",
"filterAll": "All",
"time": "Time",
"duration": "Duration",
"sourceCol": "Source",
"adapter": "Adapter",
"inboundProtocol": "Inbound Protocol",
Expand Down
1 change: 1 addition & 0 deletions locales/zh/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@
"sourceProxy": "代理",
"filterAll": "全部",
"time": "时间",
"duration": "耗时",
"sourceCol": "来源",
"adapter": "适配器",
"inboundProtocol": "入站协议",
Expand Down
6 changes: 6 additions & 0 deletions src/proxy/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export interface CaptureMeta {
export interface CaptureEntry extends CaptureMeta {
id: number
timestamp: number
/** 从创建抓包记录到响应完整写回客户端的耗时(毫秒) */
durationMs: number | null
/** 来源:proxy(代理入口)或适配器名称 */
source: string
/** 代理端协议 */
Expand Down Expand Up @@ -92,6 +94,7 @@ export class CaptureBuffer {
const entry: CaptureEntry = {
id: this.nextId++,
timestamp: Date.now(),
durationMs: null,
source,
protocol,
model,
Expand Down Expand Up @@ -123,6 +126,9 @@ export class CaptureBuffer {
const entry = this.entryMap.get(pairId)
if (!entry) return
entry[field] = data
if (field === 'responseOut') {
entry.durationMs = Math.max(0, Date.now() - entry.timestamp)
}
this.notifySubscribers(entry)
}

Expand Down
2 changes: 2 additions & 0 deletions src/proxy/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,8 @@ export async function forwardRequest(
'Content-Type': response.headers.get('content-type') ?? 'application/json',
'Access-Control-Allow-Origin': '*',
})
// 同协议响应虽无需转换,仍需记录实际写回客户端的正文并结算抓包耗时。
req.capture?.updateRequest(req.pairId!, 'responseOut', text)
res.end(text)
return
}
Expand Down
1 change: 1 addition & 0 deletions src/types/i18n.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export type TranslationKey =
| 'admin.adapters.updated'
| 'admin.capture.adapter'
| 'admin.capture.copyRaw'
| 'admin.capture.duration'
| 'admin.capture.empty'
| 'admin.capture.entryCount'
| 'admin.capture.filterAll'
Expand Down
46 changes: 46 additions & 0 deletions test/proxy/capture.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import assert from 'node:assert'
import { EventEmitter } from 'node:events'
import type { ServerResponse } from 'node:http'
import { CaptureBuffer } from '../../src/proxy/capture.js'
import { forwardRequest } from '../../src/proxy/provider.js'

function fakeRes(overrides: Partial<{ destroyed: boolean; writableEnded: boolean; writable: boolean }> = {}): ServerResponse {
const ee = new EventEmitter() as any
Expand Down Expand Up @@ -31,6 +32,7 @@ describe('proxy/capture', () => {
assert.strictEqual(all[0].protocol, 'anthropic')
assert.strictEqual(all[0].model, 'claude-3')
assert.strictEqual(all[0].pairId, 1)
assert.strictEqual(all[0].durationMs, null)
assert.strictEqual(all[0].requestIn, null)
})

Expand All @@ -43,6 +45,7 @@ describe('proxy/capture', () => {
const entry = cap.getAll()[0]
assert.strictEqual(entry.requestIn, '{"model":"gpt-4"}')
assert.strictEqual(entry.responseOut, '{"choices":[]}')
assert.ok(entry.durationMs !== null && entry.durationMs >= 0)
// 未更新的字段仍为 null
assert.strictEqual(entry.requestOut, null)
assert.strictEqual(entry.responseIn, null)
Expand All @@ -54,6 +57,49 @@ describe('proxy/capture', () => {
cap.updateRequest(999, 'requestIn', 'data')
})

it('非流式同协议响应同时记录双向正文和耗时', async () => {
const responseText = JSON.stringify({
id: 'chatcmpl-capture',
choices: [{ message: { role: 'assistant', content: 'hi' } }],
})
const fetchMock = mock.method(globalThis, 'fetch', async () => new Response(responseText, {
status: 200,
headers: { 'content-type': 'application/json' },
}))
const cap = new CaptureBuffer(100)

try {
const pairId = cap.startRequest('proxy', 'openai', 'gpt-4')
const res = fakeRes()
let clientBody = ''
res.end = ((chunk?: unknown) => {
clientBody = chunk == null ? '' : String(chunk)
return res
}) as ServerResponse['end']

await forwardRequest({
url: 'https://api.openai.com/v1/chat/completions',
method: 'POST',
headers: { 'content-type': 'application/json' },
body: { model: 'gpt-4', messages: [{ role: 'user', content: 'hello' }] },
crossProtocol: false,
inboundType: 'openai',
upstreamType: 'openai',
capture: cap,
pairId,
}, res)

const entry = cap.getAll()[0]
assert.strictEqual(entry.responseIn, responseText)
assert.strictEqual(entry.responseOut, responseText)
assert.strictEqual(clientBody, responseText)
assert.ok(entry.durationMs !== null && entry.durationMs >= 0)
} finally {
fetchMock.mock.restore()
cap.destroy()
}
})

it('startRequest 携带 meta 信息', () => {
const cap = new CaptureBuffer(100)
cap.startRequest('adapter', 'anthropic', 'claude-3', {
Expand Down
Loading